OSDN Git Service

2004-08-31 Richard Kenner <kenner@vlsi1.ultra.nyu.edu>
[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-2004 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 Unix and Windows
93 @set FILE gnat_ugn_unw
94 @end ifset
95
96 @ifset vms
97 @set PLATFORM OpenVMS Alpha
98 @set FILE gnat_ugn_vms
99 @end ifset
100
101
102
103 @settitle @value{EDITION} User's Guide for Native Platforms / @value{PLATFORM}
104 @dircategory GNU Ada tools
105 @direntry
106 * @value{EDITION} User's Guide (@value{FILE}) for Native Platforms / @value{PLATFORM}
107 @end direntry
108
109 @include gcc-common.texi
110
111 @setchapternewpage odd
112 @syncodeindex fn cp
113 @c %**end of header
114
115 @copying
116 Copyright @copyright{} 1995-2004, Free Software Foundation
117
118 Permission is granted to copy, distribute and/or modify this document
119 under the terms of the GNU Free Documentation License, Version 1.2
120 or any later version published by the Free Software Foundation;
121 with the Invariant Sections being ``GNU Free Documentation License'', with the
122 Front-Cover Texts being
123 ``GNAT User's Guide for Native Platforms / @value{PLATFORM}'',
124 and with no Back-Cover Texts.
125 A copy of the license is included in the section entitled
126 ``GNU Free Documentation License''.
127 @end copying
128
129 @titlepage
130
131 @title @value{EDITION} User's Guide
132 @center @titlefont{for Native Platforms}
133 @sp 1
134
135 @flushright
136 @titlefont{@i{@value{PLATFORM}}}
137 @end flushright
138 @sp 2
139
140 @subtitle GNAT, The GNU Ada 95 Compiler
141 @subtitle GCC version @value{version-GCC}
142
143 @author Ada Core Technologies, Inc.
144
145 @page
146 @vskip 0pt plus 1filll
147
148 @insertcopying
149
150 @end titlepage
151
152
153 @ifnottex
154 @node Top, About This Guide, (dir), (dir)
155 @top @value{EDITION} User's Guide
156
157 @noindent
158 @value{EDITION} User's Guide for Native Platforms / @value{PLATFORM}
159
160 @noindent
161 GNAT, The GNU Ada 95 Compiler@*
162 GCC version @value{version-GCC}@*
163
164 @noindent
165 Ada Core Technologies, Inc.@*
166
167 @menu
168 * About This Guide::
169 * Getting Started with GNAT::
170 * The GNAT Compilation Model::
171 * Compiling Using gcc::
172 * Binding Using gnatbind::
173 * Linking Using gnatlink::
174 * The GNAT Make Program gnatmake::
175 * Improving Performance::
176 * Renaming Files Using gnatchop::
177 * Configuration Pragmas::
178 * Handling Arbitrary File Naming Conventions Using gnatname::
179 * GNAT Project Manager::
180 * The Cross-Referencing Tools gnatxref and gnatfind::
181 * The GNAT Pretty-Printer gnatpp::
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 * Finding Memory Problems::
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 Ada 83 Programs::
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
325 Improving Performance
326 * Performance Considerations::
327 * Reducing the Size of Ada Executables with gnatelim::
328
329 Performance Considerations
330 * Controlling Run-Time Checks::
331 * Use of Restrictions::
332 * Optimization Levels::
333 * Debugging Optimized Code::
334 * Inlining of Subprograms::
335 * Optimization and Strict Aliasing::
336 @ifset vms
337 * Coverage Analysis::
338 @end ifset
339
340 Reducing the Size of Ada Executables with gnatelim
341 * About gnatelim::
342 * Running gnatelim::
343 * Correcting the List of Eliminate Pragmas::
344 * Making Your Executables Smaller::
345 * Summary of the gnatelim Usage Cycle::
346
347 Renaming Files Using gnatchop
348
349 * Handling Files with Multiple Units::
350 * Operating gnatchop in Compilation Mode::
351 * Command Line for gnatchop::
352 * Switches for gnatchop::
353 * Examples of gnatchop Usage::
354
355 Configuration Pragmas
356
357 * Handling of Configuration Pragmas::
358 * The Configuration Pragmas Files::
359
360 Handling Arbitrary File Naming Conventions Using gnatname
361
362 * Arbitrary File Naming Conventions::
363 * Running gnatname::
364 * Switches for gnatname::
365 * Examples of gnatname Usage::
366
367 GNAT Project Manager
368
369 * Introduction::
370 * Examples of Project Files::
371 * Project File Syntax::
372 * Objects and Sources in Project Files::
373 * Importing Projects::
374 * Project Extension::
375 * External References in Project Files::
376 * Packages in Project Files::
377 * Variables from Imported Projects::
378 * Naming Schemes::
379 * Library Projects::
380 * Using Third-Party Libraries through Projects::
381 * Stand-alone Library Projects::
382 * Switches Related to Project Files::
383 * Tools Supporting Project Files::
384 * An Extended Example::
385 * Project File Complete Syntax::
386
387
388 The Cross-Referencing Tools gnatxref and gnatfind
389
390 * gnatxref Switches::
391 * gnatfind Switches::
392 * Project Files for gnatxref and gnatfind::
393 * Regular Expressions in gnatfind and gnatxref::
394 * Examples of gnatxref Usage::
395 * Examples of gnatfind Usage::
396
397
398 The GNAT Pretty-Printer gnatpp
399
400 * Switches for gnatpp::
401 * Formatting Rules::
402
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 Finding Memory Problems
456
457 @ifclear vms
458 * The gnatmem Tool::
459 @end ifclear
460 * The GNAT Debug Pool Facility::
461
462 @ifclear vms
463 The gnatmem Tool
464
465 * Running gnatmem::
466 * Switches for gnatmem::
467 * Example of gnatmem Usage::
468 @end ifclear
469
470 The GNAT Debug Pool Facility
471
472 Creating Sample Bodies Using gnatstub
473
474 * Running gnatstub::
475 * Switches for gnatstub::
476
477 Other Utility Programs
478
479 * Using Other Utility Programs with GNAT::
480 * The External Symbol Naming Scheme of GNAT::
481 @ifclear vms
482 * Ada Mode for Glide::
483 @end ifclear
484 * Converting Ada Files to html with gnathtml::
485
486 Running and Debugging Ada Programs
487
488 * The GNAT Debugger GDB::
489 * Running GDB::
490 * Introduction to GDB Commands::
491 * Using Ada Expressions::
492 * Calling User-Defined Subprograms::
493 * Using the Next Command in a Function::
494 * Ada Exceptions::
495 * Ada Tasks::
496 * Debugging Generic Units::
497 * GNAT Abnormal Termination or Failure to Terminate::
498 * Naming Conventions for GNAT Source Files::
499 * Getting Internal Debugging Information::
500 * Stack Traceback::
501
502 @ifset vms
503 * LSE::
504 @end ifset
505
506 @ifset vms
507 Compatibility with DEC Ada
508
509 * Ada 95 Compatibility::
510 * Differences in the Definition of Package System::
511 * Language-Related Features::
512 * The Package STANDARD::
513 * The Package SYSTEM::
514 * Tasking and Task-Related Features::
515 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
516 * Pragmas and Pragma-Related Features::
517 * Library of Predefined Units::
518 * Bindings::
519 * Main Program Definition::
520 * Implementation-Defined Attributes::
521 * Compiler and Run-Time Interfacing::
522 * Program Compilation and Library Management::
523 * Input-Output::
524 * Implementation Limits::
525 * Tools::
526
527 Language-Related Features
528
529 * Integer Types and Representations::
530 * Floating-Point Types and Representations::
531 * Pragmas Float_Representation and Long_Float::
532 * Fixed-Point Types and Representations::
533 * Record and Array Component Alignment::
534 * Address Clauses::
535 * Other Representation Clauses::
536
537 Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
538
539 * Assigning Task IDs::
540 * Task IDs and Delays::
541 * Task-Related Pragmas::
542 * Scheduling and Task Priority::
543 * The Task Stack::
544 * External Interrupts::
545
546 Pragmas and Pragma-Related Features
547
548 * Restrictions on the Pragma INLINE::
549 * Restrictions on the Pragma INTERFACE::
550 * Restrictions on the Pragma SYSTEM_NAME::
551
552 Library of Predefined Units
553
554 * Changes to DECLIB::
555
556 Bindings
557
558 * Shared Libraries and Options Files::
559 * Interfaces to C::
560 @end ifset
561
562 Platform-Specific Information for the Run-Time Libraries
563
564 * Summary of Run-Time Configurations::
565 * Specifying a Run-Time Library::
566 * Choosing between Native and FSU Threads Libraries::
567 * Choosing the Scheduling Policy::
568 * Solaris-Specific Considerations::
569 * IRIX-Specific Considerations::
570 * Linux-Specific Considerations::
571 * AIX-Specific Considerations::
572
573 Example of Binder Output File
574
575 Elaboration Order Handling in GNAT
576
577 * Elaboration Code in Ada 95::
578 * Checking the Elaboration Order in Ada 95::
579 * Controlling the Elaboration Order in Ada 95::
580 * Controlling Elaboration in GNAT - Internal Calls::
581 * Controlling Elaboration in GNAT - External Calls::
582 * Default Behavior in GNAT - Ensuring Safety::
583 * Treatment of Pragma Elaborate::
584 * Elaboration Issues for Library Tasks::
585 * Mixing Elaboration Models::
586 * What to Do If the Default Elaboration Behavior Fails::
587 * Elaboration for Access-to-Subprogram Values::
588 * Summary of Procedures for Elaboration Control::
589 * Other Elaboration Order Considerations::
590
591 Inline Assembler
592
593 * Basic Assembler Syntax::
594 * A Simple Example of Inline Assembler::
595 * Output Variables in Inline Assembler::
596 * Input Variables in Inline Assembler::
597 * Inlining Inline Assembler Code::
598 * Other Asm Functionality::
599 * A Complete Example::
600
601 Compatibility and Porting Guide
602
603 * Compatibility with Ada 83::
604 * Implementation-dependent characteristics::
605 * Compatibility with DEC Ada 83::
606 * Compatibility with Other Ada 95 Systems::
607 * Representation Clauses::
608
609 @ifset unw
610 Microsoft Windows Topics
611
612 * Using GNAT on Windows::
613 * CONSOLE and WINDOWS subsystems::
614 * Temporary Files::
615 * Mixed-Language Programming on Windows::
616 * Windows Calling Conventions::
617 * Introduction to Dynamic Link Libraries (DLLs)::
618 * Using DLLs with GNAT::
619 * Building DLLs with GNAT::
620 * GNAT and Windows Resources::
621 * Debugging a DLL::
622 * GNAT and COM/DCOM Objects::
623 @end ifset
624
625
626 * Index::
627 @end menu
628 @end ifnottex
629
630 @node About This Guide
631 @unnumbered About This Guide
632
633 @noindent
634 @ifset vms
635 This guide describes the use of of @value{EDITION},
636 a full language compiler for the Ada
637 95 programming language, implemented on HP OpenVMS Alpha platforms.
638 @end ifset
639 @ifclear vms
640 This guide describes the use of @value{EDITION},
641 a compiler and software development
642 toolset for the full Ada 95 programming language.
643 @end ifclear
644 It describes the features of the compiler and tools, and details
645 how to use them to build Ada 95 applications.
646
647 @ifset PROEDITION
648 For ease of exposition, ``GNAT Pro'' will be referred to simply as
649 ``GNAT'' in the remainder of this document.
650 @end ifset
651
652
653
654 @menu
655 * What This Guide Contains::
656 * What You Should Know before Reading This Guide::
657 * Related Information::
658 * Conventions::
659 @end menu
660
661 @node What This Guide Contains
662 @unnumberedsec What This Guide Contains
663
664 @noindent
665 This guide contains the following chapters:
666 @itemize @bullet
667
668 @item
669 @ref{Getting Started with GNAT}, describes how to get started compiling
670 and running Ada programs with the GNAT Ada programming environment.
671 @item
672 @ref{The GNAT Compilation Model}, describes the compilation model used
673 by GNAT.
674
675 @item
676 @ref{Compiling Using gcc}, describes how to compile
677 Ada programs with @code{gcc}, the Ada compiler.
678
679 @item
680 @ref{Binding Using gnatbind}, describes how to
681 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
682 utility.
683
684 @item
685 @ref{Linking Using gnatlink},
686 describes @code{gnatlink}, a
687 program that provides for linking using the GNAT run-time library to
688 construct a program. @code{gnatlink} can also incorporate foreign language
689 object units into the executable.
690
691 @item
692 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
693 utility that automatically determines the set of sources
694 needed by an Ada compilation unit, and executes the necessary compilations
695 binding and link.
696
697 @item
698 @ref{Improving Performance}, shows various techniques for making your
699 Ada program run faster or take less space.
700 It discusses the effect of the compiler's optimization switch and
701 also describes the @command{gnatelim} tool.
702
703 @item
704 @ref{Renaming Files Using gnatchop}, describes
705 @code{gnatchop}, a utility that allows you to preprocess a file that
706 contains Ada source code, and split it into one or more new files, one
707 for each compilation unit.
708
709 @item
710 @ref{Configuration Pragmas}, describes the configuration pragmas
711 handled by GNAT.
712
713 @item
714 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
715 shows how to override the default GNAT file naming conventions,
716 either for an individual unit or globally.
717
718 @item
719 @ref{GNAT Project Manager}, describes how to use project files
720 to organize large projects.
721
722 @item
723 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
724 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
725 way to navigate through sources.
726
727 @item
728 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
729 version of an Ada source file with control over casing, indentation,
730 comment placement, and other elements of program presentation style.
731
732
733 @item
734 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
735 file name krunching utility, used to handle shortened
736 file names on operating systems with a limit on the length of names.
737
738 @item
739 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
740 preprocessor utility that allows a single source file to be used to
741 generate multiple or parameterized source files, by means of macro
742 substitution.
743
744 @ifset vms
745 @item
746 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
747 a tool for rebuilding the GNAT run time with user-supplied
748 configuration pragmas.
749 @end ifset
750
751 @item
752 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
753 utility that displays information about compiled units, including dependences
754 on the corresponding sources files, and consistency of compilations.
755
756 @item
757 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
758 to delete files that are produced by the compiler, binder and linker.
759
760 @ifclear vms
761 @item
762 @ref{GNAT and Libraries}, describes the process of creating and using
763 Libraries with GNAT. It also describes how to recompile the GNAT run-time
764 library.
765
766 @item
767 @ref{Using the GNU make Utility}, describes some techniques for using
768 the GNAT toolset in Makefiles.
769 @end ifclear
770
771 @item
772 @ref{Finding Memory Problems}, describes
773 @ifclear vms
774 @command{gnatmem}, a utility that monitors dynamic allocation and deallocation
775 and helps detect ``memory leaks'', and
776 @end ifclear
777 the GNAT Debug Pool facility, which helps detect incorrect memory references.
778
779 @item
780 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
781 a utility that generates empty but compilable bodies for library units.
782
783 @item
784 @ref{Other Utility Programs}, discusses several other GNAT utilities,
785 including @code{gnathtml}.
786
787 @item
788 @ref{Running and Debugging Ada Programs}, describes how to run and debug
789 Ada programs.
790
791 @ifset vms
792 @item
793 @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
794 DEC Ada 83 @footnote{``DEC Ada'' refers to the legacy product originally
795 developed by Digital Equipment Corporation and currently supported by HP.}
796 for OpenVMS Alpha.
797 @end ifset
798
799 @item
800 @ref{Platform-Specific Information for the Run-Time Libraries},
801 describes the various run-time
802 libraries supported by GNAT on various platforms and explains how to
803 choose a particular library.
804
805 @item
806 @ref{Example of Binder Output File}, shows the source code for the binder
807 output file for a sample program.
808
809 @item
810 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
811 you deal with elaboration order issues.
812
813 @item
814 @ref{Inline Assembler}, shows how to use the inline assembly facility
815 in an Ada program.
816
817 @item
818 @ref{Compatibility and Porting Guide}, includes sections on compatibility
819 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
820 in porting code from other environments.
821
822 @ifset unw
823 @item
824 @ref{Microsoft Windows Topics}, presents information relevant to the
825 Microsoft Windows platform.
826 @end ifset
827 @end itemize
828
829
830 @c *************************************************
831 @node What You Should Know before Reading This Guide
832 @c *************************************************
833 @unnumberedsec What You Should Know before Reading This Guide
834
835 @cindex Ada 95 Language Reference Manual
836 @noindent
837 This user's guide assumes that you are familiar with Ada 95 language, as
838 described in the International Standard ANSI/ISO/IEC-8652:1995, January
839 1995.
840
841 @node Related Information
842 @unnumberedsec Related Information
843
844 @noindent
845 For further information about related tools, refer to the following
846 documents:
847
848 @itemize @bullet
849 @item
850 @cite{GNAT Reference Manual}, which contains all reference
851 material for the GNAT implementation of Ada 95.
852
853 @ifset unw
854 @item
855 @cite{Using the GNAT Programming System}, which describes the GPS
856 integrated development environment.
857
858 @item
859 @cite{GNAT Programming System Tutorial}, which introduces the
860 main GPS features through examples.
861 @end ifset
862
863 @item
864 @cite{Ada 95 Language Reference Manual}, which contains all reference
865 material for the Ada 95 programming language.
866
867 @item
868 @cite{Debugging with GDB}
869 @ifset vms
870 , located in the GNU:[DOCS] directory,
871 @end ifset
872 contains all details on the use of the GNU source-level debugger.
873
874 @item
875 @cite{GNU Emacs Manual}
876 @ifset vms
877 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
878 @end ifset
879 contains full information on the extensible editor and programming
880 environment Emacs.
881
882 @end itemize
883
884 @c **************
885 @node Conventions
886 @unnumberedsec Conventions
887 @cindex Conventions
888 @cindex Typographical conventions
889
890 @noindent
891 Following are examples of the typographical and graphic conventions used
892 in this guide:
893
894 @itemize @bullet
895 @item
896 @code{Functions}, @code{utility program names}, @code{standard names},
897 and @code{classes}.
898
899 @item
900 @samp{Option flags}
901
902 @item
903 @file{File Names}, @file{button names}, and @file{field names}.
904
905 @item
906 @var{Variables}.
907
908 @item
909 @emph{Emphasis}.
910
911 @item
912 [optional information or parameters]
913
914 @item
915 Examples are described by text
916 @smallexample
917 and then shown this way.
918 @end smallexample
919 @end itemize
920
921 @noindent
922 Commands that are entered by the user are preceded in this manual by the
923 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
924 uses this sequence as a prompt, then the commands will appear exactly as
925 you see them in the manual. If your system uses some other prompt, then
926 the command will appear with the @code{$} replaced by whatever prompt
927 character you are using.
928
929 @ifset unw
930 Full file names are shown with the ``@code{/}'' character
931 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
932 If you are using GNAT on a Windows platform, please note that
933 the ``@code{\}'' character should be used instead.
934 @end ifset
935
936
937
938 @c ****************************
939 @node Getting Started with GNAT
940 @chapter Getting Started with GNAT
941
942 @noindent
943 This chapter describes some simple ways of using GNAT to build
944 executable Ada programs.
945 @ifset unw
946 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
947 show how to use the command line environment.
948 @ref{Introduction to Glide and GVD}, provides a brief
949 introduction to the visually-oriented IDE for GNAT.
950 Supplementing Glide on some platforms is GPS, the
951 GNAT Programming System, which offers a richer graphical
952 ``look and feel'', enhanced configurability, support for
953 development in other programming language, comprehensive
954 browsing features, and many other capabilities.
955 For information on GPS please refer to
956 @cite{Using the GNAT Programming System}.
957 @end ifset
958
959 @menu
960 * Running GNAT::
961 * Running a Simple Ada Program::
962 * Running a Program with Multiple Units::
963 * Using the gnatmake Utility::
964 @ifset vms
965 * Editing with Emacs::
966 @end ifset
967 @ifclear vms
968 * Introduction to GPS::
969 * Introduction to Glide and GVD::
970 @end ifclear
971 @end menu
972
973 @node Running GNAT
974 @section Running GNAT
975
976 @noindent
977 Three steps are needed to create an executable file from an Ada source
978 file:
979
980 @enumerate
981 @item
982 The source file(s) must be compiled.
983 @item
984 The file(s) must be bound using the GNAT binder.
985 @item
986 All appropriate object files must be linked to produce an executable.
987 @end enumerate
988
989 @noindent
990 All three steps are most commonly handled by using the @code{gnatmake}
991 utility program that, given the name of the main program, automatically
992 performs the necessary compilation, binding and linking steps.
993
994
995 @node Running a Simple Ada Program
996 @section Running a Simple Ada Program
997
998 @noindent
999 Any text editor may be used to prepare an Ada program.
1000 @ifclear vms
1001 If @code{Glide} is
1002 used, the optional Ada mode may be helpful in laying out the program.
1003 @end ifclear
1004 The
1005 program text is a normal text file. We will suppose in our initial
1006 example that you have used your editor to prepare the following
1007 standard format text file:
1008
1009 @smallexample @c ada
1010 @cartouche
1011 with Ada.Text_IO; use Ada.Text_IO;
1012 procedure Hello is
1013 begin
1014    Put_Line ("Hello WORLD!");
1015 end Hello;
1016 @end cartouche
1017 @end smallexample
1018
1019 @noindent
1020 This file should be named @file{hello.adb}.
1021 With the normal default file naming conventions, GNAT requires
1022 that each file
1023 contain a single compilation unit whose file name is the
1024 unit name,
1025 with periods replaced by hyphens; the
1026 extension is @file{ads} for a
1027 spec and @file{adb} for a body.
1028 You can override this default file naming convention by use of the
1029 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1030 Alternatively, if you want to rename your files according to this default
1031 convention, which is probably more convenient if you will be using GNAT
1032 for all your compilations, then the @code{gnatchop} utility
1033 can be used to generate correctly-named source files
1034 (@pxref{Renaming Files Using gnatchop}).
1035
1036 You can compile the program using the following command (@code{$} is used
1037 as the command prompt in the examples in this document):
1038
1039 @smallexample
1040 $ gcc -c hello.adb
1041 @end smallexample
1042
1043 @noindent
1044 @code{gcc} is the command used to run the compiler. This compiler is
1045 capable of compiling programs in several languages, including Ada 95 and
1046 C. It assumes that you have given it an Ada program if the file extension is
1047 either @file{.ads} or @file{.adb}, and it will then call
1048 the GNAT compiler to compile the specified file.
1049
1050 @ifclear vms
1051 The @option{-c} switch is required. It tells @command{gcc} to only do a
1052 compilation. (For C programs, @command{gcc} can also do linking, but this
1053 capability is not used directly for Ada programs, so the @option{-c}
1054 switch must always be present.)
1055 @end ifclear
1056
1057 This compile command generates a file
1058 @file{hello.o}, which is the object
1059 file corresponding to your Ada program. It also generates
1060 an ``Ada Library Information'' file @file{hello.ali},
1061 which contains additional information used to check
1062 that an Ada program is consistent.
1063 To build an executable file,
1064 use @code{gnatbind} to bind the program
1065 and @code{gnatlink} to link it. The
1066 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1067 @file{ALI} file, but the default extension of @file{.ali} can
1068 be omitted. This means that in the most common case, the argument
1069 is simply the name of the main program:
1070
1071 @smallexample
1072 $ gnatbind hello
1073 $ gnatlink hello
1074 @end smallexample
1075
1076 @noindent
1077 A simpler method of carrying out these steps is to use
1078 @command{gnatmake},
1079 a master program that invokes all the required
1080 compilation, binding and linking tools in the correct order. In particular,
1081 @command{gnatmake} automatically recompiles any sources that have been
1082 modified since they were last compiled, or sources that depend
1083 on such modified sources, so that ``version skew'' is avoided.
1084 @cindex Version skew (avoided by @command{gnatmake})
1085
1086 @smallexample
1087 $ gnatmake hello.adb
1088 @end smallexample
1089
1090 @noindent
1091 The result is an executable program called @file{hello}, which can be
1092 run by entering:
1093
1094 @c The following should be removed (BMB 2001-01-23)
1095 @c @smallexample
1096 @c $ ^./hello^$ RUN HELLO^
1097 @c @end smallexample
1098
1099 @smallexample
1100 $ hello
1101 @end smallexample
1102
1103 @noindent
1104 assuming that the current directory is on the search path
1105 for executable programs.
1106
1107 @noindent
1108 and, if all has gone well, you will see
1109
1110 @smallexample
1111 Hello WORLD!
1112 @end smallexample
1113
1114 @noindent
1115 appear in response to this command.
1116
1117
1118 @c ****************************************
1119 @node Running a Program with Multiple Units
1120 @section Running a Program with Multiple Units
1121
1122 @noindent
1123 Consider a slightly more complicated example that has three files: a
1124 main program, and the spec and body of a package:
1125
1126 @smallexample @c ada
1127 @cartouche
1128 @group
1129 package Greetings is
1130    procedure Hello;
1131    procedure Goodbye;
1132 end Greetings;
1133
1134 with Ada.Text_IO; use Ada.Text_IO;
1135 package body Greetings is
1136    procedure Hello is
1137    begin
1138       Put_Line ("Hello WORLD!");
1139    end Hello;
1140
1141    procedure Goodbye is
1142    begin
1143       Put_Line ("Goodbye WORLD!");
1144    end Goodbye;
1145 end Greetings;
1146 @end group
1147
1148 @group
1149 with Greetings;
1150 procedure Gmain is
1151 begin
1152    Greetings.Hello;
1153    Greetings.Goodbye;
1154 end Gmain;
1155 @end group
1156 @end cartouche
1157 @end smallexample
1158
1159 @noindent
1160 Following the one-unit-per-file rule, place this program in the
1161 following three separate files:
1162
1163 @table @file
1164 @item greetings.ads
1165 spec of package @code{Greetings}
1166
1167 @item greetings.adb
1168 body of package @code{Greetings}
1169
1170 @item gmain.adb
1171 body of main program
1172 @end table
1173
1174 @noindent
1175 To build an executable version of
1176 this program, we could use four separate steps to compile, bind, and link
1177 the program, as follows:
1178
1179 @smallexample
1180 $ gcc -c gmain.adb
1181 $ gcc -c greetings.adb
1182 $ gnatbind gmain
1183 $ gnatlink gmain
1184 @end smallexample
1185
1186 @noindent
1187 Note that there is no required order of compilation when using GNAT.
1188 In particular it is perfectly fine to compile the main program first.
1189 Also, it is not necessary to compile package specs in the case where
1190 there is an accompanying body; you only need to compile the body. If you want
1191 to submit these files to the compiler for semantic checking and not code
1192 generation, then use the
1193 @option{-gnatc} switch:
1194
1195 @smallexample
1196 $ gcc -c greetings.ads -gnatc
1197 @end smallexample
1198
1199 @noindent
1200 Although the compilation can be done in separate steps as in the
1201 above example, in practice it is almost always more convenient
1202 to use the @code{gnatmake} tool. All you need to know in this case
1203 is the name of the main program's source file. The effect of the above four
1204 commands can be achieved with a single one:
1205
1206 @smallexample
1207 $ gnatmake gmain.adb
1208 @end smallexample
1209
1210 @noindent
1211 In the next section we discuss the advantages of using @code{gnatmake} in
1212 more detail.
1213
1214 @c *****************************
1215 @node Using the gnatmake Utility
1216 @section Using the @command{gnatmake} Utility
1217
1218 @noindent
1219 If you work on a program by compiling single components at a time using
1220 @code{gcc}, you typically keep track of the units you modify. In order to
1221 build a consistent system, you compile not only these units, but also any
1222 units that depend on the units you have modified.
1223 For example, in the preceding case,
1224 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1225 you edit @file{greetings.ads}, you must recompile both
1226 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1227 units that depend on @file{greetings.ads}.
1228
1229 @code{gnatbind} will warn you if you forget one of these compilation
1230 steps, so that it is impossible to generate an inconsistent program as a
1231 result of forgetting to do a compilation. Nevertheless it is tedious and
1232 error-prone to keep track of dependencies among units.
1233 One approach to handle the dependency-bookkeeping is to use a
1234 makefile. However, makefiles present maintenance problems of their own:
1235 if the dependencies change as you change the program, you must make
1236 sure that the makefile is kept up-to-date manually, which is also an
1237 error-prone process.
1238
1239 The @code{gnatmake} utility takes care of these details automatically.
1240 Invoke it using either one of the following forms:
1241
1242 @smallexample
1243 $ gnatmake gmain.adb
1244 $ gnatmake ^gmain^GMAIN^
1245 @end smallexample
1246
1247 @noindent
1248 The argument is the name of the file containing the main program;
1249 you may omit the extension. @code{gnatmake}
1250 examines the environment, automatically recompiles any files that need
1251 recompiling, and binds and links the resulting set of object files,
1252 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1253 In a large program, it
1254 can be extremely helpful to use @code{gnatmake}, because working out by hand
1255 what needs to be recompiled can be difficult.
1256
1257 Note that @code{gnatmake}
1258 takes into account all the Ada 95 rules that
1259 establish dependencies among units. These include dependencies that result
1260 from inlining subprogram bodies, and from
1261 generic instantiation. Unlike some other
1262 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1263 found by the compiler on a previous compilation, which may possibly
1264 be wrong when sources change. @code{gnatmake} determines the exact set of
1265 dependencies from scratch each time it is run.
1266
1267 @ifset vms
1268 @node Editing with Emacs
1269 @section Editing with Emacs
1270 @cindex Emacs
1271
1272 @noindent
1273 Emacs is an extensible self-documenting text editor that is available in a
1274 separate VMSINSTAL kit.
1275
1276 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1277 click on the Emacs Help menu and run the Emacs Tutorial.
1278 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1279 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1280
1281 Documentation on Emacs and other tools is available in Emacs under the
1282 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1283 use the middle mouse button to select a topic (e.g. Emacs).
1284
1285 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1286 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1287 get to the Emacs manual.
1288 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1289 prompt.
1290
1291 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1292 which is sufficiently extensible to provide for a complete programming
1293 environment and shell for the sophisticated user.
1294 @end ifset
1295
1296 @ifclear vms
1297 @node Introduction to GPS
1298 @section Introduction to GPS
1299 @cindex GPS (GNAT Programming System)
1300 @cindex GNAT Programming System (GPS)
1301 @noindent
1302 Although the command line interface (@command{gnatmake}, etc.) alone
1303 is sufficient, a graphical Interactive Development
1304 Environment can make it easier for you to compose, navigate, and debug
1305 programs.  This section describes the main features of GPS
1306 (``GNAT Programming System''), the GNAT graphical IDE.
1307 You will see how to use GPS to build and debug an executable, and
1308 you will also learn some of the basics of the GNAT ``project'' facility.
1309
1310 GPS enables you to do much more than is presented here;
1311 e.g., you can produce a call graph, interface to a third-party
1312 Version Control System, and inspect the generated assembly language
1313 for a program.
1314 Indeed, GPS also supports languages other than Ada.
1315 Such additional information, and an explanation of all of the GPS menu
1316 items. may be found in the on-line help, which includes
1317 a user's guide and a tutorial (these are also accessible from the GNAT
1318 startup menu).
1319
1320 @menu
1321 * Building a New Program with GPS::
1322 * Simple Debugging with GPS::
1323 @end menu
1324
1325
1326 @node Building a New Program with GPS
1327 @subsection Building a New Program with GPS
1328 @noindent
1329 GPS invokes the GNAT compilation tools using information
1330 contained in a @emph{project} (also known as a @emph{project file}):
1331 a collection of properties such
1332 as source directories, identities of main subprograms, tool switches, etc.,
1333 and their associated values.
1334 (See @ref{GNAT Project Manager}, for details.)
1335 In order to run GPS, you will need to either create a new project
1336 or else open an existing one.
1337
1338 This section will explain how you can use GPS to create a project,
1339 to associate Ada source files with a project, and to build and run
1340 programs.
1341
1342 @enumerate
1343 @item @emph{Creating a project}
1344
1345 Invoke GPS, either from the command line or the platform's IDE.
1346 After it starts, GPS will display a ``Welcome'' screen with three
1347 radio buttons:
1348
1349 @itemize @bullet
1350 @item
1351 @code{Start with default project in directory}
1352
1353 @item
1354 @code{Create new project with wizard}
1355
1356 @item
1357 @code{Open existing project}
1358 @end itemize
1359
1360 @noindent
1361 Select @code{Create new project with wizard} and press @code{OK}.
1362 A new window will appear.  In the text box labeled with
1363 @code{Enter the name of the project to create}, type @file{sample}
1364 as the project name.
1365 In the next box, browse to choose the directory in which you
1366 would like to create the project file.
1367 After selecting an appropriate directory, press @code{Forward}.
1368
1369 A window will appear with the title
1370 @code{Version Control System Configuration}.
1371 Simply press @code{Forward}.
1372
1373 A window will appear with the title
1374 @code{Please select the source directories for this project}.
1375 The directory that you specified for the project file will be selected
1376 by default as the one to use for sources; simply press @code{Forward}.
1377
1378 A window will appear with the title
1379 @code{Please select the build directory for this project}.
1380 The directory that you specified for the project file will be selected
1381 by default for object files and executables;
1382 simply press @code{Forward}.
1383
1384 A window will appear with the title
1385 @code{Please select the main units for this project}.
1386 You will supply this information later, after creating the source file.
1387 Simply press @code{Forward} for now.
1388
1389 A window will appear with the title
1390 @code{Please select the switches to build the project}.
1391 Press @code{Apply}.  This will create a project file named
1392 @file{sample.prj} in the directory that you had specified.
1393
1394 @item @emph{Creating and saving the source file}
1395
1396 After you create the new project, a GPS window will appear, which is
1397 partitioned into two main sections:
1398
1399 @itemize @bullet
1400 @item
1401 A @emph{Workspace area}, initially greyed out, which you will use for
1402 creating and editing source files
1403
1404 @item
1405 Directly below, a @emph{Messages area}, which initially displays a
1406 ``Welcome'' message.
1407 (If the Messages area is not visible, drag its border upward to expand it.)
1408 @end itemize
1409
1410 @noindent
1411 Select @code{File} on the menu bar, and then the @code{New} command.
1412 The Workspace area will become white, and you can now
1413 enter the source program explicitly.
1414 Type the following text
1415
1416 @smallexample @c ada
1417 @group
1418 with Ada.Text_IO; use Ada.Text_IO;
1419 procedure Hello is
1420 begin
1421   Put_Line("Hello from GPS!");
1422 end Hello;
1423 @end group
1424 @end smallexample
1425
1426 @noindent
1427 Select @code{File}, then @code{Save As}, and enter the source file name
1428 @file{hello.adb}.
1429 The file will be saved in the same directory you specified as the
1430 location of the default project file.
1431
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
1467
1468 @node Simple Debugging with GPS
1469 @subsection Simple Debugging with GPS
1470 @noindent
1471 This section illustrates basic debugging techniques (setting breakpoints,
1472 examining/modifying variables, single stepping).
1473
1474 @enumerate
1475 @item @emph{Opening a project}
1476
1477 Start GPS and select @code{Open existing project}; browse to
1478 specify the project file @file{sample.prj} that you had created in the
1479 earlier example.
1480
1481 @item @emph{Creating a source file}
1482
1483 Select @code{File}, then @code{New}, and type in the following program:
1484
1485 @smallexample @c ada
1486 @group
1487 with Ada.Text_IO; use Ada.Text_IO;
1488 procedure Example is
1489    Line : String (1..80);
1490    N    : Natural;
1491 begin
1492    Put_Line("Type a line of text at each prompt; an empty line to exit");
1493    loop
1494       Put(": ");
1495       Get_Line (Line, N);
1496       Put_Line (Line (1..N) );
1497       exit when N=0;
1498    end loop;
1499 end Example;
1500 @end group
1501 @end smallexample
1502
1503 @noindent
1504 Select @code{File}, then @code{Save as}, and enter the file name
1505 @file{example.adb}.
1506
1507 @item @emph{Updating the project file}
1508
1509 Add @code{Example} as a new main unit for the project:
1510 @enumerate a
1511 @item
1512 Select @code{Project}, then @code{Edit Project Properties}.
1513
1514 @item
1515 Select the @code{Main files} tab, click @code{Add}, then
1516 select the file @file{example.adb} from the list, and
1517 click @code{Open}.
1518 You will see the file name appear in the list of main units
1519
1520 @item
1521 Click @code{OK}
1522 @end enumerate
1523
1524 @item @emph{Building/running the executable}
1525
1526 To build the executable
1527 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1528
1529 Run the program to see its effect (in the Messages area).
1530 Each line that you enter is displayed; an empty line will
1531 cause the loop to exit and the program to terminate.
1532
1533 @item @emph{Debugging the program}
1534
1535 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1536 which are required for debugging, are on by default when you create
1537 a new project.
1538 Thus unless you intentionally remove these settings, you will be able
1539 to debug any program that you develop using GPS.
1540
1541 @enumerate a
1542 @item @emph{Initializing}
1543
1544 Select @code{Debug}, then @code{Initialize}, then @file{example}
1545
1546 @item @emph{Setting a breakpoint}
1547
1548 After performing the initialization step, you will observe a small
1549 icon to the right of each line number.
1550 This serves as a toggle for breakpoints; clicking the icon will
1551 set a breakpoint at the corresponding line (the icon will change to
1552 a red circle with an ``x''), and clicking it again
1553 will remove the breakpoint / reset the icon.
1554
1555 For purposes of this example, set a breakpoint at line 10 (the
1556 statement @code{Put_Line@ (Line@ (1..N));}
1557
1558 @item @emph{Starting program execution}
1559
1560 Select @code{Debug}, then @code{Run}.  When the
1561 @code{Program Arguments} window appears, click @code{OK}.
1562 A console window will appear; enter some line of text,
1563 e.g. @code{abcde}, at the prompt.
1564 The program will pause execution when it gets to the
1565 breakpoint, and the corresponding line is highlighted.
1566
1567 @item @emph{Examining a variable}
1568
1569 Move the mouse over one of the occurrences of the variable @code{N}.
1570 You will see the value (5) displayed, in ``tool tip'' fashion.
1571 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1572 You will see information about @code{N} appear in the @code{Debugger Data}
1573 pane, showing the value as 5.
1574
1575
1576 @item @emph{Assigning a new value to a variable}
1577
1578 Right click on the @code{N} in the @code{Debugger Data} pane, and
1579 select @code{Set value of N}.
1580 When the input window appears, enter the value @code{4} and click
1581 @code{OK}.
1582 This value does not automatically appear in the @code{Debugger Data}
1583 pane; to see it, right click again on the @code{N} in the
1584 @code{Debugger Data} pane and select @code{Update value}.
1585 The new value, 4, will appear in red.
1586
1587 @item @emph{Single stepping}
1588
1589 Select @code{Debug}, then @code{Next}.
1590 This will cause the next statement to be executed, in this case the
1591 call of @code{Put_Line} with the string slice.
1592 Notice in the console window that the displayed string is simply
1593 @code{abcd} and not @code{abcde} which you had entered.
1594 This is because the upper bound of the slice is now 4 rather than 5.
1595
1596 @item @emph{Removing a breakpoint}
1597
1598 Toggle the breakpoint icon at line 10.
1599
1600 @item @emph{Resuming execution from a breakpoint}
1601
1602 Select @code{Debug}, then @code{Continue}.
1603 The program will reach the next iteration of the loop, and
1604 wait for input after displaying the prompt.
1605 This time, just hit the @kbd{Enter} key.
1606 The value of @code{N} will be 0, and the program will terminate.
1607 The console window will disappear.
1608 @end enumerate
1609 @end enumerate
1610
1611
1612 @node Introduction to Glide and GVD
1613 @section Introduction to Glide and GVD
1614 @cindex Glide
1615 @cindex GVD
1616 @noindent
1617 This section describes the main features of Glide,
1618 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1619 the GNU Visual Debugger.
1620 These tools may be present in addition to, or in place of, GPS on some
1621 platforms.
1622 Additional information on Glide and GVD may be found
1623 in the on-line help for these tools.
1624
1625 @menu
1626 * Building a New Program with Glide::
1627 * Simple Debugging with GVD::
1628 * Other Glide Features::
1629 @end menu
1630
1631 @node Building a New Program with Glide
1632 @subsection Building a New Program with Glide
1633 @noindent
1634 The simplest way to invoke Glide is to enter @command{glide}
1635 at the command prompt.  It will generally be useful to issue this
1636 as a background command, thus allowing you to continue using
1637 your command window for other purposes while Glide is running:
1638
1639 @smallexample
1640 $ glide&
1641 @end smallexample
1642
1643 @noindent
1644 Glide will start up with an initial screen displaying the top-level menu items
1645 as well as some other information.  The menu selections are as follows
1646 @itemize @bullet
1647 @item @code{Buffers}
1648 @item @code{Files}
1649 @item @code{Tools}
1650 @item @code{Edit}
1651 @item @code{Search}
1652 @item @code{Mule}
1653 @item @code{Glide}
1654 @item @code{Help}
1655 @end itemize
1656
1657 @noindent
1658 For this introductory example, you will need to create a new Ada source file.
1659 First, select the @code{Files} menu.  This will pop open a menu with around
1660 a dozen or so items.  To create a file, select the @code{Open file...} choice.
1661 Depending on the platform, you may see a pop-up window where you can browse
1662 to an appropriate directory and then enter the file name, or else simply
1663 see a line at the bottom of the Glide window where you can likewise enter
1664 the file name.  Note that in Glide, when you attempt to open a non-existent
1665 file, the effect is to create a file with that name.  For this example enter
1666 @file{hello.adb} as the name of the file.
1667
1668 A new buffer will now appear, occupying the entire Glide window,
1669 with the file name at the top.  The menu selections are slightly different
1670 from the ones you saw on the opening screen; there is an @code{Entities} item,
1671 and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses
1672 the file extension to identify the source language, so @file{adb} indicates
1673 an Ada source file.
1674
1675 You will enter some of the source program lines explicitly,
1676 and use the syntax-oriented template mechanism to enter other lines.
1677 First, type the following text:
1678 @smallexample
1679 with Ada.Text_IO; use Ada.Text_IO;
1680 procedure Hello is
1681 begin
1682 @end smallexample
1683
1684 @noindent
1685 Observe that Glide uses different colors to distinguish reserved words from
1686 identifiers.  Also, after the @code{procedure Hello is} line, the cursor is
1687 automatically indented in anticipation of declarations.  When you enter
1688 @code{begin}, Glide recognizes that there are no declarations and thus places
1689 @code{begin} flush left.  But after the @code{begin} line the cursor is again
1690 indented, where the statement(s) will be placed.
1691
1692 The main part of the program will be a @code{for} loop.  Instead of entering
1693 the text explicitly, however, use a statement template.  Select the @code{Ada}
1694 item on the top menu bar, move the mouse to the @code{Statements} item,
1695 and you will see a large selection of alternatives.  Choose @code{for loop}.
1696 You will be prompted (at the bottom of the buffer) for a loop name;
1697 simply press the @key{Enter} key since a loop name is not needed.
1698 You should see the beginning of a @code{for} loop appear in the source
1699 program window.  You will now be prompted for the name of the loop variable;
1700 enter a line with the identifier @code{ind} (lower case).  Note that,
1701 by default, Glide capitalizes the name (you can override such behavior
1702 if you wish, although this is outside the scope of this introduction).
1703 Next, Glide prompts you for the loop range; enter a line containing
1704 @code{1..5} and you will see this also appear in the source program,
1705 together with the remaining elements of the @code{for} loop syntax.
1706
1707 Next enter the statement (with an intentional error, a missing semicolon)
1708 that will form the body of the loop:
1709 @smallexample
1710 Put_Line("Hello, World" & Integer'Image(I))
1711 @end smallexample
1712
1713 @noindent
1714 Finally, type @code{end Hello;} as the last line in the program.
1715 Now save the file: choose the @code{File} menu item, and then the
1716 @code{Save buffer} selection.  You will see a message at the bottom
1717 of the buffer confirming that the file has been saved.
1718
1719 You are now ready to attempt to build the program.  Select the @code{Ada}
1720 item from the top menu bar.  Although we could choose simply to compile
1721 the file, we will instead attempt to do a build (which invokes
1722 @command{gnatmake}) since, if the compile is successful, we want to build
1723 an executable.  Thus select @code{Ada build}.  This will fail because of the
1724 compilation error, and you will notice that the Glide window has been split:
1725 the top window contains the source file, and the bottom window contains the
1726 output from the GNAT tools. Glide allows you to navigate from a compilation
1727 error to the source file position corresponding to the error: click the
1728 middle mouse button (or simultaneously press the left and right buttons,
1729 on a two-button mouse) on the diagnostic line in the tool window.  The
1730 focus will shift to the source window, and the cursor will be positioned
1731 on the character at which the error was detected.
1732
1733 Correct the error: type in a semicolon to terminate the statement.
1734 Although you can again save the file explicitly, you can also simply invoke
1735 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1736 This time the build will succeed; the tool output window shows you the
1737 options that are supplied by default.  The GNAT tools' output (e.g.
1738 object and ALI files, executable) will go in the directory from which
1739 Glide was launched.
1740
1741 To execute the program, choose @code{Ada} and then @code{Run}.
1742 You should see the program's output displayed in the bottom window:
1743
1744 @smallexample
1745 Hello, world 1
1746 Hello, world 2
1747 Hello, world 3
1748 Hello, world 4
1749 Hello, world 5
1750 @end smallexample
1751
1752 @node Simple Debugging with GVD
1753 @subsection Simple Debugging with GVD
1754
1755 @noindent
1756 This section describes how to set breakpoints, examine/modify variables,
1757 and step through execution.
1758
1759 In order to enable debugging, you need to pass the @option{-g} switch
1760 to both the compiler and to @command{gnatlink}.  If you are using
1761 the command line, passing @option{-g} to @command{gnatmake} will have
1762 this effect.  You can then launch GVD, e.g. on the @code{hello} program,
1763 by issuing the command:
1764
1765 @smallexample
1766 $ gvd hello
1767 @end smallexample
1768
1769 @noindent
1770 If you are using Glide, then @option{-g} is passed to the relevant tools
1771 by default when you do a build.  Start the debugger by selecting the
1772 @code{Ada} menu item, and then @code{Debug}.
1773
1774 GVD comes up in a multi-part window.  One pane shows the names of files
1775 comprising your executable; another pane shows the source code of the current
1776 unit (initially your main subprogram), another pane shows the debugger output
1777 and user interactions, and the fourth pane (the data canvas at the top
1778 of the window) displays data objects that you have selected.
1779
1780 To the left of the source file pane, you will notice green dots adjacent
1781 to some lines.  These are lines for which object code exists and where
1782 breakpoints can thus be set.  You set/reset a breakpoint by clicking
1783 the green dot.  When a breakpoint is set, the dot is replaced by an @code{X}
1784 in a red circle.  Clicking the circle toggles the breakpoint off,
1785 and the red circle is replaced by the green dot.
1786
1787 For this example, set a breakpoint at the statement where @code{Put_Line}
1788 is invoked.
1789
1790 Start program execution by selecting the @code{Run} button on the top menu bar.
1791 (The @code{Start} button will also start your program, but it will
1792 cause program execution to break at the entry to your main subprogram.)
1793 Evidence of reaching the breakpoint will appear: the source file line will be
1794 highlighted, and the debugger interactions pane will display
1795 a relevant message.
1796
1797 You can examine the values of variables in several ways.  Move the mouse
1798 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1799 the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind}
1800 and select @code{Display Ind}; a box showing the variable's name and value
1801 will appear in the data canvas.
1802
1803 Although a loop index is a constant with respect to Ada semantics,
1804 you can change its value in the debugger.  Right-click in the box
1805 for @code{Ind}, and select the @code{Set Value of Ind} item.
1806 Enter @code{2} as the new value, and press @command{OK}.
1807 The box for @code{Ind} shows the update.
1808
1809 Press the @code{Step} button on the top menu bar; this will step through
1810 one line of program text (the invocation of @code{Put_Line}), and you can
1811 observe the effect of having modified @code{Ind} since the value displayed
1812 is @code{2}.
1813
1814 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1815 button.  You will see the remaining output lines displayed in the debugger
1816 interaction window, along with a message confirming normal program
1817 termination.
1818
1819 @node Other Glide Features
1820 @subsection Other Glide Features
1821
1822 @noindent
1823 You may have observed that some of the menu selections contain abbreviations;
1824 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1825 These are @emph{shortcut keys} that you can use instead of selecting
1826 menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1827 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1828 of selecting @code{Files} and then @code{Open file...}.
1829
1830 To abort a Glide command, type @key{Ctrl-g}.
1831
1832 If you want Glide to start with an existing source file, you can either
1833 launch Glide as above and then open the file via @code{Files} @result{}
1834 @code{Open file...}, or else simply pass the name of the source file
1835 on the command line:
1836
1837 @smallexample
1838 $ glide hello.adb&
1839 @end smallexample
1840
1841 @noindent
1842 While you are using Glide, a number of @emph{buffers} exist.
1843 You create some explicitly; e.g., when you open/create a file.
1844 Others arise as an effect of the commands that you issue; e.g., the buffer
1845 containing the output of the tools invoked during a build.  If a buffer
1846 is hidden, you can bring it into a visible window by first opening
1847 the @code{Buffers} menu and then selecting the desired entry.
1848
1849 If a buffer occupies only part of the Glide screen and you want to expand it
1850 to fill the entire screen, then click in the buffer and then select
1851 @code{Files} @result{} @code{One Window}.
1852
1853 If a window is occupied by one buffer and you want to split the window
1854 to bring up a second buffer, perform the following steps:
1855 @itemize @bullet
1856 @item Select @code{Files} @result{} @code{Split Window};
1857 this will produce two windows each of which holds the original buffer
1858 (these are not copies, but rather different views of the same buffer contents)
1859
1860 @item With the focus in one of the windows,
1861 select the desired buffer from the @code{Buffers} menu
1862 @end itemize
1863
1864 @noindent
1865 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1866 @end ifclear
1867
1868 @node The GNAT Compilation Model
1869 @chapter The GNAT Compilation Model
1870 @cindex GNAT compilation model
1871 @cindex Compilation model
1872
1873 @menu
1874 * Source Representation::
1875 * Foreign Language Representation::
1876 * File Naming Rules::
1877 * Using Other File Names::
1878 * Alternative File Naming Schemes::
1879 * Generating Object Files::
1880 * Source Dependencies::
1881 * The Ada Library Information Files::
1882 * Binding an Ada Program::
1883 * Mixed Language Programming::
1884 * Building Mixed Ada & C++ Programs::
1885 * Comparison between GNAT and C/C++ Compilation Models::
1886 * Comparison between GNAT and Conventional Ada Library Models::
1887 @ifset vms
1888 * Placement of temporary files::
1889 @end ifset
1890 @end menu
1891
1892 @noindent
1893 This chapter describes the compilation model used by GNAT. Although
1894 similar to that used by other languages, such as C and C++, this model
1895 is substantially different from the traditional Ada compilation models,
1896 which are based on a library. The model is initially described without
1897 reference to the library-based model. If you have not previously used an
1898 Ada compiler, you need only read the first part of this chapter. The
1899 last section describes and discusses the differences between the GNAT
1900 model and the traditional Ada compiler models. If you have used other
1901 Ada compilers, this section will help you to understand those
1902 differences, and the advantages of the GNAT model.
1903
1904 @node Source Representation
1905 @section Source Representation
1906 @cindex Latin-1
1907
1908 @noindent
1909 Ada source programs are represented in standard text files, using
1910 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1911 7-bit ASCII set, plus additional characters used for
1912 representing foreign languages (@pxref{Foreign Language Representation}
1913 for support of non-USA character sets). The format effector characters
1914 are represented using their standard ASCII encodings, as follows:
1915
1916 @table @code
1917 @item VT
1918 @findex VT
1919 Vertical tab, @code{16#0B#}
1920
1921 @item HT
1922 @findex HT
1923 Horizontal tab, @code{16#09#}
1924
1925 @item CR
1926 @findex CR
1927 Carriage return, @code{16#0D#}
1928
1929 @item LF
1930 @findex LF
1931 Line feed, @code{16#0A#}
1932
1933 @item FF
1934 @findex FF
1935 Form feed, @code{16#0C#}
1936 @end table
1937
1938 @noindent
1939 Source files are in standard text file format. In addition, GNAT will
1940 recognize a wide variety of stream formats, in which the end of physical
1941 physical lines is marked by any of the following sequences:
1942 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1943 in accommodating files that are imported from other operating systems.
1944
1945 @cindex End of source file
1946 @cindex Source file, end
1947 @findex SUB
1948 The end of a source file is normally represented by the physical end of
1949 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1950 recognized as signalling the end of the source file. Again, this is
1951 provided for compatibility with other operating systems where this
1952 code is used to represent the end of file.
1953
1954 Each file contains a single Ada compilation unit, including any pragmas
1955 associated with the unit. For example, this means you must place a
1956 package declaration (a package @dfn{spec}) and the corresponding body in
1957 separate files. An Ada @dfn{compilation} (which is a sequence of
1958 compilation units) is represented using a sequence of files. Similarly,
1959 you will place each subunit or child unit in a separate file.
1960
1961 @node Foreign Language Representation
1962 @section Foreign Language Representation
1963
1964 @noindent
1965 GNAT supports the standard character sets defined in Ada 95 as well as
1966 several other non-standard character sets for use in localized versions
1967 of the compiler (@pxref{Character Set Control}).
1968 @menu
1969 * Latin-1::
1970 * Other 8-Bit Codes::
1971 * Wide Character Encodings::
1972 @end menu
1973
1974 @node Latin-1
1975 @subsection Latin-1
1976 @cindex Latin-1
1977
1978 @noindent
1979 The basic character set is Latin-1. This character set is defined by ISO
1980 standard 8859, part 1. The lower half (character codes @code{16#00#}
1981 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1982 is used to represent additional characters. These include extended letters
1983 used by European languages, such as French accents, the vowels with umlauts
1984 used in German, and the extra letter A-ring used in Swedish.
1985
1986 @findex Ada.Characters.Latin_1
1987 For a complete list of Latin-1 codes and their encodings, see the source
1988 file of library unit @code{Ada.Characters.Latin_1} in file
1989 @file{a-chlat1.ads}.
1990 You may use any of these extended characters freely in character or
1991 string literals. In addition, the extended characters that represent
1992 letters can be used in identifiers.
1993
1994 @node Other 8-Bit Codes
1995 @subsection Other 8-Bit Codes
1996
1997 @noindent
1998 GNAT also supports several other 8-bit coding schemes:
1999
2000 @table @asis
2001 @item ISO 8859-2 (Latin-2)
2002 @cindex Latin-2
2003 @cindex ISO 8859-2
2004 Latin-2 letters allowed in identifiers, with uppercase and lowercase
2005 equivalence.
2006
2007 @item ISO 8859-3 (Latin-3)
2008 @cindex Latin-3
2009 @cindex ISO 8859-3
2010 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2011 equivalence.
2012
2013 @item ISO 8859-4 (Latin-4)
2014 @cindex Latin-4
2015 @cindex ISO 8859-4
2016 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2017 equivalence.
2018
2019 @item ISO 8859-5 (Cyrillic)
2020 @cindex ISO 8859-5
2021 @cindex Cyrillic
2022 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2023 lowercase equivalence.
2024
2025 @item ISO 8859-15 (Latin-9)
2026 @cindex ISO 8859-15
2027 @cindex Latin-9
2028 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2029 lowercase equivalence
2030
2031 @item IBM PC (code page 437)
2032 @cindex code page 437
2033 This code page is the normal default for PCs in the U.S. It corresponds
2034 to the original IBM PC character set. This set has some, but not all, of
2035 the extended Latin-1 letters, but these letters do not have the same
2036 encoding as Latin-1. In this mode, these letters are allowed in
2037 identifiers with uppercase and lowercase equivalence.
2038
2039 @item IBM PC (code page 850)
2040 @cindex code page 850
2041 This code page is a modification of 437 extended to include all the
2042 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2043 mode, all these letters are allowed in identifiers with uppercase and
2044 lowercase equivalence.
2045
2046 @item Full Upper 8-bit
2047 Any character in the range 80-FF allowed in identifiers, and all are
2048 considered distinct. In other words, there are no uppercase and lowercase
2049 equivalences in this range. This is useful in conjunction with
2050 certain encoding schemes used for some foreign character sets (e.g.
2051 the typical method of representing Chinese characters on the PC).
2052
2053 @item No Upper-Half
2054 No upper-half characters in the range 80-FF are allowed in identifiers.
2055 This gives Ada 83 compatibility for identifier names.
2056 @end table
2057
2058 @noindent
2059 For precise data on the encodings permitted, and the uppercase and lowercase
2060 equivalences that are recognized, see the file @file{csets.adb} in
2061 the GNAT compiler sources. You will need to obtain a full source release
2062 of GNAT to obtain this file.
2063
2064 @node Wide Character Encodings
2065 @subsection Wide Character Encodings
2066
2067 @noindent
2068 GNAT allows wide character codes to appear in character and string
2069 literals, and also optionally in identifiers, by means of the following
2070 possible encoding schemes:
2071
2072 @table @asis
2073
2074 @item Hex Coding
2075 In this encoding, a wide character is represented by the following five
2076 character sequence:
2077
2078 @smallexample
2079 ESC a b c d
2080 @end smallexample
2081
2082 @noindent
2083 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2084 characters (using uppercase letters) of the wide character code. For
2085 example, ESC A345 is used to represent the wide character with code
2086 @code{16#A345#}.
2087 This scheme is compatible with use of the full Wide_Character set.
2088
2089 @item Upper-Half Coding
2090 @cindex Upper-Half Coding
2091 The wide character with encoding @code{16#abcd#} where the upper bit is on
2092 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2093 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2094 character, but is not required to be in the upper half. This method can
2095 be also used for shift-JIS or EUC, where the internal coding matches the
2096 external coding.
2097
2098 @item Shift JIS Coding
2099 @cindex Shift JIS Coding
2100 A wide character is represented by a two-character sequence,
2101 @code{16#ab#} and
2102 @code{16#cd#}, with the restrictions described for upper-half encoding as
2103 described above. The internal character code is the corresponding JIS
2104 character according to the standard algorithm for Shift-JIS
2105 conversion. Only characters defined in the JIS code set table can be
2106 used with this encoding method.
2107
2108 @item EUC Coding
2109 @cindex EUC Coding
2110 A wide character is represented by a two-character sequence
2111 @code{16#ab#} and
2112 @code{16#cd#}, with both characters being in the upper half. The internal
2113 character code is the corresponding JIS character according to the EUC
2114 encoding algorithm. Only characters defined in the JIS code set table
2115 can be used with this encoding method.
2116
2117 @item UTF-8 Coding
2118 A wide character is represented using
2119 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2120 10646-1/Am.2. Depending on the character value, the representation
2121 is a one, two, or three byte sequence:
2122 @smallexample
2123 @iftex
2124 @leftskip=.7cm
2125 @end iftex
2126 16#0000#-16#007f#: 2#0xxxxxxx#
2127 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2128 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2129
2130 @end smallexample
2131
2132 @noindent
2133 where the xxx bits correspond to the left-padded bits of the
2134 16-bit character value. Note that all lower half ASCII characters
2135 are represented as ASCII bytes and all upper half characters and
2136 other wide characters are represented as sequences of upper-half
2137 (The full UTF-8 scheme allows for encoding 31-bit characters as
2138 6-byte sequences, but in this implementation, all UTF-8 sequences
2139 of four or more bytes length will be treated as illegal).
2140 @item Brackets Coding
2141 In this encoding, a wide character is represented by the following eight
2142 character sequence:
2143
2144 @smallexample
2145 [ " a b c d " ]
2146 @end smallexample
2147
2148 @noindent
2149 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2150 characters (using uppercase letters) of the wide character code. For
2151 example, [``A345''] is used to represent the wide character with code
2152 @code{16#A345#}. It is also possible (though not required) to use the
2153 Brackets coding for upper half characters. For example, the code
2154 @code{16#A3#} can be represented as @code{[``A3'']}.
2155
2156 This scheme is compatible with use of the full Wide_Character set,
2157 and is also the method used for wide character encoding in the standard
2158 ACVC (Ada Compiler Validation Capability) test suite distributions.
2159
2160 @end table
2161
2162 @noindent
2163 Note: Some of these coding schemes do not permit the full use of the
2164 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2165 use of the upper half of the Latin-1 set.
2166
2167 @node File Naming Rules
2168 @section File Naming Rules
2169
2170 @noindent
2171 The default file name is determined by the name of the unit that the
2172 file contains. The name is formed by taking the full expanded name of
2173 the unit and replacing the separating dots with hyphens and using
2174 ^lowercase^uppercase^ for all letters.
2175
2176 An exception arises if the file name generated by the above rules starts
2177 with one of the characters
2178 @ifset vms
2179 A,G,I, or S,
2180 @end ifset
2181 @ifclear vms
2182 a,g,i, or s,
2183 @end ifclear
2184 and the second character is a
2185 minus. In this case, the character ^tilde^dollar sign^ is used in place
2186 of the minus. The reason for this special rule is to avoid clashes with
2187 the standard names for child units of the packages System, Ada,
2188 Interfaces, and GNAT, which use the prefixes
2189 @ifset vms
2190 S- A- I- and G-
2191 @end ifset
2192 @ifclear vms
2193 s- a- i- and g-
2194 @end ifclear
2195 respectively.
2196
2197 The file extension is @file{.ads} for a spec and
2198 @file{.adb} for a body. The following list shows some
2199 examples of these rules.
2200
2201 @table @file
2202 @item main.ads
2203 Main (spec)
2204 @item main.adb
2205 Main (body)
2206 @item arith_functions.ads
2207 Arith_Functions (package spec)
2208 @item arith_functions.adb
2209 Arith_Functions (package body)
2210 @item func-spec.ads
2211 Func.Spec (child package spec)
2212 @item func-spec.adb
2213 Func.Spec (child package body)
2214 @item main-sub.adb
2215 Sub (subunit of Main)
2216 @item ^a~bad.adb^A$BAD.ADB^
2217 A.Bad (child package body)
2218 @end table
2219
2220 @noindent
2221 Following these rules can result in excessively long
2222 file names if corresponding
2223 unit names are long (for example, if child units or subunits are
2224 heavily nested). An option is available to shorten such long file names
2225 (called file name ``krunching''). This may be particularly useful when
2226 programs being developed with GNAT are to be used on operating systems
2227 with limited file name lengths. @xref{Using gnatkr}.
2228
2229 Of course, no file shortening algorithm can guarantee uniqueness over
2230 all possible unit names; if file name krunching is used, it is your
2231 responsibility to ensure no name clashes occur. Alternatively you
2232 can specify the exact file names that you want used, as described
2233 in the next section. Finally, if your Ada programs are migrating from a
2234 compiler with a different naming convention, you can use the gnatchop
2235 utility to produce source files that follow the GNAT naming conventions.
2236 (For details @pxref{Renaming Files Using gnatchop}.)
2237
2238 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2239 systems, case is not significant. So for example on @code{Windows XP}
2240 if the canonical name is @code{main-sub.adb}, you can use the file name
2241 @code{Main-Sub.adb} instead. However, case is significant for other
2242 operating systems, so for example, if you want to use other than
2243 canonically cased file names on a Unix system, you need to follow
2244 the procedures described in the next section.
2245
2246 @node Using Other File Names
2247 @section Using Other File Names
2248 @cindex File names
2249
2250 @noindent
2251 In the previous section, we have described the default rules used by
2252 GNAT to determine the file name in which a given unit resides. It is
2253 often convenient to follow these default rules, and if you follow them,
2254 the compiler knows without being explicitly told where to find all
2255 the files it needs.
2256
2257 However, in some cases, particularly when a program is imported from
2258 another Ada compiler environment, it may be more convenient for the
2259 programmer to specify which file names contain which units. GNAT allows
2260 arbitrary file names to be used by means of the Source_File_Name pragma.
2261 The form of this pragma is as shown in the following examples:
2262 @cindex Source_File_Name pragma
2263
2264 @smallexample @c ada
2265 @cartouche
2266 pragma Source_File_Name (My_Utilities.Stacks,
2267   Spec_File_Name => "myutilst_a.ada");
2268 pragma Source_File_name (My_Utilities.Stacks,
2269   Body_File_Name => "myutilst.ada");
2270 @end cartouche
2271 @end smallexample
2272
2273 @noindent
2274 As shown in this example, the first argument for the pragma is the unit
2275 name (in this example a child unit). The second argument has the form
2276 of a named association. The identifier
2277 indicates whether the file name is for a spec or a body;
2278 the file name itself is given by a string literal.
2279
2280 The source file name pragma is a configuration pragma, which means that
2281 normally it will be placed in the @file{gnat.adc}
2282 file used to hold configuration
2283 pragmas that apply to a complete compilation environment.
2284 For more details on how the @file{gnat.adc} file is created and used
2285 @pxref{Handling of Configuration Pragmas}
2286 @cindex @file{gnat.adc}
2287
2288 @ifclear vms
2289 GNAT allows completely arbitrary file names to be specified using the
2290 source file name pragma. However, if the file name specified has an
2291 extension other than @file{.ads} or @file{.adb} it is necessary to use
2292 a special syntax when compiling the file. The name in this case must be
2293 preceded by the special sequence @code{-x} followed by a space and the name
2294 of the language, here @code{ada}, as in:
2295
2296 @smallexample
2297 $ gcc -c -x ada peculiar_file_name.sim
2298 @end smallexample
2299 @end ifclear
2300
2301 @noindent
2302 @code{gnatmake} handles non-standard file names in the usual manner (the
2303 non-standard file name for the main program is simply used as the
2304 argument to gnatmake). Note that if the extension is also non-standard,
2305 then it must be included in the gnatmake command, it may not be omitted.
2306
2307 @node Alternative File Naming Schemes
2308 @section Alternative File Naming Schemes
2309 @cindex File naming schemes, alternative
2310 @cindex File names
2311
2312 In the previous section, we described the use of the @code{Source_File_Name}
2313 pragma to allow arbitrary names to be assigned to individual source files.
2314 However, this approach requires one pragma for each file, and especially in
2315 large systems can result in very long @file{gnat.adc} files, and also create
2316 a maintenance problem.
2317
2318 GNAT also provides a facility for specifying systematic file naming schemes
2319 other than the standard default naming scheme previously described. An
2320 alternative scheme for naming is specified by the use of
2321 @code{Source_File_Name} pragmas having the following format:
2322 @cindex Source_File_Name pragma
2323
2324 @smallexample @c ada
2325 pragma Source_File_Name (
2326    Spec_File_Name  => FILE_NAME_PATTERN
2327  [,Casing          => CASING_SPEC]
2328  [,Dot_Replacement => STRING_LITERAL]);
2329
2330 pragma Source_File_Name (
2331    Body_File_Name  => FILE_NAME_PATTERN
2332  [,Casing          => CASING_SPEC]
2333  [,Dot_Replacement => STRING_LITERAL]);
2334
2335 pragma Source_File_Name (
2336    Subunit_File_Name  => FILE_NAME_PATTERN
2337  [,Casing             => CASING_SPEC]
2338  [,Dot_Replacement    => STRING_LITERAL]);
2339
2340 FILE_NAME_PATTERN ::= STRING_LITERAL
2341 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2342 @end smallexample
2343
2344 @noindent
2345 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2346 It contains a single asterisk character, and the unit name is substituted
2347 systematically for this asterisk. The optional parameter
2348 @code{Casing} indicates
2349 whether the unit name is to be all upper-case letters, all lower-case letters,
2350 or mixed-case. If no
2351 @code{Casing} parameter is used, then the default is all
2352 ^lower-case^upper-case^.
2353
2354 The optional @code{Dot_Replacement} string is used to replace any periods
2355 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2356 argument is used then separating dots appear unchanged in the resulting
2357 file name.
2358 Although the above syntax indicates that the
2359 @code{Casing} argument must appear
2360 before the @code{Dot_Replacement} argument, but it
2361 is also permissible to write these arguments in the opposite order.
2362
2363 As indicated, it is possible to specify different naming schemes for
2364 bodies, specs, and subunits. Quite often the rule for subunits is the
2365 same as the rule for bodies, in which case, there is no need to give
2366 a separate @code{Subunit_File_Name} rule, and in this case the
2367 @code{Body_File_name} rule is used for subunits as well.
2368
2369 The separate rule for subunits can also be used to implement the rather
2370 unusual case of a compilation environment (e.g. a single directory) which
2371 contains a subunit and a child unit with the same unit name. Although
2372 both units cannot appear in the same partition, the Ada Reference Manual
2373 allows (but does not require) the possibility of the two units coexisting
2374 in the same environment.
2375
2376 The file name translation works in the following steps:
2377
2378 @itemize @bullet
2379
2380 @item
2381 If there is a specific @code{Source_File_Name} pragma for the given unit,
2382 then this is always used, and any general pattern rules are ignored.
2383
2384 @item
2385 If there is a pattern type @code{Source_File_Name} pragma that applies to
2386 the unit, then the resulting file name will be used if the file exists. If
2387 more than one pattern matches, the latest one will be tried first, and the
2388 first attempt resulting in a reference to a file that exists will be used.
2389
2390 @item
2391 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2392 for which the corresponding file exists, then the standard GNAT default
2393 naming rules are used.
2394
2395 @end itemize
2396
2397 @noindent
2398 As an example of the use of this mechanism, consider a commonly used scheme
2399 in which file names are all lower case, with separating periods copied
2400 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2401 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2402 two pragmas appear:
2403
2404 @smallexample @c ada
2405 pragma Source_File_Name
2406   (Spec_File_Name => "*.1.ada");
2407 pragma Source_File_Name
2408   (Body_File_Name => "*.2.ada");
2409 @end smallexample
2410
2411 @noindent
2412 The default GNAT scheme is actually implemented by providing the following
2413 default pragmas internally:
2414
2415 @smallexample @c ada
2416 pragma Source_File_Name
2417   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2418 pragma Source_File_Name
2419   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2420 @end smallexample
2421
2422 @noindent
2423 Our final example implements a scheme typically used with one of the
2424 Ada 83 compilers, where the separator character for subunits was ``__''
2425 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2426 by adding @file{.ADA}, and subunits by
2427 adding @file{.SEP}. All file names were
2428 upper case. Child units were not present of course since this was an
2429 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2430 the same double underscore separator for child units.
2431
2432 @smallexample @c ada
2433 pragma Source_File_Name
2434   (Spec_File_Name => "*_.ADA",
2435    Dot_Replacement => "__",
2436    Casing = Uppercase);
2437 pragma Source_File_Name
2438   (Body_File_Name => "*.ADA",
2439    Dot_Replacement => "__",
2440    Casing = Uppercase);
2441 pragma Source_File_Name
2442   (Subunit_File_Name => "*.SEP",
2443    Dot_Replacement => "__",
2444    Casing = Uppercase);
2445 @end smallexample
2446
2447 @node Generating Object Files
2448 @section Generating Object Files
2449
2450 @noindent
2451 An Ada program consists of a set of source files, and the first step in
2452 compiling the program is to generate the corresponding object files.
2453 These are generated by compiling a subset of these source files.
2454 The files you need to compile are the following:
2455
2456 @itemize @bullet
2457 @item
2458 If a package spec has no body, compile the package spec to produce the
2459 object file for the package.
2460
2461 @item
2462 If a package has both a spec and a body, compile the body to produce the
2463 object file for the package. The source file for the package spec need
2464 not be compiled in this case because there is only one object file, which
2465 contains the code for both the spec and body of the package.
2466
2467 @item
2468 For a subprogram, compile the subprogram body to produce the object file
2469 for the subprogram. The spec, if one is present, is as usual in a
2470 separate file, and need not be compiled.
2471
2472 @item
2473 @cindex Subunits
2474 In the case of subunits, only compile the parent unit. A single object
2475 file is generated for the entire subunit tree, which includes all the
2476 subunits.
2477
2478 @item
2479 Compile child units independently of their parent units
2480 (though, of course, the spec of all the ancestor unit must be present in order
2481 to compile a child unit).
2482
2483 @item
2484 @cindex Generics
2485 Compile generic units in the same manner as any other units. The object
2486 files in this case are small dummy files that contain at most the
2487 flag used for elaboration checking. This is because GNAT always handles generic
2488 instantiation by means of macro expansion. However, it is still necessary to
2489 compile generic units, for dependency checking and elaboration purposes.
2490 @end itemize
2491
2492 @noindent
2493 The preceding rules describe the set of files that must be compiled to
2494 generate the object files for a program. Each object file has the same
2495 name as the corresponding source file, except that the extension is
2496 @file{.o} as usual.
2497
2498 You may wish to compile other files for the purpose of checking their
2499 syntactic and semantic correctness. For example, in the case where a
2500 package has a separate spec and body, you would not normally compile the
2501 spec. However, it is convenient in practice to compile the spec to make
2502 sure it is error-free before compiling clients of this spec, because such
2503 compilations will fail if there is an error in the spec.
2504
2505 GNAT provides an option for compiling such files purely for the
2506 purposes of checking correctness; such compilations are not required as
2507 part of the process of building a program. To compile a file in this
2508 checking mode, use the @option{-gnatc} switch.
2509
2510 @node Source Dependencies
2511 @section Source Dependencies
2512
2513 @noindent
2514 A given object file clearly depends on the source file which is compiled
2515 to produce it. Here we are using @dfn{depends} in the sense of a typical
2516 @code{make} utility; in other words, an object file depends on a source
2517 file if changes to the source file require the object file to be
2518 recompiled.
2519 In addition to this basic dependency, a given object may depend on
2520 additional source files as follows:
2521
2522 @itemize @bullet
2523 @item
2524 If a file being compiled @code{with}'s a unit @var{X}, the object file
2525 depends on the file containing the spec of unit @var{X}. This includes
2526 files that are @code{with}'ed implicitly either because they are parents
2527 of @code{with}'ed child units or they are run-time units required by the
2528 language constructs used in a particular unit.
2529
2530 @item
2531 If a file being compiled instantiates a library level generic unit, the
2532 object file depends on both the spec and body files for this generic
2533 unit.
2534
2535 @item
2536 If a file being compiled instantiates a generic unit defined within a
2537 package, the object file depends on the body file for the package as
2538 well as the spec file.
2539
2540 @item
2541 @findex Inline
2542 @cindex @option{-gnatn} switch
2543 If a file being compiled contains a call to a subprogram for which
2544 pragma @code{Inline} applies and inlining is activated with the
2545 @option{-gnatn} switch, the object file depends on the file containing the
2546 body of this subprogram as well as on the file containing the spec. Note
2547 that for inlining to actually occur as a result of the use of this switch,
2548 it is necessary to compile in optimizing mode.
2549
2550 @cindex @option{-gnatN} switch
2551 The use of @option{-gnatN} activates a more extensive inlining optimization
2552 that is performed by the front end of the compiler. This inlining does
2553 not require that the code generation be optimized. Like @option{-gnatn},
2554 the use of this switch generates additional dependencies.
2555 Note that
2556 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2557 to specify both options.
2558
2559 @item
2560 If an object file O  depends on the proper body of a subunit through inlining
2561 or instantiation, it depends on the parent unit of the subunit. This means that
2562 any modification of the parent unit or one of its subunits affects the
2563 compilation of O.
2564
2565 @item
2566 The object file for a parent unit depends on all its subunit body files.
2567
2568 @item
2569 The previous two rules meant that for purposes of computing dependencies and
2570 recompilation, a body and all its subunits are treated as an indivisible whole.
2571
2572 @noindent
2573 These rules are applied transitively: if unit @code{A} @code{with}'s
2574 unit @code{B}, whose elaboration calls an inlined procedure in package
2575 @code{C}, the object file for unit @code{A} will depend on the body of
2576 @code{C}, in file @file{c.adb}.
2577
2578 The set of dependent files described by these rules includes all the
2579 files on which the unit is semantically dependent, as described in the
2580 Ada 95 Language Reference Manual. However, it is a superset of what the
2581 ARM describes, because it includes generic, inline, and subunit dependencies.
2582
2583 An object file must be recreated by recompiling the corresponding source
2584 file if any of the source files on which it depends are modified. For
2585 example, if the @code{make} utility is used to control compilation,
2586 the rule for an Ada object file must mention all the source files on
2587 which the object file depends, according to the above definition.
2588 The determination of the necessary
2589 recompilations is done automatically when one uses @code{gnatmake}.
2590 @end itemize
2591
2592 @node The Ada Library Information Files
2593 @section The Ada Library Information Files
2594 @cindex Ada Library Information files
2595 @cindex @file{ALI} files
2596
2597 @noindent
2598 Each compilation actually generates two output files. The first of these
2599 is the normal object file that has a @file{.o} extension. The second is a
2600 text file containing full dependency information. It has the same
2601 name as the source file, but an @file{.ali} extension.
2602 This file is known as the Ada Library Information (@file{ALI}) file.
2603 The following information is contained in the @file{ALI} file.
2604
2605 @itemize @bullet
2606 @item
2607 Version information (indicates which version of GNAT was used to compile
2608 the unit(s) in question)
2609
2610 @item
2611 Main program information (including priority and time slice settings,
2612 as well as the wide character encoding used during compilation).
2613
2614 @item
2615 List of arguments used in the @code{gcc} command for the compilation
2616
2617 @item
2618 Attributes of the unit, including configuration pragmas used, an indication
2619 of whether the compilation was successful, exception model used etc.
2620
2621 @item
2622 A list of relevant restrictions applying to the unit (used for consistency)
2623 checking.
2624
2625 @item
2626 Categorization information (e.g. use of pragma @code{Pure}).
2627
2628 @item
2629 Information on all @code{with}'ed units, including presence of
2630 @code{Elaborate} or @code{Elaborate_All} pragmas.
2631
2632 @item
2633 Information from any @code{Linker_Options} pragmas used in the unit
2634
2635 @item
2636 Information on the use of @code{Body_Version} or @code{Version}
2637 attributes in the unit.
2638
2639 @item
2640 Dependency information. This is a list of files, together with
2641 time stamp and checksum information. These are files on which
2642 the unit depends in the sense that recompilation is required
2643 if any of these units are modified.
2644
2645 @item
2646 Cross-reference data. Contains information on all entities referenced
2647 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2648 provide cross-reference information.
2649
2650 @end itemize
2651
2652 @noindent
2653 For a full detailed description of the format of the @file{ALI} file,
2654 see the source of the body of unit @code{Lib.Writ}, contained in file
2655 @file{lib-writ.adb} in the GNAT compiler sources.
2656
2657 @node Binding an Ada Program
2658 @section Binding an Ada Program
2659
2660 @noindent
2661 When using languages such as C and C++, once the source files have been
2662 compiled the only remaining step in building an executable program
2663 is linking the object modules together. This means that it is possible to
2664 link an inconsistent version of a program, in which two units have
2665 included different versions of the same header.
2666
2667 The rules of Ada do not permit such an inconsistent program to be built.
2668 For example, if two clients have different versions of the same package,
2669 it is illegal to build a program containing these two clients.
2670 These rules are enforced by the GNAT binder, which also determines an
2671 elaboration order consistent with the Ada rules.
2672
2673 The GNAT binder is run after all the object files for a program have
2674 been created. It is given the name of the main program unit, and from
2675 this it determines the set of units required by the program, by reading the
2676 corresponding ALI files. It generates error messages if the program is
2677 inconsistent or if no valid order of elaboration exists.
2678
2679 If no errors are detected, the binder produces a main program, in Ada by
2680 default, that contains calls to the elaboration procedures of those
2681 compilation unit that require them, followed by
2682 a call to the main program. This Ada program is compiled to generate the
2683 object file for the main program. The name of
2684 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2685 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2686 main program unit.
2687
2688 Finally, the linker is used to build the resulting executable program,
2689 using the object from the main program from the bind step as well as the
2690 object files for the Ada units of the program.
2691
2692 @node Mixed Language Programming
2693 @section Mixed Language Programming
2694 @cindex Mixed Language Programming
2695
2696 @noindent
2697 This section describes how to develop a mixed-language program,
2698 specifically one that comprises units in both Ada and C.
2699
2700 @menu
2701 * Interfacing to C::
2702 * Calling Conventions::
2703 @end menu
2704
2705 @node Interfacing to C
2706 @subsection Interfacing to C
2707 @noindent
2708 Interfacing Ada with a foreign language such as C involves using
2709 compiler directives to import and/or export entity definitions in each
2710 language---using @code{extern} statements in C, for instance, and the
2711 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.  For
2712 a full treatment of these topics, read Appendix B, section 1 of the Ada
2713 95 Language Reference Manual.
2714
2715 There are two ways to build a program using GNAT that contains some Ada
2716 sources and some foreign language sources, depending on whether or not
2717 the main subprogram is written in Ada.  Here is a source example with
2718 the main subprogram in Ada:
2719
2720 @smallexample
2721 /* file1.c */
2722 #include <stdio.h>
2723
2724 void print_num (int num)
2725 @{
2726   printf ("num is %d.\n", num);
2727   return;
2728 @}
2729
2730 /* file2.c */
2731
2732 /* num_from_Ada is declared in my_main.adb */
2733 extern int num_from_Ada;
2734
2735 int get_num (void)
2736 @{
2737   return num_from_Ada;
2738 @}
2739 @end smallexample
2740
2741 @smallexample @c ada
2742 --  my_main.adb
2743 procedure My_Main is
2744
2745    --  Declare then export an Integer entity called num_from_Ada
2746    My_Num : Integer := 10;
2747    pragma Export (C, My_Num, "num_from_Ada");
2748
2749    --  Declare an Ada function spec for Get_Num, then use
2750    --  C function get_num for the implementation.
2751    function Get_Num return Integer;
2752    pragma Import (C, Get_Num, "get_num");
2753
2754    --  Declare an Ada procedure spec for Print_Num, then use
2755    --  C function print_num for the implementation.
2756    procedure Print_Num (Num : Integer);
2757    pragma Import (C, Print_Num, "print_num");
2758
2759 begin
2760    Print_Num (Get_Num);
2761 end My_Main;
2762 @end smallexample
2763
2764 @enumerate
2765 @item
2766 To build this example, first compile the foreign language files to
2767 generate object files:
2768 @smallexample
2769 gcc -c file1.c
2770 gcc -c file2.c
2771 @end smallexample
2772
2773 @item
2774 Then, compile the Ada units to produce a set of object files and ALI
2775 files:
2776 @smallexample
2777 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2778 @end smallexample
2779
2780 @item
2781 Run the Ada binder on the Ada main program:
2782 @smallexample
2783 gnatbind my_main.ali
2784 @end smallexample
2785
2786 @item
2787 Link the Ada main program, the Ada objects and the other language
2788 objects:
2789 @smallexample
2790 gnatlink my_main.ali file1.o file2.o
2791 @end smallexample
2792 @end enumerate
2793
2794 The last three steps can be grouped in a single command:
2795 @smallexample
2796 gnatmake my_main.adb -largs file1.o file2.o
2797 @end smallexample
2798
2799 @cindex Binder output file
2800 @noindent
2801 If the main program is in a language other than Ada, then you may have
2802 more than one entry point into the Ada subsystem. You must use a special
2803 binder option to generate callable routines that initialize and
2804 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2805 Calls to the initialization and finalization routines must be inserted
2806 in the main program, or some other appropriate point in the code. The
2807 call to initialize the Ada units must occur before the first Ada
2808 subprogram is called, and the call to finalize the Ada units must occur
2809 after the last Ada subprogram returns. The binder will place the
2810 initialization and finalization subprograms into the
2811 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2812 sources.  To illustrate, we have the following example:
2813
2814 @smallexample
2815 /* main.c */
2816 extern void adainit (void);
2817 extern void adafinal (void);
2818 extern int add (int, int);
2819 extern int sub (int, int);
2820
2821 int main (int argc, char *argv[])
2822 @{
2823   int a = 21, b = 7;
2824
2825   adainit();
2826
2827   /* Should print "21 + 7 = 28" */
2828   printf ("%d + %d = %d\n", a, b, add (a, b));
2829   /* Should print "21 - 7 = 14" */
2830   printf ("%d - %d = %d\n", a, b, sub (a, b));
2831
2832   adafinal();
2833 @}
2834 @end smallexample
2835
2836 @smallexample @c ada
2837 --  unit1.ads
2838 package Unit1 is
2839    function Add (A, B : Integer) return Integer;
2840    pragma Export (C, Add, "add");
2841 end Unit1;
2842
2843 --  unit1.adb
2844 package body Unit1 is
2845    function Add (A, B : Integer) return Integer is
2846    begin
2847       return A + B;
2848    end Add;
2849 end Unit1;
2850
2851 --  unit2.ads
2852 package Unit2 is
2853    function Sub (A, B : Integer) return Integer;
2854    pragma Export (C, Sub, "sub");
2855 end Unit2;
2856
2857 --  unit2.adb
2858 package body Unit2 is
2859    function Sub (A, B : Integer) return Integer is
2860    begin
2861       return A - B;
2862    end Sub;
2863 end Unit2;
2864 @end smallexample
2865
2866 @enumerate
2867 @item
2868 The build procedure for this application is similar to the last
2869 example's.  First, compile the foreign language files to generate object
2870 files:
2871 @smallexample
2872 gcc -c main.c
2873 @end smallexample
2874
2875 @item
2876 Next, compile the Ada units to produce a set of object files and ALI
2877 files:
2878 @smallexample
2879 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2880 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2881 @end smallexample
2882
2883 @item
2884 Run the Ada binder on every generated ALI file.  Make sure to use the
2885 @option{-n} option to specify a foreign main program:
2886 @smallexample
2887 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2888 @end smallexample
2889
2890 @item
2891 Link the Ada main program, the Ada objects and the foreign language
2892 objects. You need only list the last ALI file here:
2893 @smallexample
2894 gnatlink unit2.ali main.o -o exec_file
2895 @end smallexample
2896
2897 This procedure yields a binary executable called @file{exec_file}.
2898 @end enumerate
2899
2900 @node Calling Conventions
2901 @subsection Calling Conventions
2902 @cindex Foreign Languages
2903 @cindex Calling Conventions
2904 GNAT follows standard calling sequence conventions and will thus interface
2905 to any other language that also follows these conventions. The following
2906 Convention identifiers are recognized by GNAT:
2907
2908 @table @code
2909 @cindex Interfacing to Ada
2910 @cindex Other Ada compilers
2911 @cindex Convention Ada
2912 @item Ada
2913 This indicates that the standard Ada calling sequence will be
2914 used and all Ada data items may be passed without any limitations in the
2915 case where GNAT is used to generate both the caller and callee. It is also
2916 possible to mix GNAT generated code and code generated by another Ada
2917 compiler. In this case, the data types should be restricted to simple
2918 cases, including primitive types. Whether complex data types can be passed
2919 depends on the situation. Probably it is safe to pass simple arrays, such
2920 as arrays of integers or floats. Records may or may not work, depending
2921 on whether both compilers lay them out identically. Complex structures
2922 involving variant records, access parameters, tasks, or protected types,
2923 are unlikely to be able to be passed.
2924
2925 Note that in the case of GNAT running
2926 on a platform that supports DEC Ada 83, a higher degree of compatibility
2927 can be guaranteed, and in particular records are layed out in an identical
2928 manner in the two compilers. Note also that if output from two different
2929 compilers is mixed, the program is responsible for dealing with elaboration
2930 issues. Probably the safest approach is to write the main program in the
2931 version of Ada other than GNAT, so that it takes care of its own elaboration
2932 requirements, and then call the GNAT-generated adainit procedure to ensure
2933 elaboration of the GNAT components. Consult the documentation of the other
2934 Ada compiler for further details on elaboration.
2935
2936 However, it is not possible to mix the tasking run time of GNAT and
2937 DEC Ada 83, All the tasking operations must either be entirely within
2938 GNAT compiled sections of the program, or entirely within DEC Ada 83
2939 compiled sections of the program.
2940
2941 @cindex Interfacing to Assembly
2942 @cindex Convention Assembler
2943 @item Assembler
2944 Specifies assembler as the convention. In practice this has the
2945 same effect as convention Ada (but is not equivalent in the sense of being
2946 considered the same convention).
2947
2948 @cindex Convention Asm
2949 @findex Asm
2950 @item Asm
2951 Equivalent to Assembler.
2952
2953 @cindex Interfacing to COBOL
2954 @cindex Convention COBOL
2955 @findex COBOL
2956 @item COBOL
2957 Data will be passed according to the conventions described
2958 in section B.4 of the Ada 95 Reference Manual.
2959
2960 @findex C
2961 @cindex Interfacing to C
2962 @cindex Convention C
2963 @item C
2964 Data will be passed according to the conventions described
2965 in section B.3 of the Ada 95 Reference Manual.
2966
2967 @findex C varargs function
2968 @cindex Intefacing to C varargs function
2969 @cindex varargs function intefacs
2970 @item C varargs function
2971 In C, @code{varargs} allows a function to take a variable number of
2972 arguments. There is no direct equivalent in this to Ada. One
2973 approach that can be used is to create a C wrapper for each
2974 different profile and then interface to this C wrapper. For
2975 example, to print an @code{int} value using @code{printf},
2976 create a C function @code{printfi} that takes two arguments, a
2977 pointer to a string and an int, and calls @code{printf}.
2978 Then in the Ada program, use pragma @code{Import} to
2979 interface to printfi.
2980
2981 It may work on some platforms to directly interface to
2982 a @code{varargs} function by providing a specific Ada profile
2983 for a a particular call. However, this does not work on
2984 all platforms, since there is no guarantee that the
2985 calling sequence for a two argument normal C function
2986 is the same as for calling a @code{varargs} C function with
2987 the same two arguments.
2988
2989 @cindex Convention Default
2990 @findex Default
2991 @item Default
2992 Equivalent to C.
2993
2994 @cindex Convention External
2995 @findex External
2996 @item External
2997 Equivalent to C.
2998
2999 @findex C++
3000 @cindex Interfacing to C++
3001 @cindex Convention C++
3002 @item CPP
3003 This stands for C++. For most purposes this is identical to C.
3004 See the separate description of the specialized GNAT pragmas relating to
3005 C++ interfacing for further details.
3006
3007 @findex Fortran
3008 @cindex Interfacing to Fortran
3009 @cindex Convention Fortran
3010 @item Fortran
3011 Data will be passed according to the conventions described
3012 in section B.5 of the Ada 95 Reference Manual.
3013
3014 @item Intrinsic
3015 This applies to an intrinsic operation, as defined in the Ada 95
3016 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
3017 this means that the body of the subprogram is provided by the compiler itself,
3018 usually by means of an efficient code sequence, and that the user does not
3019 supply an explicit body for it. In an application program, the pragma can
3020 only be applied to the following two sets of names, which the GNAT compiler
3021 recognizes.
3022
3023 @itemize @bullet
3024 @item
3025 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
3026 Arithmetic.  The corresponding subprogram declaration must have
3027 two formal parameters. The
3028 first one must be a signed integer type or a modular type with a binary
3029 modulus, and the second parameter must be of type Natural.
3030 The return type must be the same as the type of the first argument. The size
3031 of this type can only be 8, 16, 32, or 64.
3032 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3033 The corresponding operator declaration must have parameters and result type
3034 that have the same root numeric type (for example, all three are long_float
3035 types). This simplifies the definition of operations that use type checking
3036 to perform dimensional checks:
3037
3038 @smallexample @c ada
3039 type Distance is new Long_Float;
3040 type Time     is new Long_Float;
3041 type Velocity is new Long_Float;
3042 function "/" (D : Distance; T : Time)
3043   return Velocity;
3044 pragma Import (Intrinsic, "/");
3045 @end smallexample
3046
3047 @noindent
3048 This common idiom is often programmed with a generic definition and an
3049 explicit body. The pragma makes it simpler to introduce such declarations.
3050 It incurs no overhead in compilation time or code size, because it is
3051 implemented as a single machine instruction.
3052 @end itemize
3053 @noindent
3054
3055 @ifset unw
3056 @findex Stdcall
3057 @cindex Convention Stdcall
3058 @item Stdcall
3059 This is relevant only to NT/Win95 implementations of GNAT,
3060 and specifies that the Stdcall calling sequence will be used, as defined
3061 by the NT API.
3062
3063 @findex DLL
3064 @cindex Convention DLL
3065 @item DLL
3066 This is equivalent to Stdcall.
3067
3068 @findex Win32
3069 @cindex Convention Win32
3070 @item Win32
3071 This is equivalent to Stdcall.
3072 @end ifset
3073
3074 @findex Stubbed
3075 @cindex Convention Stubbed
3076 @item Stubbed
3077 This is a special convention that indicates that the compiler
3078 should provide a stub body that raises @code{Program_Error}.
3079 @end table
3080
3081 @noindent
3082 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3083 that can be used to parametrize conventions and allow additional synonyms
3084 to be specified. For example if you have legacy code in which the convention
3085 identifier Fortran77 was used for Fortran, you can use the configuration
3086 pragma:
3087
3088 @smallexample @c ada
3089 pragma Convention_Identifier (Fortran77, Fortran);
3090 @end smallexample
3091
3092 @noindent
3093 And from now on the identifier Fortran77 may be used as a convention
3094 identifier (for example in an @code{Import} pragma) with the same
3095 meaning as Fortran.
3096
3097 @node Building Mixed Ada & C++ Programs
3098 @section Building Mixed Ada & C++ Programs
3099
3100 @noindent
3101 A programmer inexperienced with mixed-language development may find that
3102 building an application containing both Ada and C++ code can be a
3103 challenge. As a matter of fact, interfacing with C++ has not been
3104 standardized in the Ada 95 Reference Manual due to the immaturity of --
3105 and lack of standards for -- C++ at the time. This section gives a few
3106 hints that should make this task easier. The first section addresses
3107 the differences regarding interfacing with C. The second section
3108 looks into the delicate problem of linking the complete application from
3109 its Ada and C++ parts. The last section gives some hints on how the GNAT
3110 run time can be adapted in order to allow inter-language dispatching
3111 with a new C++ compiler.
3112
3113 @menu
3114 * Interfacing to C++::
3115 * Linking a Mixed C++ & Ada Program::
3116 * A Simple Example::
3117 * Adapting the Run Time to a New C++ Compiler::
3118 @end menu
3119
3120 @node Interfacing to C++
3121 @subsection Interfacing to C++
3122
3123 @noindent
3124 GNAT supports interfacing with C++ compilers generating code that is
3125 compatible with the standard Application Binary Interface of the given
3126 platform.
3127
3128 @noindent
3129 Interfacing can be done at 3 levels: simple data, subprograms, and
3130 classes. In the first two cases, GNAT offers a specific @var{Convention
3131 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3132 the names of subprograms, and currently, GNAT does not provide any help
3133 to solve the demangling problem. This problem can be addressed in two
3134 ways:
3135 @itemize @bullet
3136 @item
3137 by modifying the C++ code in order to force a C convention using
3138 the @code{extern "C"} syntax.
3139
3140 @item
3141 by figuring out the mangled name and use it as the Link_Name argument of
3142 the pragma import.
3143 @end itemize
3144
3145 @noindent
3146 Interfacing at the class level can be achieved by using the GNAT specific
3147 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3148 Reference Manual for additional information.
3149
3150 @node Linking a Mixed C++ & Ada Program
3151 @subsection Linking a Mixed C++ & Ada Program
3152
3153 @noindent
3154 Usually the linker of the C++ development system must be used to link
3155 mixed applications because most C++ systems will resolve elaboration
3156 issues (such as calling constructors on global class instances)
3157 transparently during the link phase. GNAT has been adapted to ease the
3158 use of a foreign linker for the last phase. Three cases can be
3159 considered:
3160 @enumerate
3161
3162 @item
3163 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3164 The C++ linker can simply be called by using the C++ specific driver
3165 called @code{c++}. Note that this setup is not very common because it
3166 may involve recompiling the whole GCC tree from sources, which makes it
3167 harder to upgrade the compilation system for one language without
3168 destabilizing the other.
3169
3170 @smallexample
3171 $ c++ -c file1.C
3172 $ c++ -c file2.C
3173 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3174 @end smallexample
3175
3176 @item
3177 Using GNAT and G++ from two different GCC installations: If both
3178 compilers are on the PATH, the previous method may be used. It is
3179 important to note that environment variables such as C_INCLUDE_PATH,
3180 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3181 at the same time and may make one of the two compilers operate
3182 improperly if set during invocation of the wrong compiler.  It is also
3183 very important that the linker uses the proper @file{libgcc.a} GCC
3184 library -- that is, the one from the C++ compiler installation. The
3185 implicit link command as suggested in the gnatmake command from the
3186 former example can be replaced by an explicit link command with the
3187 full-verbosity option in order to verify which library is used:
3188 @smallexample
3189 $ gnatbind ada_unit
3190 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3191 @end smallexample
3192 If there is a problem due to interfering environment variables, it can
3193 be worked around by using an intermediate script. The following example
3194 shows the proper script to use when GNAT has not been installed at its
3195 default location and g++ has been installed at its default location:
3196
3197 @smallexample
3198 $ cat ./my_script
3199 #!/bin/sh
3200 unset BINUTILS_ROOT
3201 unset GCC_ROOT
3202 c++ $*
3203 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3204 @end smallexample
3205
3206 @item
3207 Using a non-GNU C++ compiler: The commands previously described can be
3208 used to insure that the C++ linker is used. Nonetheless, you need to add
3209 the path to libgcc explicitly, since some libraries needed by GNAT are
3210 located in this directory:
3211
3212 @smallexample
3213 $ cat ./my_script
3214 #!/bin/sh
3215 CC $* `gcc -print-libgcc-file-name`
3216 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3217 @end smallexample
3218
3219 Where CC is the name of the non-GNU C++ compiler.
3220
3221 @end enumerate
3222
3223 @node A Simple Example
3224 @subsection  A Simple Example
3225 @noindent
3226 The following example, provided as part of the GNAT examples, shows how
3227 to achieve procedural interfacing between Ada and C++ in both
3228 directions. The C++ class A has two methods. The first method is exported
3229 to Ada by the means of an extern C wrapper function. The second method
3230 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3231 a limited record with a layout comparable to the C++ class. The Ada
3232 subprogram, in turn, calls the C++ method. So, starting from the C++
3233 main program, the process passes back and forth between the two
3234 languages.
3235
3236 @noindent
3237 Here are the compilation commands:
3238 @smallexample
3239 $ gnatmake -c simple_cpp_interface
3240 $ c++ -c cpp_main.C
3241 $ c++ -c ex7.C
3242 $ gnatbind -n simple_cpp_interface
3243 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3244       -lstdc++ ex7.o cpp_main.o
3245 @end smallexample
3246
3247 @noindent
3248 Here are the corresponding sources:
3249 @smallexample
3250
3251 //cpp_main.C
3252
3253 #include "ex7.h"
3254
3255 extern "C" @{
3256   void adainit (void);
3257   void adafinal (void);
3258   void method1 (A *t);
3259 @}
3260
3261 void method1 (A *t)
3262 @{
3263   t->method1 ();
3264 @}
3265
3266 int main ()
3267 @{
3268   A obj;
3269   adainit ();
3270   obj.method2 (3030);
3271   adafinal ();
3272 @}
3273
3274 //ex7.h
3275
3276 class Origin @{
3277  public:
3278   int o_value;
3279 @};
3280 class A : public Origin @{
3281  public:
3282   void method1 (void);
3283   virtual void method2 (int v);
3284   A();
3285   int   a_value;
3286 @};
3287
3288 //ex7.C
3289
3290 #include "ex7.h"
3291 #include <stdio.h>
3292
3293 extern "C" @{ void ada_method2 (A *t, int v);@}
3294
3295 void A::method1 (void)
3296 @{
3297   a_value = 2020;
3298   printf ("in A::method1, a_value = %d \n",a_value);
3299
3300 @}
3301
3302 void A::method2 (int v)
3303 @{
3304    ada_method2 (this, v);
3305    printf ("in A::method2, a_value = %d \n",a_value);
3306
3307 @}
3308
3309 A::A(void)
3310 @{
3311    a_value = 1010;
3312   printf ("in A::A, a_value = %d \n",a_value);
3313 @}
3314
3315 -- Ada sources
3316 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3317
3318    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3319    @b{begin}
3320       Method1 (This);
3321       This.A_Value := V;
3322    @b{end} Ada_Method2;
3323
3324 @b{end} Simple_Cpp_Interface;
3325
3326 @b{package} Simple_Cpp_Interface @b{is}
3327    @b{type} A @b{is} @b{limited}
3328       @b{record}
3329          O_Value : Integer;
3330          A_Value : Integer;
3331       @b{end} @b{record};
3332    @b{pragma} Convention (C, A);
3333
3334    @b{procedure} Method1 (This : @b{in} @b{out} A);
3335    @b{pragma} Import (C, Method1);
3336
3337    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3338    @b{pragma} Export (C, Ada_Method2);
3339
3340 @b{end} Simple_Cpp_Interface;
3341 @end smallexample
3342
3343 @node Adapting the Run Time to a New C++ Compiler
3344 @subsection Adapting the Run Time to a New C++ Compiler
3345 @noindent
3346 GNAT offers the capability to derive Ada 95 tagged types directly from
3347 preexisting C++ classes and . See ``Interfacing with C++'' in the
3348 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3349 such a goal
3350 has been made user configurable through a GNAT library unit
3351 @code{Interfaces.CPP}. The default version of this file is adapted to
3352 the GNU C++ compiler. Internal knowledge of the virtual
3353 table layout used by the new C++ compiler is needed to configure
3354 properly this unit. The Interface of this unit is known by the compiler
3355 and cannot be changed except for the value of the constants defining the
3356 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3357 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3358 of this unit for more details.
3359
3360 @node Comparison between GNAT and C/C++ Compilation Models
3361 @section Comparison between GNAT and C/C++ Compilation Models
3362
3363 @noindent
3364 The GNAT model of compilation is close to the C and C++ models. You can
3365 think of Ada specs as corresponding to header files in C. As in C, you
3366 don't need to compile specs; they are compiled when they are used. The
3367 Ada @code{with} is similar in effect to the @code{#include} of a C
3368 header.
3369
3370 One notable difference is that, in Ada, you may compile specs separately
3371 to check them for semantic and syntactic accuracy. This is not always
3372 possible with C headers because they are fragments of programs that have
3373 less specific syntactic or semantic rules.
3374
3375 The other major difference is the requirement for running the binder,
3376 which performs two important functions. First, it checks for
3377 consistency. In C or C++, the only defense against assembling
3378 inconsistent programs lies outside the compiler, in a makefile, for
3379 example. The binder satisfies the Ada requirement that it be impossible
3380 to construct an inconsistent program when the compiler is used in normal
3381 mode.
3382
3383 @cindex Elaboration order control
3384 The other important function of the binder is to deal with elaboration
3385 issues. There are also elaboration issues in C++ that are handled
3386 automatically. This automatic handling has the advantage of being
3387 simpler to use, but the C++ programmer has no control over elaboration.
3388 Where @code{gnatbind} might complain there was no valid order of
3389 elaboration, a C++ compiler would simply construct a program that
3390 malfunctioned at run time.
3391
3392 @node Comparison between GNAT and Conventional Ada Library Models
3393 @section Comparison between GNAT and Conventional Ada Library Models
3394
3395 @noindent
3396 This section is intended to be useful to Ada programmers who have
3397 previously used an Ada compiler implementing the traditional Ada library
3398 model, as described in the Ada 95 Language Reference Manual. If you
3399 have not used such a system, please go on to the next section.
3400
3401 @cindex GNAT library
3402 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
3403 source files themselves acts as the library. Compiling Ada programs does
3404 not generate any centralized information, but rather an object file and
3405 a ALI file, which are of interest only to the binder and linker.
3406 In a traditional system, the compiler reads information not only from
3407 the source file being compiled, but also from the centralized library.
3408 This means that the effect of a compilation depends on what has been
3409 previously compiled. In particular:
3410
3411 @itemize @bullet
3412 @item
3413 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3414 to the version of the unit most recently compiled into the library.
3415
3416 @item
3417 Inlining is effective only if the necessary body has already been
3418 compiled into the library.
3419
3420 @item
3421 Compiling a unit may obsolete other units in the library.
3422 @end itemize
3423
3424 @noindent
3425 In GNAT, compiling one unit never affects the compilation of any other
3426 units because the compiler reads only source files. Only changes to source
3427 files can affect the results of a compilation. In particular:
3428
3429 @itemize @bullet
3430 @item
3431 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3432 to the source version of the unit that is currently accessible to the
3433 compiler.
3434
3435 @item
3436 @cindex Inlining
3437 Inlining requires the appropriate source files for the package or
3438 subprogram bodies to be available to the compiler. Inlining is always
3439 effective, independent of the order in which units are complied.
3440
3441 @item
3442 Compiling a unit never affects any other compilations. The editing of
3443 sources may cause previous compilations to be out of date if they
3444 depended on the source file being modified.
3445 @end itemize
3446
3447 @noindent
3448 The most important result of these differences is that order of compilation
3449 is never significant in GNAT. There is no situation in which one is
3450 required to do one compilation before another. What shows up as order of
3451 compilation requirements in the traditional Ada library becomes, in
3452 GNAT, simple source dependencies; in other words, there is only a set
3453 of rules saying what source files must be present when a file is
3454 compiled.
3455
3456 @ifset vms
3457 @node Placement of temporary files
3458 @section Placement of temporary files
3459 @cindex Temporary files (user control over placement)
3460
3461 @noindent
3462 GNAT creates temporary files in the directory designated by the environment
3463 variable @env{TMPDIR}.
3464 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3465 for detailed information on how environment variables are resolved.
3466 For most users the easiest way to make use of this feature is to simply
3467 define @env{TMPDIR} as a job level logical name).
3468 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3469 for compiler temporary files, then you can include something like the
3470 following command in your @file{LOGIN.COM} file:
3471
3472 @smallexample
3473 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3474 @end smallexample
3475
3476 @noindent
3477 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3478 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3479 designated by @env{TEMP}.
3480 If none of these environment variables are defined then GNAT uses the
3481 directory designated by the logical name @code{SYS$SCRATCH:}
3482 (by default the user's home directory). If all else fails
3483 GNAT uses the current directory for temporary files.
3484 @end ifset
3485
3486
3487 @c *************************
3488 @node Compiling Using gcc
3489 @chapter Compiling Using @code{gcc}
3490
3491 @noindent
3492 This chapter discusses how to compile Ada programs using the @code{gcc}
3493 command. It also describes the set of switches
3494 that can be used to control the behavior of the compiler.
3495 @menu
3496 * Compiling Programs::
3497 * Switches for gcc::
3498 * Search Paths and the Run-Time Library (RTL)::
3499 * Order of Compilation Issues::
3500 * Examples::
3501 @end menu
3502
3503 @node Compiling Programs
3504 @section Compiling Programs
3505
3506 @noindent
3507 The first step in creating an executable program is to compile the units
3508 of the program using the @code{gcc} command. You must compile the
3509 following files:
3510
3511 @itemize @bullet
3512 @item
3513 the body file (@file{.adb}) for a library level subprogram or generic
3514 subprogram
3515
3516 @item
3517 the spec file (@file{.ads}) for a library level package or generic
3518 package that has no body
3519
3520 @item
3521 the body file (@file{.adb}) for a library level package
3522 or generic package that has a body
3523
3524 @end itemize
3525
3526 @noindent
3527 You need @emph{not} compile the following files
3528
3529 @itemize @bullet
3530
3531 @item
3532 the spec of a library unit which has a body
3533
3534 @item
3535 subunits
3536 @end itemize
3537
3538 @noindent
3539 because they are compiled as part of compiling related units. GNAT
3540 package specs
3541 when the corresponding body is compiled, and subunits when the parent is
3542 compiled.
3543
3544 @cindex cannot generate code
3545 If you attempt to compile any of these files, you will get one of the
3546 following error messages (where fff is the name of the file you compiled):
3547
3548 @smallexample
3549 cannot generate code for file @var{fff} (package spec)
3550 to check package spec, use -gnatc
3551
3552 cannot generate code for file @var{fff} (missing subunits)
3553 to check parent unit, use -gnatc
3554
3555 cannot generate code for file @var{fff} (subprogram spec)
3556 to check subprogram spec, use -gnatc
3557
3558 cannot generate code for file @var{fff} (subunit)
3559 to check subunit, use -gnatc
3560 @end smallexample
3561
3562 @noindent
3563 As indicated by the above error messages, if you want to submit
3564 one of these files to the compiler to check for correct semantics
3565 without generating code, then use the @option{-gnatc} switch.
3566
3567 The basic command for compiling a file containing an Ada unit is
3568
3569 @smallexample
3570 $ gcc -c [@var{switches}] @file{file name}
3571 @end smallexample
3572
3573 @noindent
3574 where @var{file name} is the name of the Ada file (usually
3575 having an extension
3576 @file{.ads} for a spec or @file{.adb} for a body).
3577 @ifclear vms
3578 You specify the
3579 @option{-c} switch to tell @code{gcc} to compile, but not link, the file.
3580 @end ifclear
3581 The result of a successful compilation is an object file, which has the
3582 same name as the source file but an extension of @file{.o} and an Ada
3583 Library Information (ALI) file, which also has the same name as the
3584 source file, but with @file{.ali} as the extension. GNAT creates these
3585 two output files in the current directory, but you may specify a source
3586 file in any directory using an absolute or relative path specification
3587 containing the directory information.
3588
3589 @findex gnat1
3590 @code{gcc} is actually a driver program that looks at the extensions of
3591 the file arguments and loads the appropriate compiler. For example, the
3592 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3593 These programs are in directories known to the driver program (in some
3594 configurations via environment variables you set), but need not be in
3595 your path. The @code{gcc} driver also calls the assembler and any other
3596 utilities needed to complete the generation of the required object
3597 files.
3598
3599 It is possible to supply several file names on the same @code{gcc}
3600 command. This causes @code{gcc} to call the appropriate compiler for
3601 each file. For example, the following command lists three separate
3602 files to be compiled:
3603
3604 @smallexample
3605 $ gcc -c x.adb y.adb z.c
3606 @end smallexample
3607
3608 @noindent
3609 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3610 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3611 The compiler generates three object files @file{x.o}, @file{y.o} and
3612 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3613 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3614 @ifclear vms
3615 except for
3616 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3617 @end ifclear
3618
3619 @node Switches for gcc
3620 @section Switches for @code{gcc}
3621
3622 @noindent
3623 The @code{gcc} command accepts switches that control the
3624 compilation process. These switches are fully described in this section.
3625 First we briefly list all the switches, in alphabetical order, then we
3626 describe the switches in more detail in functionally grouped sections.
3627
3628 @menu
3629 * Output and Error Message Control::
3630 * Warning Message Control::
3631 * Debugging and Assertion Control::
3632 * Validity Checking::
3633 * Style Checking::
3634 * Run-Time Checks::
3635 * Stack Overflow Checking::
3636 * Using gcc for Syntax Checking::
3637 * Using gcc for Semantic Checking::
3638 * Compiling Ada 83 Programs::
3639 * Character Set Control::
3640 * File Naming Control::
3641 * Subprogram Inlining Control::
3642 * Auxiliary Output Control::
3643 * Debugging Control::
3644 * Exception Handling Control::
3645 * Units to Sources Mapping Files::
3646 * Integrated Preprocessing::
3647 * Code Generation Control::
3648 @ifset vms
3649 * Return Codes::
3650 @end ifset
3651 @end menu
3652
3653 @table @option
3654 @c !sort!
3655 @ifclear vms
3656 @cindex @option{-b} (@code{gcc})
3657 @item -b @var{target}
3658 Compile your program to run on @var{target}, which is the name of a
3659 system configuration. You must have a GNAT cross-compiler built if
3660 @var{target} is not the same as your host system.
3661
3662 @item -B@var{dir}
3663 @cindex @option{-B} (@code{gcc})
3664 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3665 from @var{dir} instead of the default location. Only use this switch
3666 when multiple versions of the GNAT compiler are available. See the
3667 @code{gcc} manual page for further details. You would normally use the
3668 @option{-b} or @option{-V} switch instead.
3669
3670 @item -c
3671 @cindex @option{-c} (@code{gcc})
3672 Compile. Always use this switch when compiling Ada programs.
3673
3674 Note: for some other languages when using @code{gcc}, notably in
3675 the case of C and C++, it is possible to use
3676 use @code{gcc} without a @option{-c} switch to
3677 compile and link in one step. In the case of GNAT, you
3678 cannot use this approach, because the binder must be run
3679 and @code{gcc} cannot be used to run the GNAT binder.
3680 @end ifclear
3681
3682 @item -fno-inline
3683 @cindex @option{-fno-inline} (@code{gcc})
3684 Suppresses all back-end inlining, even if other optimization or inlining
3685 switches are set.
3686 This includes suppression of inlining that results
3687 from the use of the pragma @code{Inline_Always}.
3688 See also @option{-gnatn} and @option{-gnatN}.
3689
3690 @item -fno-strict-aliasing
3691 @cindex @option{-fno-strict-aliasing} (@code{gcc})
3692 Causes the compiler to avoid assumptions regarding non-aliasing
3693 of objects of different types. See section
3694 @pxref{Optimization and Strict Aliasing} for details.
3695
3696 @item -fstack-check
3697 @cindex @option{-fstack-check} (@code{gcc})
3698 Activates stack checking.
3699 See @ref{Stack Overflow Checking} for details of the use of this option.
3700
3701 @item ^-g^/DEBUG^
3702 @cindex @option{^-g^/DEBUG^} (@code{gcc})
3703 Generate debugging information. This information is stored in the object
3704 file and copied from there to the final executable file by the linker,
3705 where it can be read by the debugger. You must use the
3706 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3707
3708 @item -gnat83
3709 @cindex @option{-gnat83} (@code{gcc})
3710 Enforce Ada 83 restrictions.
3711
3712 @item -gnata
3713 @cindex @option{-gnata} (@code{gcc})
3714 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3715 activated.
3716
3717 @item -gnatA
3718 @cindex @option{-gnatA} (@code{gcc})
3719 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3720 it will be ignored.
3721
3722 @item -gnatb
3723 @cindex @option{-gnatb} (@code{gcc})
3724 Generate brief messages to @file{stderr} even if verbose mode set.
3725
3726 @item -gnatc
3727 @cindex @option{-gnatc} (@code{gcc})
3728 Check syntax and semantics only (no code generation attempted).
3729
3730 @item -gnatd
3731 @cindex @option{-gnatd} (@code{gcc})
3732 Specify debug options for the compiler. The string of characters after
3733 the @option{-gnatd} specify the specific debug options. The possible
3734 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3735 compiler source file @file{debug.adb} for details of the implemented
3736 debug options. Certain debug options are relevant to applications
3737 programmers, and these are documented at appropriate points in this
3738 users guide.
3739
3740 @item -gnatD
3741 @cindex @option{-gnatD} (@code{gcc})
3742 Create expanded source files for source level debugging. This switch
3743 also suppress generation of cross-reference information
3744 (see @option{-gnatx}).
3745
3746 @item -gnatec=@var{path}
3747 @cindex @option{-gnatec} (@code{gcc})
3748 Specify a configuration pragma file
3749 @ifclear vms
3750 (the equal sign is optional)
3751 @end ifclear
3752 (see @ref{The Configuration Pragmas Files}).
3753
3754 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3755 @cindex @option{-gnateD} (@code{gcc})
3756 Defines a symbol, associated with value, for preprocessing.
3757 (see @ref{Integrated Preprocessing})
3758
3759 @item -gnatef
3760 @cindex @option{-gnatef} (@code{gcc})
3761 Display full source path name in brief error messages.
3762
3763 @item -gnatem=@var{path}
3764 @cindex @option{-gnatem} (@code{gcc})
3765 Specify a mapping file
3766 @ifclear vms
3767 (the equal sign is optional)
3768 @end ifclear
3769 (see @ref{Units to Sources Mapping Files}).
3770
3771 @item -gnatep=@var{file}
3772 @cindex @option{-gnatep} (@code{gcc})
3773 Specify a preprocessing data file
3774 @ifclear vms
3775 (the equal sign is optional)
3776 @end ifclear
3777 (see @ref{Integrated Preprocessing}).
3778
3779 @item -gnatE
3780 @cindex @option{-gnatE} (@code{gcc})
3781 Full dynamic elaboration checks.
3782
3783 @item -gnatf
3784 @cindex @option{-gnatf} (@code{gcc})
3785 Full errors. Multiple errors per line, all undefined references, do not
3786 attempt to suppress cascaded errors.
3787
3788 @item -gnatF
3789 @cindex @option{-gnatF} (@code{gcc})
3790 Externals names are folded to all uppercase.
3791
3792 @item -gnatg
3793 @cindex @option{-gnatg} (@code{gcc})
3794 Internal GNAT implementation mode. This should not be used for
3795 applications programs, it is intended only for use by the compiler
3796 and its run-time library. For documentation, see the GNAT sources.
3797 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3798 are generated on unreferenced entities, and all warnings are treated
3799 as errors.
3800
3801 @item -gnatG
3802 @cindex @option{-gnatG} (@code{gcc})
3803 List generated expanded code in source form.
3804
3805 @item ^-gnath^/HELP^
3806 @cindex @option{^-gnath^/HELP^} (@code{gcc})
3807 Output usage information. The output is written to @file{stdout}.
3808
3809 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3810 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
3811 Identifier character set
3812 @ifclear vms
3813 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3814 @end ifclear
3815 @ifset vms
3816 For details of the possible selections for @var{c},
3817 see @xref{Character Set Control}.
3818 @end ifset
3819
3820 @item -gnatk=@var{n}
3821 @cindex @option{-gnatk} (@code{gcc})
3822 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3823
3824 @item -gnatl
3825 @cindex @option{-gnatl} (@code{gcc})
3826 Output full source listing with embedded error messages.
3827
3828 @item -gnatL
3829 @cindex @option{-gnatL} (@code{gcc})
3830 Use the longjmp/setjmp method for exception handling
3831
3832 @item -gnatm=@var{n}
3833 @cindex @option{-gnatm} (@code{gcc})
3834 Limit number of detected error or warning messages to @var{n}
3835 where @var{n} is in the range 1..999_999. The default setting if
3836 no switch is given is 9999. Compilation is terminated if this
3837 limit is exceeded.
3838
3839 @item -gnatn
3840 @cindex @option{-gnatn} (@code{gcc})
3841 Activate inlining for subprograms for which
3842 pragma @code{inline} is specified. This inlining is performed
3843 by the GCC back-end.
3844
3845 @item -gnatN
3846 @cindex @option{-gnatN} (@code{gcc})
3847 Activate front end inlining for subprograms for which
3848 pragma @code{Inline} is specified. This inlining is performed
3849 by the front end and will be visible in the
3850 @option{-gnatG} output.
3851 In some cases, this has proved more effective than the back end
3852 inlining resulting from the use of
3853 @option{-gnatn}.
3854 Note that
3855 @option{-gnatN} automatically implies
3856 @option{-gnatn} so it is not necessary
3857 to specify both options. There are a few cases that the back-end inlining
3858 catches that cannot be dealt with in the front-end.
3859
3860 @item -gnato
3861 @cindex @option{-gnato} (@code{gcc})
3862 Enable numeric overflow checking (which is not normally enabled by
3863 default). Not that division by zero is a separate check that is not
3864 controlled by this switch (division by zero checking is on by default).
3865
3866 @item -gnatp
3867 @cindex @option{-gnatp} (@code{gcc})
3868 Suppress all checks.
3869
3870 @item -gnatP
3871 @cindex @option{-gnatP} (@code{gcc})
3872 Enable polling. This is required on some systems (notably Windows NT) to
3873 obtain asynchronous abort and asynchronous transfer of control capability.
3874 See the description of pragma Polling in the GNAT Reference Manual for
3875 full details.
3876
3877 @item -gnatq
3878 @cindex @option{-gnatq} (@code{gcc})
3879 Don't quit; try semantics, even if parse errors.
3880
3881 @item -gnatQ
3882 @cindex @option{-gnatQ} (@code{gcc})
3883 Don't quit; generate @file{ALI} and tree files even if illegalities.
3884
3885 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3886 @cindex @option{-gnatR} (@code{gcc})
3887 Output representation information for declared types and objects.
3888
3889 @item -gnats
3890 @cindex @option{-gnats} (@code{gcc})
3891 Syntax check only.
3892
3893 @item -gnatS
3894 @cindex @option{-gnatS} (@code{gcc})
3895 Print package Standard.
3896
3897 @item -gnatt
3898 @cindex @option{-gnatt} (@code{gcc})
3899 Generate tree output file.
3900
3901 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3902 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@code{gcc})
3903 All compiler tables start at @var{nnn} times usual starting size.
3904
3905 @item -gnatu
3906 @cindex @option{-gnatu} (@code{gcc})
3907 List units for this compilation.
3908
3909 @item -gnatU
3910 @cindex @option{-gnatU} (@code{gcc})
3911 Tag all error messages with the unique string ``error:''
3912
3913 @item -gnatv
3914 @cindex @option{-gnatv} (@code{gcc})
3915 Verbose mode. Full error output with source lines to @file{stdout}.
3916
3917 @item -gnatV
3918 @cindex @option{-gnatV} (@code{gcc})
3919 Control level of validity checking. See separate section describing
3920 this feature.
3921
3922 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
3923 @cindex @option{^-gnatw^/WARNINGS^} (@code{gcc})
3924 Warning mode where
3925 ^@var{xxx} is a string of option letters that^the list of options^ denotes
3926 the exact warnings that
3927 are enabled or disabled. (see @ref{Warning Message Control})
3928
3929 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3930 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
3931 Wide character encoding method
3932 @ifclear vms
3933 (@var{e}=n/h/u/s/e/8).
3934 @end ifclear
3935 @ifset vms
3936 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3937 @end ifset
3938
3939 @item -gnatx
3940 @cindex @option{-gnatx} (@code{gcc})
3941 Suppress generation of cross-reference information.
3942
3943 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3944 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@code{gcc})
3945 Enable built-in style checks. (see @ref{Style Checking})
3946
3947 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3948 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@code{gcc})
3949 Distribution stub generation and compilation
3950 @ifclear vms
3951 (@var{m}=r/c for receiver/caller stubs).
3952 @end ifclear
3953 @ifset vms
3954 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3955 to be generated and compiled).
3956 @end ifset
3957
3958 @item -gnatZ
3959 Use the zero cost method for exception handling
3960
3961 @item ^-I^/SEARCH=^@var{dir}
3962 @cindex @option{^-I^/SEARCH^} (@code{gcc})
3963 @cindex RTL
3964 Direct GNAT to search the @var{dir} directory for source files needed by
3965 the current compilation
3966 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3967
3968 @item ^-I-^/NOCURRENT_DIRECTORY^
3969 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gcc})
3970 @cindex RTL
3971 Except for the source file named in the command line, do not look for source
3972 files in the directory containing the source file named in the command line
3973 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3974
3975 @ifclear vms
3976 @item -mbig-switch
3977 @cindex @option{-mbig-switch} (@command{gcc})
3978 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
3979 This standard gcc switch causes the compiler to use larger offsets in its
3980 jump table representation for @code{case} statements.
3981 This may result in less efficient code, but is sometimes necessary
3982 (for example on HP-UX targets)
3983 @cindex HP-UX and @option{-mbig-switch} option
3984 in order to compile large and/or nested @code{case} statements.
3985
3986 @item -o @var{file}
3987 @cindex @option{-o} (@code{gcc})
3988 This switch is used in @code{gcc} to redirect the generated object file
3989 and its associated ALI file. Beware of this switch with GNAT, because it may
3990 cause the object file and ALI file to have different names which in turn
3991 may confuse the binder and the linker.
3992 @end ifclear
3993
3994 @item -nostdinc
3995 @cindex @option{-nostdinc} (@command{gcc})
3996 Inhibit the search of the default location for the GNAT Run Time
3997 Library (RTL) source files.
3998
3999 @item -nostdlib
4000 @cindex @option{-nostdlib} (@command{gcc})
4001 Inhibit the search of the default location for the GNAT Run Time
4002 Library (RTL) ALI files.
4003
4004 @ifclear vms
4005 @item -O[@var{n}]
4006 @cindex @option{-O} (@code{gcc})
4007 @var{n} controls the optimization level.
4008
4009 @table @asis
4010 @item n = 0
4011 No optimization, the default setting if no @option{-O} appears
4012
4013 @item n = 1
4014 Normal optimization, the default if you specify @option{-O} without
4015 an operand.
4016
4017 @item n = 2
4018 Extensive optimization
4019
4020 @item n = 3
4021 Extensive optimization with automatic inlining of subprograms not
4022 specified by pragma @code{Inline}. This applies only to
4023 inlining within a unit. For details on control of inlining
4024 see @xref{Subprogram Inlining Control}.
4025 @end table
4026 @end ifclear
4027
4028 @ifset vms
4029 @item  /NOOPTIMIZE
4030 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4031 Equivalent to @option{/OPTIMIZE=NONE}.
4032 This is the default behavior in the absence of an @option{/OPTMIZE}
4033 qualifier.
4034
4035 @item /OPTIMIZE[=(keyword[,...])]
4036 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4037 Selects the level of optimization for your program. The supported
4038 keywords are as follows:
4039 @table @code
4040 @item   ALL
4041 Perform most optimizations, including those that
4042 are expensive.
4043 This is the default if the @option{/OPTMIZE} qualifier is supplied
4044 without keyword options.
4045
4046 @item   NONE
4047 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4048
4049 @item SOME
4050 Perform some optimizations, but omit ones that are costly.
4051
4052 @item   DEVELOPMENT
4053 Same as @code{SOME}.
4054
4055 @item   INLINING
4056 Full optimization, and also attempt automatic inlining of small
4057 subprograms within a unit even when pragma @code{Inline}
4058 is not specified (@pxref{Inlining of Subprograms}).
4059
4060 @item   UNROLL_LOOPS
4061 Try to unroll loops. This keyword may be specified together with
4062 any keyword above other than @code{NONE}. Loop unrolling
4063 usually, but not always, improves the performance of programs.
4064 @end table
4065 @end ifset
4066
4067 @ifclear vms
4068 @item -pass-exit-codes
4069 @cindex @option{-pass-exit-codes} (@code{gcc})
4070 Catch exit codes from the compiler and use the most meaningful as
4071 exit status.
4072 @end ifclear
4073
4074 @item --RTS=@var{rts-path}
4075 @cindex @option{--RTS} (@code{gcc})
4076 Specifies the default location of the runtime library. Same meaning as the
4077 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
4078
4079 @item ^-S^/ASM^
4080 @cindex @option{^-S^/ASM^} (@code{gcc})
4081 ^Used in place of @option{-c} to^Used to^
4082 cause the assembler source file to be
4083 generated, using @file{^.s^.S^} as the extension,
4084 instead of the object file.
4085 This may be useful if you need to examine the generated assembly code.
4086
4087 @item ^-fverbose-asm^/VERBOSE_ASM^
4088 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@code{gcc})
4089 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4090 to cause the generated assembly code file to be annotated with variable
4091 names, making it significantly easier to follow.
4092
4093 @item ^-v^/VERBOSE^
4094 @cindex @option{^-v^/VERBOSE^} (@code{gcc})
4095 Show commands generated by the @code{gcc} driver. Normally used only for
4096 debugging purposes or if you need to be sure what version of the
4097 compiler you are executing.
4098
4099 @ifclear vms
4100 @item -V @var{ver}
4101 @cindex @option{-V} (@code{gcc})
4102 Execute @var{ver} version of the compiler. This is the @code{gcc}
4103 version, not the GNAT version.
4104 @end ifclear
4105
4106 @end table
4107
4108 @ifclear vms
4109 You may combine a sequence of GNAT switches into a single switch. For
4110 example, the combined switch
4111
4112 @cindex Combining GNAT switches
4113 @smallexample
4114 -gnatofi3
4115 @end smallexample
4116
4117 @noindent
4118 is equivalent to specifying the following sequence of switches:
4119
4120 @smallexample
4121 -gnato -gnatf -gnati3
4122 @end smallexample
4123 @end ifclear
4124
4125
4126 @c NEED TO CHECK THIS FOR VMS
4127
4128 @noindent
4129 The following restrictions apply to the combination of switches
4130 in this manner:
4131
4132 @itemize @bullet
4133 @item
4134 The switch @option{-gnatc} if combined with other switches must come
4135 first in the string.
4136
4137 @item
4138 The switch @option{-gnats} if combined with other switches must come
4139 first in the string.
4140
4141 @item
4142 The switches
4143 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4144 may not be combined with any other switches.
4145
4146 @ifclear vms
4147 @item
4148 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4149 switch), then all further characters in the switch are interpreted
4150 as style modifiers (see description of @option{-gnaty}).
4151
4152 @item
4153 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4154 switch), then all further characters in the switch are interpreted
4155 as debug flags (see description of @option{-gnatd}).
4156
4157 @item
4158 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4159 switch), then all further characters in the switch are interpreted
4160 as warning mode modifiers (see description of @option{-gnatw}).
4161
4162 @item
4163 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4164 switch), then all further characters in the switch are interpreted
4165 as validity checking options (see description of @option{-gnatV}).
4166 @end ifclear
4167 @end itemize
4168
4169
4170 @node Output and Error Message Control
4171 @subsection Output and Error Message Control
4172 @findex stderr
4173
4174 @noindent
4175 The standard default format for error messages is called ``brief format''.
4176 Brief format messages are written to @file{stderr} (the standard error
4177 file) and have the following form:
4178
4179 @smallexample
4180 e.adb:3:04: Incorrect spelling of keyword "function"
4181 e.adb:4:20: ";" should be "is"
4182 @end smallexample
4183
4184 @noindent
4185 The first integer after the file name is the line number in the file,
4186 and the second integer is the column number within the line.
4187 @code{glide} can parse the error messages
4188 and point to the referenced character.
4189 The following switches provide control over the error message
4190 format:
4191
4192 @table @option
4193 @c !sort!
4194 @item -gnatv
4195 @cindex @option{-gnatv} (@code{gcc})
4196 @findex stdout
4197 @ifclear vms
4198 The v stands for verbose.
4199 @end ifclear
4200 The effect of this setting is to write long-format error
4201 messages to @file{stdout} (the standard output file.
4202 The same program compiled with the
4203 @option{-gnatv} switch would generate:
4204
4205 @smallexample
4206 @cartouche
4207 3. funcion X (Q : Integer)
4208    |
4209 >>> Incorrect spelling of keyword "function"
4210 4. return Integer;
4211                  |
4212 >>> ";" should be "is"
4213 @end cartouche
4214 @end smallexample
4215
4216 @noindent
4217 The vertical bar indicates the location of the error, and the @samp{>>>}
4218 prefix can be used to search for error messages. When this switch is
4219 used the only source lines output are those with errors.
4220
4221 @item -gnatl
4222 @cindex @option{-gnatl} (@code{gcc})
4223 @ifclear vms
4224 The @code{l} stands for list.
4225 @end ifclear
4226 This switch causes a full listing of
4227 the file to be generated. The output might look as follows:
4228
4229 @smallexample
4230 @cartouche
4231  1. procedure E is
4232  2.    V : Integer;
4233  3.    funcion X (Q : Integer)
4234        |
4235     >>> Incorrect spelling of keyword "function"
4236  4.     return Integer;
4237                       |
4238     >>> ";" should be "is"
4239  5.    begin
4240  6.       return Q + Q;
4241  7.    end;
4242  8. begin
4243  9.    V := X + X;
4244 10.end E;
4245 @end cartouche
4246 @end smallexample
4247
4248 @noindent
4249 @findex stderr
4250 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4251 standard output is redirected, a brief summary is written to
4252 @file{stderr} (standard error) giving the number of error messages and
4253 warning messages generated.
4254
4255 @item -gnatU
4256 @cindex @option{-gnatU} (@code{gcc})
4257 This switch forces all error messages to be preceded by the unique
4258 string ``error:''. This means that error messages take a few more
4259 characters in space, but allows easy searching for and identification
4260 of error messages.
4261
4262 @item -gnatb
4263 @cindex @option{-gnatb} (@code{gcc})
4264 @ifclear vms
4265 The @code{b} stands for brief.
4266 @end ifclear
4267 This switch causes GNAT to generate the
4268 brief format error messages to @file{stderr} (the standard error
4269 file) as well as the verbose
4270 format message or full listing (which as usual is written to
4271 @file{stdout} (the standard output file).
4272
4273 @item -gnatm^^=^@var{n}
4274 @cindex @option{-gnatm} (@code{gcc})
4275 @ifclear vms
4276 The @code{m} stands for maximum.
4277 @end ifclear
4278 @var{n} is a decimal integer in the
4279 range of 1 to 999 and limits the number of error messages to be
4280 generated. For example, using @option{-gnatm2} might yield
4281
4282 @smallexample
4283 e.adb:3:04: Incorrect spelling of keyword "function"
4284 e.adb:5:35: missing ".."
4285 fatal error: maximum errors reached
4286 compilation abandoned
4287 @end smallexample
4288
4289 @item -gnatf
4290 @cindex @option{-gnatf} (@code{gcc})
4291 @cindex Error messages, suppressing
4292 @ifclear vms
4293 The @code{f} stands for full.
4294 @end ifclear
4295 Normally, the compiler suppresses error messages that are likely to be
4296 redundant. This switch causes all error
4297 messages to be generated. In particular, in the case of
4298 references to undefined variables. If a given variable is referenced
4299 several times, the normal format of messages is
4300 @smallexample
4301 e.adb:7:07: "V" is undefined (more references follow)
4302 @end smallexample
4303
4304 @noindent
4305 where the parenthetical comment warns that there are additional
4306 references to the variable @code{V}. Compiling the same program with the
4307 @option{-gnatf} switch yields
4308
4309 @smallexample
4310 e.adb:7:07: "V" is undefined
4311 e.adb:8:07: "V" is undefined
4312 e.adb:8:12: "V" is undefined
4313 e.adb:8:16: "V" is undefined
4314 e.adb:9:07: "V" is undefined
4315 e.adb:9:12: "V" is undefined
4316 @end smallexample
4317
4318 @noindent
4319 The @option{-gnatf} switch also generates additional information for
4320 some error messages.  Some examples are:
4321
4322 @itemize @bullet
4323 @item
4324 Full details on entities not available in high integrity mode
4325 @item
4326 Details on possibly non-portable unchecked conversion
4327 @item
4328 List possible interpretations for ambiguous calls
4329 @item
4330 Additional details on incorrect parameters
4331 @end itemize
4332
4333
4334 @item -gnatq
4335 @cindex @option{-gnatq} (@code{gcc})
4336 @ifclear vms
4337 The @code{q} stands for quit (really ``don't quit'').
4338 @end ifclear
4339 In normal operation mode, the compiler first parses the program and
4340 determines if there are any syntax errors. If there are, appropriate
4341 error messages are generated and compilation is immediately terminated.
4342 This switch tells
4343 GNAT to continue with semantic analysis even if syntax errors have been
4344 found. This may enable the detection of more errors in a single run. On
4345 the other hand, the semantic analyzer is more likely to encounter some
4346 internal fatal error when given a syntactically invalid tree.
4347
4348 @item -gnatQ
4349 @cindex @option{-gnatQ} (@code{gcc})
4350 In normal operation mode, the @file{ALI} file is not generated if any
4351 illegalities are detected in the program. The use of @option{-gnatQ} forces
4352 generation of the @file{ALI} file. This file is marked as being in
4353 error, so it cannot be used for binding purposes, but it does contain
4354 reasonably complete cross-reference information, and thus may be useful
4355 for use by tools (e.g. semantic browsing tools or integrated development
4356 environments) that are driven from the @file{ALI} file. This switch
4357 implies @option{-gnatq}, since the semantic phase must be run to get a
4358 meaningful ALI file.
4359
4360 In addition, if @option{-gnatt} is also specified, then the tree file is
4361 generated even if there are illegalities. It may be useful in this case
4362 to also specify @option{-gnatq} to ensure that full semantic processing
4363 occurs. The resulting tree file can be processed by ASIS, for the purpose
4364 of providing partial information about illegal units, but if the error
4365 causes the tree to be badly malformed, then ASIS may crash during the
4366 analysis.
4367
4368 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4369 being in error, @code{gnatmake} will attempt to recompile the source when it
4370 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4371
4372 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4373 since ALI files are never generated if @option{-gnats} is set.
4374
4375 @end table
4376
4377
4378 @node Warning Message Control
4379 @subsection Warning Message Control
4380 @cindex Warning messages
4381 @noindent
4382 In addition to error messages, which correspond to illegalities as defined
4383 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4384 situations.
4385
4386 First, the compiler considers some constructs suspicious and generates a
4387 warning message to alert you to a possible error. Second, if the
4388 compiler detects a situation that is sure to raise an exception at
4389 run time, it generates a warning message. The following shows an example
4390 of warning messages:
4391 @smallexample
4392 e.adb:4:24: warning: creation of object may raise Storage_Error
4393 e.adb:10:17: warning: static value out of range
4394 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4395 @end smallexample
4396
4397 @noindent
4398 GNAT considers a large number of situations as appropriate
4399 for the generation of warning messages. As always, warnings are not
4400 definite indications of errors. For example, if you do an out-of-range
4401 assignment with the deliberate intention of raising a
4402 @code{Constraint_Error} exception, then the warning that may be
4403 issued does not indicate an error. Some of the situations for which GNAT
4404 issues warnings (at least some of the time) are given in the following
4405 list. This list is not complete, and new warnings are often added to
4406 subsequent versions of GNAT. The list is intended to give a general idea
4407 of the kinds of warnings that are generated.
4408
4409 @itemize @bullet
4410 @item
4411 Possible infinitely recursive calls
4412
4413 @item
4414 Out-of-range values being assigned
4415
4416 @item
4417 Possible order of elaboration problems
4418
4419 @item
4420 Unreachable code
4421
4422 @item
4423 Fixed-point type declarations with a null range
4424
4425 @item
4426 Direct_IO or Sequential_IO instantiated with a type that has access values
4427
4428 @item
4429 Variables that are never assigned a value
4430
4431 @item
4432 Variables that are referenced before being initialized
4433
4434 @item
4435 Task entries with no corresponding @code{accept} statement
4436
4437 @item
4438 Duplicate accepts for the same task entry in a @code{select}
4439
4440 @item
4441 Objects that take too much storage
4442
4443 @item
4444 Unchecked conversion between types of differing sizes
4445
4446 @item
4447 Missing @code{return} statement along some execution path in a function
4448
4449 @item
4450 Incorrect (unrecognized) pragmas
4451
4452 @item
4453 Incorrect external names
4454
4455 @item
4456 Allocation from empty storage pool
4457
4458 @item
4459 Potentially blocking operation in protected type
4460
4461 @item
4462 Suspicious parenthesization of expressions
4463
4464 @item
4465 Mismatching bounds in an aggregate
4466
4467 @item
4468 Attempt to return local value by reference
4469
4470
4471 @item
4472 Premature instantiation of a generic body
4473
4474 @item
4475 Attempt to pack aliased components
4476
4477 @item
4478 Out of bounds array subscripts
4479
4480 @item
4481 Wrong length on string assignment
4482
4483 @item
4484 Violations of style rules if style checking is enabled
4485
4486 @item
4487 Unused @code{with} clauses
4488
4489 @item
4490 @code{Bit_Order} usage that does not have any effect
4491
4492 @item
4493 @code{Standard.Duration} used to resolve universal fixed expression
4494
4495 @item
4496 Dereference of possibly null value
4497
4498 @item
4499 Declaration that is likely to cause storage error
4500
4501 @item
4502 Internal GNAT unit @code{with}'ed by application unit
4503
4504 @item
4505 Values known to be out of range at compile time
4506
4507 @item
4508 Unreferenced labels and variables
4509
4510 @item
4511 Address overlays that could clobber memory
4512
4513 @item
4514 Unexpected initialization when address clause present
4515
4516 @item
4517 Bad alignment for address clause
4518
4519 @item
4520 Useless type conversions
4521
4522 @item
4523 Redundant assignment statements and other redundant constructs
4524
4525 @item
4526 Useless exception handlers
4527
4528 @item
4529 Accidental hiding of name by child unit
4530
4531
4532 @item
4533 Access before elaboration detected at compile time
4534
4535 @item
4536 A range in a @code{for} loop that is known to be null or might be null
4537
4538 @end itemize
4539
4540 @noindent
4541 The following switches are available to control the handling of
4542 warning messages:
4543
4544 @table @option
4545 @c !sort!
4546 @item -gnatwa
4547 @emph{Activate all optional errors.}
4548 @cindex @option{-gnatwa} (@code{gcc})
4549 This switch activates most optional warning messages, see remaining list
4550 in this section for details on optional warning messages that can be
4551 individually controlled.  The warnings that are not turned on by this
4552 switch are
4553 @option{-gnatwd} (implicit dereferencing),
4554 @option{-gnatwh} (hiding),
4555 and @option{-gnatwl} (elaboration warnings).
4556 All other optional warnings are turned on.
4557
4558 @item -gnatwA
4559 @emph{Suppress all optional errors.}
4560 @cindex @option{-gnatwA} (@code{gcc})
4561 This switch suppresses all optional warning messages, see remaining list
4562 in this section for details on optional warning messages that can be
4563 individually controlled.
4564
4565 @item -gnatwc
4566 @emph{Activate warnings on conditionals.}
4567 @cindex @option{-gnatwc} (@code{gcc})
4568 @cindex Conditionals, constant
4569 This switch activates warnings for conditional expressions used in
4570 tests that are known to be True or False at compile time. The default
4571 is that such warnings are not generated.
4572 Note that this warning does
4573 not get issued for the use of boolean variables or constants whose
4574 values are known at compile time, since this is a standard technique
4575 for conditional compilation in Ada, and this would generate too many
4576 ``false positive'' warnings.
4577 This warning can also be turned on using @option{-gnatwa}.
4578
4579 @item -gnatwC
4580 @emph{Suppress warnings on conditionals.}
4581 @cindex @option{-gnatwC} (@code{gcc})
4582 This switch suppresses warnings for conditional expressions used in
4583 tests that are known to be True or False at compile time.
4584
4585 @item -gnatwd
4586 @emph{Activate warnings on implicit dereferencing.}
4587 @cindex @option{-gnatwd} (@code{gcc})
4588 If this switch is set, then the use of a prefix of an access type
4589 in an indexed component, slice, or selected component without an
4590 explicit @code{.all} will generate a warning. With this warning
4591 enabled, access checks occur only at points where an explicit
4592 @code{.all} appears in the source code (assuming no warnings are
4593 generated as a result of this switch). The default is that such
4594 warnings are not generated.
4595 Note that @option{-gnatwa} does not affect the setting of
4596 this warning option.
4597
4598 @item -gnatwD
4599 @emph{Suppress warnings on implicit dereferencing.}
4600 @cindex @option{-gnatwD} (@code{gcc})
4601 @cindex Implicit dereferencing
4602 @cindex Dereferencing, implicit
4603 This switch suppresses warnings for implicit dereferences in
4604 indexed components, slices, and selected components.
4605
4606 @item -gnatwe
4607 @emph{Treat warnings as errors.}
4608 @cindex @option{-gnatwe} (@code{gcc})
4609 @cindex Warnings, treat as error
4610 This switch causes warning messages to be treated as errors.
4611 The warning string still appears, but the warning messages are counted
4612 as errors, and prevent the generation of an object file.
4613
4614 @item -gnatwf
4615 @emph{Activate warnings on unreferenced formals.}
4616 @cindex @option{-gnatwf} (@code{gcc})
4617 @cindex Formals, unreferenced
4618 This switch causes a warning to be generated if a formal parameter
4619 is not referenced in the body of the subprogram. This warning can
4620 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4621
4622 @item -gnatwF
4623 @emph{Suppress warnings on unreferenced formals.}
4624 @cindex @option{-gnatwF} (@code{gcc})
4625 This switch suppresses warnings for unreferenced formal
4626 parameters. Note that the
4627 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4628 effect of warning on unreferenced entities other than subprogram
4629 formals.
4630
4631 @item -gnatwg
4632 @emph{Activate warnings on unrecognized pragmas.}
4633 @cindex @option{-gnatwg} (@code{gcc})
4634 @cindex Pragmas, unrecognized
4635 This switch causes a warning to be generated if an unrecognized
4636 pragma is encountered. Apart from issuing this warning, the
4637 pragma is ignored and has no effect. This warning can
4638 also be turned on using @option{-gnatwa}. The default
4639 is that such warnings are issued (satisfying the Ada Reference
4640 Manual requirement that such warnings appear).
4641
4642 @item -gnatwG
4643 @emph{Suppress warnings on unrecognized pragmas.}
4644 @cindex @option{-gnatwG} (@code{gcc})
4645 This switch suppresses warnings for unrecognized pragmas.
4646
4647 @item -gnatwh
4648 @emph{Activate warnings on hiding.}
4649 @cindex @option{-gnatwh} (@code{gcc})
4650 @cindex Hiding of Declarations
4651 This switch activates warnings on hiding declarations.
4652 A declaration is considered hiding
4653 if it is for a non-overloadable entity, and it declares an entity with the
4654 same name as some other entity that is directly or use-visible. The default
4655 is that such warnings are not generated.
4656 Note that @option{-gnatwa} does not affect the setting of this warning option.
4657
4658 @item -gnatwH
4659 @emph{Suppress warnings on hiding.}
4660 @cindex @option{-gnatwH} (@code{gcc})
4661 This switch suppresses warnings on hiding declarations.
4662
4663 @item -gnatwi
4664 @emph{Activate warnings on implementation units.}
4665 @cindex @option{-gnatwi} (@code{gcc})
4666 This switch activates warnings for a @code{with} of an internal GNAT
4667 implementation unit, defined as any unit from the @code{Ada},
4668 @code{Interfaces}, @code{GNAT},
4669 ^^@code{DEC},^ or @code{System}
4670 hierarchies that is not
4671 documented in either the Ada Reference Manual or the GNAT
4672 Programmer's Reference Manual. Such units are intended only
4673 for internal implementation purposes and should not be @code{with}'ed
4674 by user programs. The default is that such warnings are generated
4675 This warning can also be turned on using @option{-gnatwa}.
4676
4677 @item -gnatwI
4678 @emph{Disable warnings on implementation units.}
4679 @cindex @option{-gnatwI} (@code{gcc})
4680 This switch disables warnings for a @code{with} of an internal GNAT
4681 implementation unit.
4682
4683 @item -gnatwj
4684 @emph{Activate warnings on obsolescent features (Annex J).}
4685 @cindex @option{-gnatwj} (@code{gcc})
4686 @cindex Features, obsolescent
4687 @cindex Obsolescent features
4688 If this warning option is activated, then warnings are generated for
4689 calls to subprograms marked with @code{pragma Obsolescent} and
4690 for use of features in Annex J of the Ada Reference Manual. In the
4691 case of Annex J, not all features are flagged. In particular use
4692 of the renamed packages (like @code{Text_IO}) and use of package
4693 @code{ASCII} are not flagged, since these are very common and
4694 would generate many annoying positive warnings. The default is that
4695 such warnings are not generated.
4696
4697 @item -gnatwJ
4698 @emph{Suppress warnings on obsolescent features (Annex J).}
4699 @cindex @option{-gnatwJ} (@code{gcc})
4700 This switch disables warnings on use of obsolescent features.
4701
4702 @item -gnatwk
4703 @emph{Activate warnings on variables that could be constants.}
4704 @cindex @option{-gnatwk} (@code{gcc})
4705 This switch activates warnings for variables that are initialized but
4706 never modified, and then could be declared constants.
4707
4708 @item -gnatwK
4709 @emph{Suppress warnings on variables that could be constants.}
4710 @cindex @option{-gnatwK} (@code{gcc})
4711 This switch disables warnings on variables that could be declared constants.
4712
4713 @item -gnatwl
4714 @emph{Activate warnings for missing elaboration pragmas.}
4715 @cindex @option{-gnatwl} (@code{gcc})
4716 @cindex Elaboration, warnings
4717 This switch activates warnings on missing
4718 @code{pragma Elaborate_All} statements.
4719 See the section in this guide on elaboration checking for details on
4720 when such pragma should be used. Warnings are also generated if you
4721 are using the static mode of elaboration, and a @code{pragma Elaborate}
4722 is encountered. The default is that such warnings
4723 are not generated.
4724 This warning is not automatically turned on by the use of @option{-gnatwa}.
4725
4726 @item -gnatwL
4727 @emph{Suppress warnings for missing elaboration pragmas.}
4728 @cindex @option{-gnatwL} (@code{gcc})
4729 This switch suppresses warnings on missing pragma Elaborate_All statements.
4730 See the section in this guide on elaboration checking for details on
4731 when such pragma should be used.
4732
4733 @item -gnatwm
4734 @emph{Activate warnings on modified but unreferenced variables.}
4735 @cindex @option{-gnatwm} (@code{gcc})
4736 This switch activates warnings for variables that are assigned (using
4737 an initialization value or with one or more assignment statements) but
4738 whose value is never read. The warning is suppressed for volatile
4739 variables and also for variables that are renamings of other variables
4740 or for which an address clause is given.
4741 This warning can also be turned on using @option{-gnatwa}.
4742
4743 @item -gnatwM
4744 @emph{Disable warnings on modified but unreferenced variables.}
4745 @cindex @option{-gnatwM} (@code{gcc})
4746 This switch disables warnings for variables that are assigned or
4747 initialized, but never read.
4748
4749 @item -gnatwn
4750 @emph{Set normal warnings mode.}
4751 @cindex @option{-gnatwn} (@code{gcc})
4752 This switch sets normal warning mode, in which enabled warnings are
4753 issued and treated as warnings rather than errors. This is the default
4754 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4755 an explicit @option{-gnatws} or
4756 @option{-gnatwe}. It also cancels the effect of the
4757 implicit @option{-gnatwe} that is activated by the
4758 use of @option{-gnatg}.
4759
4760 @item -gnatwo
4761 @emph{Activate warnings on address clause overlays.}
4762 @cindex @option{-gnatwo} (@code{gcc})
4763 @cindex Address Clauses, warnings
4764 This switch activates warnings for possibly unintended initialization
4765 effects of defining address clauses that cause one variable to overlap
4766 another. The default is that such warnings are generated.
4767 This warning can also be turned on using @option{-gnatwa}.
4768
4769 @item -gnatwO
4770 @emph{Suppress warnings on address clause overlays.}
4771 @cindex @option{-gnatwO} (@code{gcc})
4772 This switch suppresses warnings on possibly unintended initialization
4773 effects of defining address clauses that cause one variable to overlap
4774 another.
4775
4776 @item -gnatwp
4777 @emph{Activate warnings on ineffective pragma Inlines.}
4778 @cindex @option{-gnatwp} (@code{gcc})
4779 @cindex Inlining, warnings
4780 This switch activates warnings for failure of front end inlining
4781 (activated by @option{-gnatN}) to inline a particular call. There are
4782 many reasons for not being able to inline a call, including most
4783 commonly that the call is too complex to inline.
4784 This warning can also be turned on using @option{-gnatwa}.
4785
4786 @item -gnatwP
4787 @emph{Suppress warnings on ineffective pragma Inlines.}
4788 @cindex @option{-gnatwP} (@code{gcc})
4789 This switch suppresses warnings on ineffective pragma Inlines. If the
4790 inlining mechanism cannot inline a call, it will simply ignore the
4791 request silently.
4792
4793 @item -gnatwr
4794 @emph{Activate warnings on redundant constructs.}
4795 @cindex @option{-gnatwr} (@code{gcc})
4796 This switch activates warnings for redundant constructs. The following
4797 is the current list of constructs regarded as redundant:
4798 This warning can also be turned on using @option{-gnatwa}.
4799
4800 @itemize @bullet
4801 @item
4802 Assignment of an item to itself.
4803 @item
4804 Type conversion that converts an expression to its own type.
4805 @item
4806 Use of the attribute @code{Base} where @code{typ'Base} is the same
4807 as @code{typ}.
4808 @item
4809 Use of pragma @code{Pack} when all components are placed by a record
4810 representation clause.
4811 @item
4812 Exception handler containing only a reraise statement (raise with no
4813 operand) which has no effect.
4814 @item
4815 Use of the operator abs on an operand that is known at compile time
4816 to be non-negative
4817 @item
4818 Use of an unnecessary extra level of parentheses (C-style) around conditions
4819 in @code{if} statements, @code{while} statements and @code{exit} statements.
4820 @item
4821 Comparison of boolean expressions to an explicit True value.
4822 @end itemize
4823
4824 @item -gnatwR
4825 @emph{Suppress warnings on redundant constructs.}
4826 @cindex @option{-gnatwR} (@code{gcc})
4827 This switch suppresses warnings for redundant constructs.
4828
4829 @item -gnatws
4830 @emph{Suppress all warnings.}
4831 @cindex @option{-gnatws} (@code{gcc})
4832 This switch completely suppresses the
4833 output of all warning messages from the GNAT front end.
4834 Note that it does not suppress warnings from the @code{gcc} back end.
4835 To suppress these back end warnings as well, use the switch @option{-w}
4836 in addition to @option{-gnatws}.
4837
4838 @item -gnatwu
4839 @emph{Activate warnings on unused entities.}
4840 @cindex @option{-gnatwu} (@code{gcc})
4841 This switch activates warnings to be generated for entities that
4842 are declared but not referenced, and for units that are @code{with}'ed
4843 and not
4844 referenced. In the case of packages, a warning is also generated if
4845 no entities in the package are referenced. This means that if the package
4846 is referenced but the only references are in @code{use}
4847 clauses or @code{renames}
4848 declarations, a warning is still generated. A warning is also generated
4849 for a generic package that is @code{with}'ed but never instantiated.
4850 In the case where a package or subprogram body is compiled, and there
4851 is a @code{with} on the corresponding spec
4852 that is only referenced in the body,
4853 a warning is also generated, noting that the
4854 @code{with} can be moved to the body. The default is that
4855 such warnings are not generated.
4856 This switch also activates warnings on unreferenced formals
4857 (it is includes the effect of @option{-gnatwf}).
4858 This warning can also be turned on using @option{-gnatwa}.
4859
4860 @item -gnatwU
4861 @emph{Suppress warnings on unused entities.}
4862 @cindex @option{-gnatwU} (@code{gcc})
4863 This switch suppresses warnings for unused entities and packages.
4864 It also turns off warnings on unreferenced formals (and thus includes
4865 the effect of @option{-gnatwF}).
4866
4867 @item -gnatwv
4868 @emph{Activate warnings on unassigned variables.}
4869 @cindex @option{-gnatwv} (@code{gcc})
4870 @cindex Unassigned variable warnings
4871 This switch activates warnings for access to variables which
4872 may not be properly initialized. The default is that
4873 such warnings are generated.
4874
4875 @item -gnatwV
4876 @emph{Suppress warnings on unassigned variables.}
4877 @cindex @option{-gnatwV} (@code{gcc})
4878 This switch suppresses warnings for access to variables which
4879 may not be properly initialized.
4880
4881 @item -gnatwx
4882 @emph{Activate warnings on Export/Import pragmas.}
4883 @cindex @option{-gnatwx} (@code{gcc})
4884 @cindex Export/Import pragma warnings
4885 This switch activates warnings on Export/Import pragmas when
4886 the compiler detects a possible conflict between the Ada and
4887 foreign language calling sequences. For example, the use of
4888 default parameters in a convention C procedure is dubious
4889 because the C compiler cannot supply the proper default, so
4890 a warning is issued. The default is that such warnings are
4891 generated.
4892
4893 @item -gnatwX
4894 @emph{Suppress warnings on Export/Import pragmas.}
4895 @cindex @option{-gnatwX} (@code{gcc})
4896 This switch suppresses warnings on Export/Import pragmas.
4897 The sense of this is that you are telling the compiler that
4898 you know what you are doing in writing the pragma, and it
4899 should not complain at you.
4900
4901 @item -gnatwz
4902 @emph{Activate warnings on unchecked conversions.}
4903 @cindex @option{-gnatwz} (@code{gcc})
4904 @cindex Unchecked_Conversion warnings
4905 This switch activates warnings for unchecked conversions
4906 where the types are known at compile time to have different
4907 sizes. The default
4908 is that such warnings are generated.
4909
4910 @item -gnatwZ
4911 @emph{Suppress warnings on unchecked conversions.}
4912 @cindex @option{-gnatwZ} (@code{gcc})
4913 This switch suppresses warnings for unchecked conversions
4914 where the types are known at compile time to have different
4915 sizes.
4916
4917 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
4918 @cindex @option{-Wuninitialized}
4919 The warnings controlled by the @option{-gnatw} switch are generated by the
4920 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
4921 can provide additional warnings. One such useful warning is provided by
4922 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
4923 conjunction with tunrning on optimization mode. This causes the flow
4924 analysis circuits of the back end optimizer to output additional
4925 warnings about uninitialized variables.
4926
4927 @item ^-w^/NO_BACK_END_WARNINGS^
4928 @cindex @option{-w}
4929 This switch suppresses warnings from the @option{^gcc^GCC^} back end. It may
4930 be used in conjunction with @option{-gnatws} to ensure that all warnings
4931 are suppressed during the entire compilation process.
4932
4933 @end table
4934
4935 @noindent
4936 @ifclear vms
4937 A string of warning parameters can be used in the same parameter. For example:
4938
4939 @smallexample
4940 -gnatwaLe
4941 @end smallexample
4942
4943 @noindent
4944 will turn on all optional warnings except for elaboration pragma warnings,
4945 and also specify that warnings should be treated as errors.
4946 @end ifclear
4947 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
4948
4949 @table @option
4950 @c !sort!
4951 @item -gnatwC
4952 @item -gnatwD
4953 @item -gnatwF
4954 @item -gnatwg
4955 @item -gnatwH
4956 @item -gnatwi
4957 @item -gnatwJ
4958 @item -gnatwK
4959 @item -gnatwL
4960 @item -gnatwM
4961 @item -gnatwn
4962 @item -gnatwo
4963 @item -gnatwP
4964 @item -gnatwR
4965 @item -gnatwU
4966 @item -gnatwv
4967 @item -gnatwz
4968 @item -gnatwx
4969
4970 @end table
4971
4972
4973 @node Debugging and Assertion Control
4974 @subsection Debugging and Assertion Control
4975
4976 @table @option
4977 @item -gnata
4978 @cindex @option{-gnata} (@code{gcc})
4979 @findex Assert
4980 @findex Debug
4981 @cindex Assertions
4982
4983 @noindent
4984 The pragmas @code{Assert} and @code{Debug} normally have no effect and
4985 are ignored. This switch, where @samp{a} stands for assert, causes
4986 @code{Assert} and @code{Debug} pragmas to be activated.
4987
4988 The pragmas have the form:
4989
4990 @smallexample
4991 @cartouche
4992    @b{pragma} Assert (@var{Boolean-expression} [,
4993                       @var{static-string-expression}])
4994    @b{pragma} Debug (@var{procedure call})
4995 @end cartouche
4996 @end smallexample
4997
4998 @noindent
4999 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5000 If the result is @code{True}, the pragma has no effect (other than
5001 possible side effects from evaluating the expression). If the result is
5002 @code{False}, the exception @code{Assert_Failure} declared in the package
5003 @code{System.Assertions} is
5004 raised (passing @var{static-string-expression}, if present, as the
5005 message associated with the exception). If no string expression is
5006 given the default is a string giving the file name and line number
5007 of the pragma.
5008
5009 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5010 @code{pragma Debug} may appear within a declaration sequence, allowing
5011 debugging procedures to be called between declarations.
5012
5013 @ifset vms
5014 @item /DEBUG[=debug-level]
5015 @itemx  /NODEBUG
5016 Specifies how much debugging information is to be included in
5017 the resulting object file where 'debug-level' is one of the following:
5018 @table @code
5019 @item   TRACEBACK
5020 Include both debugger symbol records and traceback
5021 the object file.
5022 This is the default setting.
5023 @item   ALL
5024 Include both debugger symbol records and traceback in
5025 object file.
5026 @item   NONE
5027 Excludes both debugger symbol records and traceback
5028 the object file. Same as /NODEBUG.
5029 @item   SYMBOLS
5030 Includes only debugger symbol records in the object
5031 file. Note that this doesn't include traceback information.
5032 @end table
5033 @end ifset
5034 @end table
5035
5036 @node Validity Checking
5037 @subsection Validity Checking
5038 @findex Validity Checking
5039
5040 @noindent
5041 The Ada 95 Reference Manual has specific requirements for checking
5042 for invalid values. In particular, RM 13.9.1 requires that the
5043 evaluation of invalid values (for example from unchecked conversions),
5044 not result in erroneous execution. In GNAT, the result of such an
5045 evaluation in normal default mode is to either use the value
5046 unmodified, or to raise Constraint_Error in those cases where use
5047 of the unmodified value would cause erroneous execution. The cases
5048 where unmodified values might lead to erroneous execution are case
5049 statements (where a wild jump might result from an invalid value),
5050 and subscripts on the left hand side (where memory corruption could
5051 occur as a result of an invalid value).
5052
5053 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5054 checking mode.
5055 @ifclear vms
5056 The @code{x} argument is a string of letters that
5057 indicate validity checks that are performed or not performed in addition
5058 to the default checks described above.
5059 @end ifclear
5060 @ifset vms
5061 The options allowed for this qualifier
5062 indicate validity checks that are performed or not performed in addition
5063 to the default checks described above.
5064 @end ifset
5065
5066
5067 @table @option
5068 @c !sort!
5069 @item -gnatVa
5070 @emph{All validity checks.}
5071 @cindex @option{-gnatVa} (@code{gcc})
5072 All validity checks are turned on.
5073 @ifclear vms
5074 That is, @option{-gnatVa} is
5075 equivalent to @option{gnatVcdfimorst}.
5076 @end ifclear
5077
5078 @item -gnatVc
5079 @emph{Validity checks for copies.}
5080 @cindex @option{-gnatVc} (@code{gcc})
5081 The right hand side of assignments, and the initializing values of
5082 object declarations are validity checked.
5083
5084 @item -gnatVd
5085 @emph{Default (RM) validity checks.}
5086 @cindex @option{-gnatVd} (@code{gcc})
5087 Some validity checks are done by default following normal Ada semantics
5088 (RM 13.9.1 (9-11)).
5089 A check is done in case statements that the expression is within the range
5090 of the subtype. If it is not, Constraint_Error is raised.
5091 For assignments to array components, a check is done that the expression used
5092 as index is within the range. If it is not, Constraint_Error is raised.
5093 Both these validity checks may be turned off using switch @option{-gnatVD}.
5094 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5095 switch @option{-gnatVd} will leave the checks turned on.
5096 Switch @option{-gnatVD} should be used only if you are sure that all such
5097 expressions have valid values. If you use this switch and invalid values
5098 are present, then the program is erroneous, and wild jumps or memory
5099 overwriting may occur.
5100
5101 @item -gnatVf
5102 @emph{Validity checks for floating-point values.}
5103 @cindex @option{-gnatVf} (@code{gcc})
5104 In the absence of this switch, validity checking occurs only for discrete
5105 values. If @option{-gnatVf} is specified, then validity checking also applies
5106 for floating-point values, and NaN's and infinities are considered invalid,
5107 as well as out of range values for constrained types. Note that this means
5108 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5109 in which floating-point values are checked depends on the setting of other
5110 options. For example,
5111 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5112 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5113 (the order does not matter) specifies that floating-point parameters of mode
5114 @code{in} should be validity checked.
5115
5116 @item -gnatVi
5117 @emph{Validity checks for @code{in} mode parameters}
5118 @cindex @option{-gnatVi} (@code{gcc})
5119 Arguments for parameters of mode @code{in} are validity checked in function
5120 and procedure calls at the point of call.
5121
5122 @item -gnatVm
5123 @emph{Validity checks for @code{in out} mode parameters.}
5124 @cindex @option{-gnatVm} (@code{gcc})
5125 Arguments for parameters of mode @code{in out} are validity checked in
5126 procedure calls at the point of call. The @code{'m'} here stands for
5127 modify, since this concerns parameters that can be modified by the call.
5128 Note that there is no specific option to test @code{out} parameters,
5129 but any reference within the subprogram will be tested in the usual
5130 manner, and if an invalid value is copied back, any reference to it
5131 will be subject to validity checking.
5132
5133 @item -gnatVn
5134 @emph{No validity checks.}
5135 @cindex @option{-gnatVn} (@code{gcc})
5136 This switch turns off all validity checking, including the default checking
5137 for case statements and left hand side subscripts. Note that the use of
5138 the switch @option{-gnatp} suppresses all run-time checks, including
5139 validity checks, and thus implies @option{-gnatVn}. When this switch
5140 is used, it cancels any other @option{-gnatV} previously issued.
5141
5142 @item -gnatVo
5143 @emph{Validity checks for operator and attribute operands.}
5144 @cindex @option{-gnatVo} (@code{gcc})
5145 Arguments for predefined operators and attributes are validity checked.
5146 This includes all operators in package @code{Standard},
5147 the shift operators defined as intrinsic in package @code{Interfaces}
5148 and operands for attributes such as @code{Pos}. Checks are also made
5149 on individual component values for composite comparisons.
5150
5151 @item -gnatVp
5152 @emph{Validity checks for parameters.}
5153 @cindex @option{-gnatVp} (@code{gcc})
5154 This controls the treatment of parameters within a subprogram (as opposed
5155 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5156 of parameters on a call. If either of these call options is used, then
5157 normally an assumption is made within a subprogram that the input arguments
5158 have been validity checking at the point of call, and do not need checking
5159 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5160 is not made, and parameters are not assumed to be valid, so their validity
5161 will be checked (or rechecked) within the subprogram.
5162
5163 @item -gnatVr
5164 @emph{Validity checks for function returns.}
5165 @cindex @option{-gnatVr} (@code{gcc})
5166 The expression in @code{return} statements in functions is validity
5167 checked.
5168
5169 @item -gnatVs
5170 @emph{Validity checks for subscripts.}
5171 @cindex @option{-gnatVs} (@code{gcc})
5172 All subscripts expressions are checked for validity, whether they appear
5173 on the right side or left side (in default mode only left side subscripts
5174 are validity checked).
5175
5176 @item -gnatVt
5177 @emph{Validity checks for tests.}
5178 @cindex @option{-gnatVt} (@code{gcc})
5179 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5180 statements are checked, as well as guard expressions in entry calls.
5181
5182 @end table
5183
5184 @noindent
5185 The @option{-gnatV} switch may be followed by
5186 ^a string of letters^a list of options^
5187 to turn on a series of validity checking options.
5188 For example,
5189 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5190 specifies that in addition to the default validity checking, copies and
5191 function return expressions are to be validity checked.
5192 In order to make it easier
5193 to specify the desired combination of effects,
5194 @ifclear vms
5195 the upper case letters @code{CDFIMORST} may
5196 be used to turn off the corresponding lower case option.
5197 @end ifclear
5198 @ifset vms
5199 the prefix @code{NO} on an option turns off the corresponding validity
5200 checking:
5201 @itemize @bullet
5202 @item @code{NOCOPIES}
5203 @item @code{NODEFAULT}
5204 @item @code{NOFLOATS}
5205 @item @code{NOIN_PARAMS}
5206 @item @code{NOMOD_PARAMS}
5207 @item @code{NOOPERANDS}
5208 @item @code{NORETURNS}
5209 @item @code{NOSUBSCRIPTS}
5210 @item @code{NOTESTS}
5211 @end itemize
5212 @end ifset
5213 Thus
5214 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5215 turns on all validity checking options except for
5216 checking of @code{@b{in out}} procedure arguments.
5217
5218 The specification of additional validity checking generates extra code (and
5219 in the case of @option{-gnatVa} the code expansion can be substantial.
5220 However, these additional checks can be very useful in detecting
5221 uninitialized variables, incorrect use of unchecked conversion, and other
5222 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5223 is useful in conjunction with the extra validity checking, since this
5224 ensures that wherever possible uninitialized variables have invalid values.
5225
5226 See also the pragma @code{Validity_Checks} which allows modification of
5227 the validity checking mode at the program source level, and also allows for
5228 temporary disabling of validity checks.
5229
5230
5231 @node Style Checking
5232 @subsection Style Checking
5233 @findex Style checking
5234
5235 @noindent
5236 The @option{-gnaty^x^(option,option,...)^} switch
5237 @cindex @option{-gnaty} (@code{gcc})
5238 causes the compiler to
5239 enforce specified style rules. A limited set of style rules has been used
5240 in writing the GNAT sources themselves. This switch allows user programs
5241 to activate all or some of these checks. If the source program fails a
5242 specified style check, an appropriate warning message is given, preceded by
5243 the character sequence ``(style)''.
5244 @ifset vms
5245 @code{(option,option,...)} is a sequence of keywords
5246 @end ifset
5247 @ifclear vms
5248 The string @var{x} is a sequence of letters or digits
5249 @end ifclear
5250 indicating the particular style
5251 checks to be performed. The following checks are defined:
5252
5253 @table @option
5254 @c !sort!
5255 @item 1-9
5256 @emph{Specify indentation level.}
5257 If a digit from 1-9 appears
5258 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5259 then proper indentation is checked, with the digit indicating the
5260 indentation level required.
5261 The general style of required indentation is as specified by
5262 the examples in the Ada Reference Manual. Full line comments must be
5263 aligned with the @code{--} starting on a column that is a multiple of
5264 the alignment level.
5265
5266 @item ^a^ATTRIBUTE^
5267 @emph{Check attribute casing.}
5268 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5269 then attribute names, including the case of keywords such as @code{digits}
5270 used as attributes names, must be written in mixed case, that is, the
5271 initial letter and any letter following an underscore must be uppercase.
5272 All other letters must be lowercase.
5273
5274 @item ^b^BLANKS^
5275 @emph{Blanks not allowed at statement end.}
5276 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5277 trailing blanks are not allowed at the end of statements. The purpose of this
5278 rule, together with h (no horizontal tabs), is to enforce a canonical format
5279 for the use of blanks to separate source tokens.
5280
5281 @item ^c^COMMENTS^
5282 @emph{Check comments.}
5283 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5284 then comments must meet the following set of rules:
5285
5286 @itemize @bullet
5287
5288 @item
5289 The ``@code{--}'' that starts the column must either start in column one,
5290 or else at least one blank must precede this sequence.
5291
5292 @item
5293 Comments that follow other tokens on a line must have at least one blank
5294 following the ``@code{--}'' at the start of the comment.
5295
5296 @item
5297 Full line comments must have two blanks following the ``@code{--}'' that
5298 starts the comment, with the following exceptions.
5299
5300 @item
5301 A line consisting only of the ``@code{--}'' characters, possibly preceded
5302 by blanks is permitted.
5303
5304 @item
5305 A comment starting with ``@code{--x}'' where @code{x} is a special character
5306 is permitted.
5307 This allows proper processing of the output generated by specialized tools
5308 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5309 annotation
5310 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5311 special character is defined as being in one of the ASCII ranges
5312 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5313 Note that this usage is not permitted
5314 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5315
5316 @item
5317 A line consisting entirely of minus signs, possibly preceded by blanks, is
5318 permitted. This allows the construction of box comments where lines of minus
5319 signs are used to form the top and bottom of the box.
5320
5321 @item
5322 If a comment starts and ends with ``@code{--}'' is permitted as long as at
5323 least one blank follows the initial ``@code{--}''. Together with the preceding
5324 rule, this allows the construction of box comments, as shown in the following
5325 example:
5326 @smallexample
5327 ---------------------------
5328 -- This is a box comment --
5329 -- with two text lines.  --
5330 ---------------------------
5331 @end smallexample
5332 @end itemize
5333
5334 @item ^e^END^
5335 @emph{Check end/exit labels.}
5336 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5337 optional labels on @code{end} statements ending subprograms and on
5338 @code{exit} statements exiting named loops, are required to be present.
5339
5340 @item ^f^VTABS^
5341 @emph{No form feeds or vertical tabs.}
5342 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5343 neither form feeds nor vertical tab characters are not permitted
5344 in the source text.
5345
5346 @item ^h^HTABS^
5347 @emph{No horizontal tabs.}
5348 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5349 horizontal tab characters are not permitted in the source text.
5350 Together with the b (no blanks at end of line) check, this
5351 enforces a canonical form for the use of blanks to separate
5352 source tokens.
5353
5354 @item ^i^IF_THEN^
5355 @emph{Check if-then layout.}
5356 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5357 then the keyword @code{then} must appear either on the same
5358 line as corresponding @code{if}, or on a line on its own, lined
5359 up under the @code{if} with at least one non-blank line in between
5360 containing all or part of the condition to be tested.
5361
5362 @item ^k^KEYWORD^
5363 @emph{Check keyword casing.}
5364 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5365 all keywords must be in lower case (with the exception of keywords
5366 such as @code{digits} used as attribute names to which this check
5367 does not apply).
5368
5369 @item ^l^LAYOUT^
5370 @emph{Check layout.}
5371 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5372 layout of statement and declaration constructs must follow the
5373 recommendations in the Ada Reference Manual, as indicated by the
5374 form of the syntax rules. For example an @code{else} keyword must
5375 be lined up with the corresponding @code{if} keyword.
5376
5377 There are two respects in which the style rule enforced by this check
5378 option are more liberal than those in the Ada Reference Manual. First
5379 in the case of record declarations, it is permissible to put the
5380 @code{record} keyword on the same line as the @code{type} keyword, and
5381 then the @code{end} in @code{end record} must line up under @code{type}.
5382 For example, either of the following two layouts is acceptable:
5383
5384 @smallexample @c ada
5385 @cartouche
5386 type q is record
5387    a : integer;
5388    b : integer;
5389 end record;
5390
5391 type q is
5392    record
5393       a : integer;
5394       b : integer;
5395    end record;
5396 @end cartouche
5397 @end smallexample
5398
5399 @noindent
5400 Second, in the case of a block statement, a permitted alternative
5401 is to put the block label on the same line as the @code{declare} or
5402 @code{begin} keyword, and then line the @code{end} keyword up under
5403 the block label. For example both the following are permitted:
5404
5405 @smallexample @c ada
5406 @cartouche
5407 Block : declare
5408    A : Integer := 3;
5409 begin
5410    Proc (A, A);
5411 end Block;
5412
5413 Block :
5414    declare
5415       A : Integer := 3;
5416    begin
5417       Proc (A, A);
5418    end Block;
5419 @end cartouche
5420 @end smallexample
5421
5422 @noindent
5423 The same alternative format is allowed for loops. For example, both of
5424 the following are permitted:
5425
5426 @smallexample @c ada
5427 @cartouche
5428 Clear : while J < 10 loop
5429    A (J) := 0;
5430 end loop Clear;
5431
5432 Clear :
5433    while J < 10 loop
5434       A (J) := 0;
5435    end loop Clear;
5436 @end cartouche
5437 @end smallexample
5438
5439 @item ^Lnnn^MAX_NESTING=nnn^
5440 @emph{Set maximum nesting level}
5441 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5442 the range 0-999, appears in the string after @option{-gnaty} then the
5443 maximum level of nesting of constructs (including subprograms, loops,
5444 blocks, packages, and conditionals) may not exceed the given value. A
5445 value of zero disconnects this style check.
5446
5447 @item ^m^LINE_LENGTH^
5448 @emph{Check maximum line length.}
5449 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5450 then the length of source lines must not exceed 79 characters, including
5451 any trailing blanks. The value of 79 allows convenient display on an
5452 80 character wide device or window, allowing for possible special
5453 treatment of 80 character lines. Note that this count is of raw
5454 characters in the source text. This means that a tab character counts
5455 as one character in this count and a wide character sequence counts as
5456 several characters (however many are needed in the encoding).
5457
5458 @item ^Mnnn^MAX_LENGTH=nnn^
5459 @emph{Set maximum line length.}
5460 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5461 the string after @option{-gnaty} then the length of lines must not exceed the
5462 given value.
5463
5464 @item ^n^STANDARD_CASING^
5465 @emph{Check casing of entities in Standard.}
5466 If the ^letter n^word STANDARD_CASING^ appears in the string
5467 after @option{-gnaty} then any identifier from Standard must be cased
5468 to match the presentation in the Ada Reference Manual (for example,
5469 @code{Integer} and @code{ASCII.NUL}).
5470
5471 @item ^o^ORDERED_SUBPROGRAMS^
5472 @emph{Check order of subprogram bodies.}
5473 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5474 after @option{-gnaty} then all subprogram bodies in a given scope
5475 (e.g. a package body) must be in alphabetical order. The ordering
5476 rule uses normal Ada rules for comparing strings, ignoring casing
5477 of letters, except that if there is a trailing numeric suffix, then
5478 the value of this suffix is used in the ordering (e.g. Junk2 comes
5479 before Junk10).
5480
5481 @item ^p^PRAGMA^
5482 @emph{Check pragma casing.}
5483 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5484 pragma names must be written in mixed case, that is, the
5485 initial letter and any letter following an underscore must be uppercase.
5486 All other letters must be lowercase.
5487
5488 @item ^r^REFERENCES^
5489 @emph{Check references.}
5490 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5491 then all identifier references must be cased in the same way as the
5492 corresponding declaration. No specific casing style is imposed on
5493 identifiers. The only requirement is for consistency of references
5494 with declarations.
5495
5496 @item ^s^SPECS^
5497 @emph{Check separate specs.}
5498 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5499 separate declarations (``specs'') are required for subprograms (a
5500 body is not allowed to serve as its own declaration). The only
5501 exception is that parameterless library level procedures are
5502 not required to have a separate declaration. This exception covers
5503 the most frequent form of main program procedures.
5504
5505 @item ^t^TOKEN^
5506 @emph{Check token spacing.}
5507 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5508 the following token spacing rules are enforced:
5509
5510 @itemize @bullet
5511
5512 @item
5513 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5514
5515 @item
5516 The token @code{=>} must be surrounded by spaces.
5517
5518 @item
5519 The token @code{<>} must be preceded by a space or a left parenthesis.
5520
5521 @item
5522 Binary operators other than @code{**} must be surrounded by spaces.
5523 There is no restriction on the layout of the @code{**} binary operator.
5524
5525 @item
5526 Colon must be surrounded by spaces.
5527
5528 @item
5529 Colon-equal (assignment, initialization) must be surrounded by spaces.
5530
5531 @item
5532 Comma must be the first non-blank character on the line, or be
5533 immediately preceded by a non-blank character, and must be followed
5534 by a space.
5535
5536 @item
5537 If the token preceding a left parenthesis ends with a letter or digit, then
5538 a space must separate the two tokens.
5539
5540 @item
5541 A right parenthesis must either be the first non-blank character on
5542 a line, or it must be preceded by a non-blank character.
5543
5544 @item
5545 A semicolon must not be preceded by a space, and must not be followed by
5546 a non-blank character.
5547
5548 @item
5549 A unary plus or minus may not be followed by a space.
5550
5551 @item
5552 A vertical bar must be surrounded by spaces.
5553 @end itemize
5554
5555 @noindent
5556 In the above rules, appearing in column one is always permitted, that is,
5557 counts as meeting either a requirement for a required preceding space,
5558 or as meeting a requirement for no preceding space.
5559
5560 Appearing at the end of a line is also always permitted, that is, counts
5561 as meeting either a requirement for a following space, or as meeting
5562 a requirement for no following space.
5563
5564 @end table
5565
5566 @noindent
5567 If any of these style rules is violated, a message is generated giving
5568 details on the violation. The initial characters of such messages are
5569 always ``@code{(style)}''. Note that these messages are treated as warning
5570 messages, so they normally do not prevent the generation of an object
5571 file. The @option{-gnatwe} switch can be used to treat warning messages,
5572 including style messages, as fatal errors.
5573
5574 The switch
5575 @ifclear vms
5576 @option{-gnaty} on its own (that is not
5577 followed by any letters or digits),
5578 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
5579 options enabled with the exception of -gnatyo,
5580 @end ifclear
5581 @ifset vms
5582 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5583 the exception of ORDERED_SUBPROGRAMS,
5584 @end ifset
5585 with an indentation level of 3. This is the standard
5586 checking option that is used for the GNAT sources.
5587
5588 The switch
5589 @ifclear vms
5590 @option{-gnatyN}
5591 @end ifclear
5592 @ifset vms
5593 /STYLE_CHECKS=NONE
5594 @end ifset
5595 clears any previously set style checks.
5596
5597 @node Run-Time Checks
5598 @subsection Run-Time Checks
5599 @cindex Division by zero
5600 @cindex Access before elaboration
5601 @cindex Checks, division by zero
5602 @cindex Checks, access before elaboration
5603
5604 @noindent
5605 If you compile with the default options, GNAT will insert many run-time
5606 checks into the compiled code, including code that performs range
5607 checking against constraints, but not arithmetic overflow checking for
5608 integer operations (including division by zero) or checks for access
5609 before elaboration on subprogram calls. All other run-time checks, as
5610 required by the Ada 95 Reference Manual, are generated by default.
5611 The following @code{gcc} switches refine this default behavior:
5612
5613 @table @option
5614 @c !sort!
5615 @item -gnatp
5616 @cindex @option{-gnatp} (@code{gcc})
5617 @cindex Suppressing checks
5618 @cindex Checks, suppressing
5619 @findex Suppress
5620 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5621 had been present in the source. Validity checks are also suppressed (in
5622 other words @option{-gnatp} also implies @option{-gnatVn}.
5623 Use this switch to improve the performance
5624 of the code at the expense of safety in the presence of invalid data or
5625 program bugs.
5626
5627 @item -gnato
5628 @cindex @option{-gnato} (@code{gcc})
5629 @cindex Overflow checks
5630 @cindex Check, overflow
5631 Enables overflow checking for integer operations.
5632 This causes GNAT to generate slower and larger executable
5633 programs by adding code to check for overflow (resulting in raising
5634 @code{Constraint_Error} as required by standard Ada
5635 semantics). These overflow checks correspond to situations in which
5636 the true value of the result of an operation may be outside the base
5637 range of the result type. The following example shows the distinction:
5638
5639 @smallexample @c ada
5640 X1 : Integer := Integer'Last;
5641 X2 : Integer range 1 .. 5 := 5;
5642 X3 : Integer := Integer'Last;
5643 X4 : Integer range 1 .. 5 := 5;
5644 F  : Float := 2.0E+20;
5645 ...
5646 X1 := X1 + 1;
5647 X2 := X2 + 1;
5648 X3 := Integer (F);
5649 X4 := Integer (F);
5650 @end smallexample
5651
5652 @noindent
5653 Here the first addition results in a value that is outside the base range
5654 of Integer, and hence requires an overflow check for detection of the
5655 constraint error. Thus the first assignment to @code{X1} raises a
5656 @code{Constraint_Error} exception only if @option{-gnato} is set.
5657
5658 The second increment operation results in a violation
5659 of the explicit range constraint, and such range checks are always
5660 performed (unless specifically suppressed with a pragma @code{suppress}
5661 or the use of @option{-gnatp}).
5662
5663 The two conversions of @code{F} both result in values that are outside
5664 the base range of type @code{Integer} and thus will raise
5665 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5666 The fact that the result of the second conversion is assigned to
5667 variable @code{X4} with a restricted range is irrelevant, since the problem
5668 is in the conversion, not the assignment.
5669
5670 Basically the rule is that in the default mode (@option{-gnato} not
5671 used), the generated code assures that all integer variables stay
5672 within their declared ranges, or within the base range if there is
5673 no declared range. This prevents any serious problems like indexes
5674 out of range for array operations.
5675
5676 What is not checked in default mode is an overflow that results in
5677 an in-range, but incorrect value. In the above example, the assignments
5678 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5679 range of the target variable, but the result is wrong in the sense that
5680 it is too large to be represented correctly. Typically the assignment
5681 to @code{X1} will result in wrap around to the largest negative number.
5682 The conversions of @code{F} will result in some @code{Integer} value
5683 and if that integer value is out of the @code{X4} range then the
5684 subsequent assignment would generate an exception.
5685
5686 @findex Machine_Overflows
5687 Note that the @option{-gnato} switch does not affect the code generated
5688 for any floating-point operations; it applies only to integer
5689 semantics).
5690 For floating-point, GNAT has the @code{Machine_Overflows}
5691 attribute set to @code{False} and the normal mode of operation is to
5692 generate IEEE NaN and infinite values on overflow or invalid operations
5693 (such as dividing 0.0 by 0.0).
5694
5695 The reason that we distinguish overflow checking from other kinds of
5696 range constraint checking is that a failure of an overflow check can
5697 generate an incorrect value, but cannot cause erroneous behavior. This
5698 is unlike the situation with a constraint check on an array subscript,
5699 where failure to perform the check can result in random memory description,
5700 or the range check on a case statement, where failure to perform the check
5701 can cause a wild jump.
5702
5703 Note again that @option{-gnato} is off by default, so overflow checking is
5704 not performed in default mode. This means that out of the box, with the
5705 default settings, GNAT does not do all the checks expected from the
5706 language description in the Ada Reference Manual. If you want all constraint
5707 checks to be performed, as described in this Manual, then you must
5708 explicitly use the -gnato switch either on the @code{gnatmake} or
5709 @code{gcc} command.
5710
5711 @item -gnatE
5712 @cindex @option{-gnatE} (@code{gcc})
5713 @cindex Elaboration checks
5714 @cindex Check, elaboration
5715 Enables dynamic checks for access-before-elaboration
5716 on subprogram calls and generic instantiations.
5717 For full details of the effect and use of this switch,
5718 @xref{Compiling Using gcc}.
5719 @end table
5720
5721 @findex Unsuppress
5722 @noindent
5723 The setting of these switches only controls the default setting of the
5724 checks. You may modify them using either @code{Suppress} (to remove
5725 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5726 the program source.
5727
5728 @node Stack Overflow Checking
5729 @subsection Stack Overflow Checking
5730 @cindex Stack Overflow Checking
5731 @cindex -fstack-check
5732
5733 @noindent
5734 For most operating systems, @code{gcc} does not perform stack overflow
5735 checking by default. This means that if the main environment task or
5736 some other task exceeds the available stack space, then unpredictable
5737 behavior will occur.
5738
5739 To activate stack checking, compile all units with the gcc option
5740 @option{-fstack-check}. For example:
5741
5742 @smallexample
5743 gcc -c -fstack-check package1.adb
5744 @end smallexample
5745
5746 @noindent
5747 Units compiled with this option will generate extra instructions to check
5748 that any use of the stack (for procedure calls or for declaring local
5749 variables in declare blocks) do not exceed the available stack space.
5750 If the space is exceeded, then a @code{Storage_Error} exception is raised.
5751
5752 For declared tasks, the stack size is always controlled by the size
5753 given in an applicable @code{Storage_Size} pragma (or is set to
5754 the default size if no pragma is used.
5755
5756 For the environment task, the stack size depends on
5757 system defaults and is unknown to the compiler. The stack
5758 may even dynamically grow on some systems, precluding the
5759 normal Ada semantics for stack overflow. In the worst case,
5760 unbounded stack usage, causes unbounded stack expansion
5761 resulting in the system running out of virtual memory.
5762
5763 The stack checking may still work correctly if a fixed
5764 size stack is allocated, but this cannot be guaranteed.
5765 To ensure that a clean exception is signalled for stack
5766 overflow, set the environment variable
5767 @code{GNAT_STACK_LIMIT} to indicate the maximum
5768 stack area that can be used, as in:
5769 @cindex GNAT_STACK_LIMIT
5770
5771 @smallexample
5772 SET GNAT_STACK_LIMIT 1600
5773 @end smallexample
5774
5775 @noindent
5776 The limit is given in kilobytes, so the above declaration would
5777 set the stack limit of the environment task to 1.6 megabytes.
5778 Note that the only purpose of this usage is to limit the amount
5779 of stack used by the environment task. If it is necessary to
5780 increase the amount of stack for the environment task, then this
5781 is an operating systems issue, and must be addressed with the
5782 appropriate operating systems commands.
5783
5784
5785 @node Using gcc for Syntax Checking
5786 @subsection Using @code{gcc} for Syntax Checking
5787 @table @option
5788 @item -gnats
5789 @cindex @option{-gnats} (@code{gcc})
5790 @ifclear vms
5791
5792 @noindent
5793 The @code{s} stands for ``syntax''.
5794 @end ifclear
5795
5796 Run GNAT in syntax checking only mode. For
5797 example, the command
5798
5799 @smallexample
5800 $ gcc -c -gnats x.adb
5801 @end smallexample
5802
5803 @noindent
5804 compiles file @file{x.adb} in syntax-check-only mode. You can check a
5805 series of files in a single command
5806 @ifclear vms
5807 , and can use wild cards to specify such a group of files.
5808 Note that you must specify the @option{-c} (compile
5809 only) flag in addition to the @option{-gnats} flag.
5810 @end ifclear
5811 .
5812 You may use other switches in conjunction with @option{-gnats}. In
5813 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5814 format of any generated error messages.
5815
5816 When the source file is empty or contains only empty lines and/or comments,
5817 the output is a warning:
5818
5819 @smallexample
5820 $ gcc -c -gnats -x ada toto.txt
5821 toto.txt:1:01: warning: empty file, contains no compilation units
5822 $
5823 @end smallexample
5824
5825 Otherwise, the output is simply the error messages, if any. No object file or
5826 ALI file is generated by a syntax-only compilation. Also, no units other
5827 than the one specified are accessed. For example, if a unit @code{X}
5828 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5829 check only mode does not access the source file containing unit
5830 @code{Y}.
5831
5832 @cindex Multiple units, syntax checking
5833 Normally, GNAT allows only a single unit in a source file. However, this
5834 restriction does not apply in syntax-check-only mode, and it is possible
5835 to check a file containing multiple compilation units concatenated
5836 together. This is primarily used by the @code{gnatchop} utility
5837 (@pxref{Renaming Files Using gnatchop}).
5838 @end table
5839
5840
5841 @node Using gcc for Semantic Checking
5842 @subsection Using @code{gcc} for Semantic Checking
5843 @table @option
5844 @item -gnatc
5845 @cindex @option{-gnatc} (@code{gcc})
5846
5847 @ifclear vms
5848 @noindent
5849 The @code{c} stands for ``check''.
5850 @end ifclear
5851 Causes the compiler to operate in semantic check mode,
5852 with full checking for all illegalities specified in the
5853 Ada 95 Reference Manual, but without generation of any object code
5854 (no object file is generated).
5855
5856 Because dependent files must be accessed, you must follow the GNAT
5857 semantic restrictions on file structuring to operate in this mode:
5858
5859 @itemize @bullet
5860 @item
5861 The needed source files must be accessible
5862 (@pxref{Search Paths and the Run-Time Library (RTL)}).
5863
5864 @item
5865 Each file must contain only one compilation unit.
5866
5867 @item
5868 The file name and unit name must match (@pxref{File Naming Rules}).
5869 @end itemize
5870
5871 The output consists of error messages as appropriate. No object file is
5872 generated. An @file{ALI} file is generated for use in the context of
5873 cross-reference tools, but this file is marked as not being suitable
5874 for binding (since no object file is generated).
5875 The checking corresponds exactly to the notion of
5876 legality in the Ada 95 Reference Manual.
5877
5878 Any unit can be compiled in semantics-checking-only mode, including
5879 units that would not normally be compiled (subunits,
5880 and specifications where a separate body is present).
5881 @end table
5882
5883 @node Compiling Ada 83 Programs
5884 @subsection Compiling Ada 83 Programs
5885 @table @option
5886 @cindex Ada 83 compatibility
5887 @item -gnat83
5888 @cindex @option{-gnat83} (@code{gcc})
5889 @cindex ACVC, Ada 83 tests
5890
5891 @noindent
5892 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
5893 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
5894 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
5895 where this can be done easily.
5896 It is not possible to guarantee this switch does a perfect
5897 job; for example, some subtle tests, such as are
5898 found in earlier ACVC tests (and that have been removed from the ACATS suite
5899 for Ada 95), might not compile correctly.
5900 Nevertheless, this switch may be useful in some circumstances, for example
5901 where, due to contractual reasons, legacy code needs to be maintained
5902 using only Ada 83 features.
5903
5904 With few exceptions (most notably the need to use @code{<>} on
5905 @cindex Generic formal parameters
5906 unconstrained generic formal parameters, the use of the new Ada 95
5907 reserved words, and the use of packages
5908 with optional bodies), it is not necessary to use the
5909 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
5910 exceptions, Ada 95 is upwardly compatible with Ada 83. This
5911 means that a correct Ada 83 program is usually also a correct Ada 95
5912 program.
5913 For further information, please refer to @ref{Compatibility and Porting Guide}.
5914
5915 @end table
5916
5917 @node Character Set Control
5918 @subsection Character Set Control
5919 @table @option
5920 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
5921 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
5922
5923 @noindent
5924 Normally GNAT recognizes the Latin-1 character set in source program
5925 identifiers, as described in the Ada 95 Reference Manual.
5926 This switch causes
5927 GNAT to recognize alternate character sets in identifiers. @var{c} is a
5928 single character ^^or word^ indicating the character set, as follows:
5929
5930 @table @code
5931 @item 1
5932 ISO 8859-1 (Latin-1) identifiers
5933
5934 @item 2
5935 ISO 8859-2 (Latin-2) letters allowed in identifiers
5936
5937 @item 3
5938 ISO 8859-3 (Latin-3) letters allowed in identifiers
5939
5940 @item 4
5941 ISO 8859-4 (Latin-4) letters allowed in identifiers
5942
5943 @item 5
5944 ISO 8859-5 (Cyrillic) letters allowed in identifiers
5945
5946 @item 9
5947 ISO 8859-15 (Latin-9) letters allowed in identifiers
5948
5949 @item ^p^PC^
5950 IBM PC letters (code page 437) allowed in identifiers
5951
5952 @item ^8^PC850^
5953 IBM PC letters (code page 850) allowed in identifiers
5954
5955 @item ^f^FULL_UPPER^
5956 Full upper-half codes allowed in identifiers
5957
5958 @item ^n^NO_UPPER^
5959 No upper-half codes allowed in identifiers
5960
5961 @item ^w^WIDE^
5962 Wide-character codes (that is, codes greater than 255)
5963 allowed in identifiers
5964 @end table
5965
5966 @xref{Foreign Language Representation}, for full details on the
5967 implementation of these character sets.
5968
5969 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
5970 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
5971 Specify the method of encoding for wide characters.
5972 @var{e} is one of the following:
5973
5974 @table @code
5975
5976 @item ^h^HEX^
5977 Hex encoding (brackets coding also recognized)
5978
5979 @item ^u^UPPER^
5980 Upper half encoding (brackets encoding also recognized)
5981
5982 @item ^s^SHIFT_JIS^
5983 Shift/JIS encoding (brackets encoding also recognized)
5984
5985 @item ^e^EUC^
5986 EUC encoding (brackets encoding also recognized)
5987
5988 @item ^8^UTF8^
5989 UTF-8 encoding (brackets encoding also recognized)
5990
5991 @item ^b^BRACKETS^
5992 Brackets encoding only (default value)
5993 @end table
5994 For full details on the these encoding
5995 methods see @xref{Wide Character Encodings}.
5996 Note that brackets coding is always accepted, even if one of the other
5997 options is specified, so for example @option{-gnatW8} specifies that both
5998 brackets and @code{UTF-8} encodings will be recognized. The units that are
5999 with'ed directly or indirectly will be scanned using the specified
6000 representation scheme, and so if one of the non-brackets scheme is
6001 used, it must be used consistently throughout the program. However,
6002 since brackets encoding is always recognized, it may be conveniently
6003 used in standard libraries, allowing these libraries to be used with
6004 any of the available coding schemes.
6005 scheme. If no @option{-gnatW?} parameter is present, then the default
6006 representation is Brackets encoding only.
6007
6008 Note that the wide character representation that is specified (explicitly
6009 or by default) for the main program also acts as the default encoding used
6010 for Wide_Text_IO files if not specifically overridden by a WCEM form
6011 parameter.
6012
6013 @end table
6014 @node File Naming Control
6015 @subsection File Naming Control
6016
6017 @table @option
6018 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6019 @cindex @option{-gnatk} (@code{gcc})
6020 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6021 1-999, indicates the maximum allowable length of a file name (not
6022 including the @file{.ads} or @file{.adb} extension). The default is not
6023 to enable file name krunching.
6024
6025 For the source file naming rules, @xref{File Naming Rules}.
6026 @end table
6027
6028
6029 @node Subprogram Inlining Control
6030 @subsection Subprogram Inlining Control
6031
6032 @table @option
6033 @c !sort!
6034 @item -gnatn
6035 @cindex @option{-gnatn} (@code{gcc})
6036 @ifclear vms
6037 The @code{n} here is intended to suggest the first syllable of the
6038 word ``inline''.
6039 @end ifclear
6040 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6041 inlining to actually occur, optimization must be enabled. To enable
6042 inlining of subprograms specified by pragma @code{Inline},
6043 you must also specify this switch.
6044 In the absence of this switch, GNAT does not attempt
6045 inlining and does not need to access the bodies of
6046 subprograms for which @code{pragma Inline} is specified if they are not
6047 in the current unit.
6048
6049 If you specify this switch the compiler will access these bodies,
6050 creating an extra source dependency for the resulting object file, and
6051 where possible, the call will be inlined.
6052 For further details on when inlining is possible
6053 see @xref{Inlining of Subprograms}.
6054
6055 @item -gnatN
6056 @cindex @option{-gnatN} (@code{gcc})
6057 The front end inlining activated by this switch is generally more extensive,
6058 and quite often more effective than the standard @option{-gnatn} inlining mode.
6059 It will also generate additional dependencies.
6060 Note that
6061 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6062 to specify both options.
6063 @end table
6064
6065 @node Auxiliary Output Control
6066 @subsection Auxiliary Output Control
6067
6068 @table @option
6069 @item -gnatt
6070 @cindex @option{-gnatt} (@code{gcc})
6071 @cindex Writing internal trees
6072 @cindex Internal trees, writing to file
6073 Causes GNAT to write the internal tree for a unit to a file (with the
6074 extension @file{.adt}.
6075 This not normally required, but is used by separate analysis tools.
6076 Typically
6077 these tools do the necessary compilations automatically, so you should
6078 not have to specify this switch in normal operation.
6079
6080 @item -gnatu
6081 @cindex @option{-gnatu} (@code{gcc})
6082 Print a list of units required by this compilation on @file{stdout}.
6083 The listing includes all units on which the unit being compiled depends
6084 either directly or indirectly.
6085
6086 @ifclear vms
6087 @item -pass-exit-codes
6088 @cindex @option{-pass-exit-codes} (@code{gcc})
6089 If this switch is not used, the exit code returned by @code{gcc} when
6090 compiling multiple files indicates whether all source files have
6091 been successfully used to generate object files or not.
6092
6093 When @option{-pass-exit-codes} is used, @code{gcc} exits with an extended
6094 exit status and allows an integrated development environment to better
6095 react to a compilation failure. Those exit status are:
6096
6097 @table @asis
6098 @item 5
6099 There was an error in at least one source file.
6100 @item 3
6101 At least one source file did not generate an object file.
6102 @item 2
6103 The compiler died unexpectedly (internal error for example).
6104 @item 0
6105 An object file has been generated for every source file.
6106 @end table
6107 @end ifclear
6108 @end table
6109
6110 @node Debugging Control
6111 @subsection Debugging Control
6112
6113 @table @option
6114 @c !sort!
6115 @cindex Debugging options
6116 @ifclear vms
6117 @item -gnatd@var{x}
6118 @cindex @option{-gnatd} (@code{gcc})
6119 Activate internal debugging switches. @var{x} is a letter or digit, or
6120 string of letters or digits, which specifies the type of debugging
6121 outputs desired. Normally these are used only for internal development
6122 or system debugging purposes. You can find full documentation for these
6123 switches in the body of the @code{Debug} unit in the compiler source
6124 file @file{debug.adb}.
6125 @end ifclear
6126
6127 @item -gnatG
6128 @cindex @option{-gnatG} (@code{gcc})
6129 This switch causes the compiler to generate auxiliary output containing
6130 a pseudo-source listing of the generated expanded code. Like most Ada
6131 compilers, GNAT works by first transforming the high level Ada code into
6132 lower level constructs. For example, tasking operations are transformed
6133 into calls to the tasking run-time routines. A unique capability of GNAT
6134 is to list this expanded code in a form very close to normal Ada source.
6135 This is very useful in understanding the implications of various Ada
6136 usage on the efficiency of the generated code. There are many cases in
6137 Ada (e.g. the use of controlled types), where simple Ada statements can
6138 generate a lot of run-time code. By using @option{-gnatG} you can identify
6139 these cases, and consider whether it may be desirable to modify the coding
6140 approach to improve efficiency.
6141
6142 The format of the output is very similar to standard Ada source, and is
6143 easily understood by an Ada programmer. The following special syntactic
6144 additions correspond to low level features used in the generated code that
6145 do not have any exact analogies in pure Ada source form. The following
6146 is a partial list of these special constructions. See the specification
6147 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6148
6149 @table @code
6150 @item new @var{xxx} [storage_pool = @var{yyy}]
6151 Shows the storage pool being used for an allocator.
6152
6153 @item at end @var{procedure-name};
6154 Shows the finalization (cleanup) procedure for a scope.
6155
6156 @item (if @var{expr} then @var{expr} else @var{expr})
6157 Conditional expression equivalent to the @code{x?y:z} construction in C.
6158
6159 @item @var{target}^^^(@var{source})
6160 A conversion with floating-point truncation instead of rounding.
6161
6162 @item @var{target}?(@var{source})
6163 A conversion that bypasses normal Ada semantic checking. In particular
6164 enumeration types and fixed-point types are treated simply as integers.
6165
6166 @item @var{target}?^^^(@var{source})
6167 Combines the above two cases.
6168
6169 @item @var{x} #/ @var{y}
6170 @itemx @var{x} #mod @var{y}
6171 @itemx @var{x} #* @var{y}
6172 @itemx @var{x} #rem @var{y}
6173 A division or multiplication of fixed-point values which are treated as
6174 integers without any kind of scaling.
6175
6176 @item free @var{expr} [storage_pool = @var{xxx}]
6177 Shows the storage pool associated with a @code{free} statement.
6178
6179 @item freeze @var{typename} [@var{actions}]
6180 Shows the point at which @var{typename} is frozen, with possible
6181 associated actions to be performed at the freeze point.
6182
6183 @item reference @var{itype}
6184 Reference (and hence definition) to internal type @var{itype}.
6185
6186 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6187 Intrinsic function call.
6188
6189 @item @var{labelname} : label
6190 Declaration of label @var{labelname}.
6191
6192 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6193 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6194 @var{expr}, but handled more efficiently).
6195
6196 @item [constraint_error]
6197 Raise the @code{Constraint_Error} exception.
6198
6199 @item @var{expression}'reference
6200 A pointer to the result of evaluating @var{expression}.
6201
6202 @item @var{target-type}!(@var{source-expression})
6203 An unchecked conversion of @var{source-expression} to @var{target-type}.
6204
6205 @item [@var{numerator}/@var{denominator}]
6206 Used to represent internal real literals (that) have no exact
6207 representation in base 2-16 (for example, the result of compile time
6208 evaluation of the expression 1.0/27.0).
6209 @end table
6210
6211 @item -gnatD
6212 @cindex @option{-gnatD} (@code{gcc})
6213 When used in conjunction with @option{-gnatG}, this switch causes
6214 the expanded source, as described above for
6215 @option{-gnatG} to be written to files with names
6216 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6217 instead of to the standard ooutput file. For
6218 example, if the source file name is @file{hello.adb}, then a file
6219 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6220 information generated by the @code{gcc} @option{^-g^/DEBUG^} switch
6221 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6222 you to do source level debugging using the generated code which is
6223 sometimes useful for complex code, for example to find out exactly
6224 which part of a complex construction raised an exception. This switch
6225 also suppress generation of cross-reference information (see
6226 @option{-gnatx}) since otherwise the cross-reference information
6227 would refer to the @file{^.dg^.DG^} file, which would cause
6228 confusion since this is not the original source file.
6229
6230 Note that @option{-gnatD} actually implies @option{-gnatG}
6231 automatically, so it is not necessary to give both options.
6232 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6233
6234 @ifclear vms
6235 @item -gnatR[0|1|2|3[s]]
6236 @cindex @option{-gnatR} (@code{gcc})
6237 This switch controls output from the compiler of a listing showing
6238 representation information for declared types and objects. For
6239 @option{-gnatR0}, no information is output (equivalent to omitting
6240 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6241 so @option{-gnatR} with no parameter has the same effect), size and alignment
6242 information is listed for declared array and record types. For
6243 @option{-gnatR2}, size and alignment information is listed for all
6244 expression information for values that are computed at run time for
6245 variant records. These symbolic expressions have a mostly obvious
6246 format with #n being used to represent the value of the n'th
6247 discriminant. See source files @file{repinfo.ads/adb} in the
6248 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6249 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6250 the output is to a file with the name @file{^file.rep^file_REP^} where
6251 file is the name of the corresponding source file.
6252 @end ifclear
6253 @ifset vms
6254 @item /REPRESENTATION_INFO
6255 @cindex @option{/REPRESENTATION_INFO} (@code{gcc})
6256 This qualifier controls output from the compiler of a listing showing
6257 representation information for declared types and objects. For
6258 @option{/REPRESENTATION_INFO=NONE}, no information is output
6259 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6260 @option{/REPRESENTATION_INFO} without option is equivalent to
6261 @option{/REPRESENTATION_INFO=ARRAYS}.
6262 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6263 information is listed for declared array and record types. For
6264 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6265 is listed for all expression information for values that are computed
6266 at run time for variant records. These symbolic expressions have a mostly
6267 obvious format with #n being used to represent the value of the n'th
6268 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6269 @code{GNAT} sources for full details on the format of
6270 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6271 If _FILE is added at the end of an option
6272 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6273 then the output is to a file with the name @file{file_REP} where
6274 file is the name of the corresponding source file.
6275 @end ifset
6276
6277 @item -gnatS
6278 @cindex @option{-gnatS} (@code{gcc})
6279 The use of the switch @option{-gnatS} for an
6280 Ada compilation will cause the compiler to output a
6281 representation of package Standard in a form very
6282 close to standard Ada. It is not quite possible to
6283 do this entirely in standard Ada (since new
6284 numeric base types cannot be created in standard
6285 Ada), but the output is easily
6286 readable to any Ada programmer, and is useful to
6287 determine the characteristics of target dependent
6288 types in package Standard.
6289
6290 @item -gnatx
6291 @cindex @option{-gnatx} (@code{gcc})
6292 Normally the compiler generates full cross-referencing information in
6293 the @file{ALI} file. This information is used by a number of tools,
6294 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6295 suppresses this information. This saves some space and may slightly
6296 speed up compilation, but means that these tools cannot be used.
6297 @end table
6298
6299 @node Exception Handling Control
6300 @subsection Exception Handling Control
6301
6302 @noindent
6303 GNAT uses two methods for handling exceptions at run-time. The
6304 @code{longjmp/setjmp} method saves the context when entering
6305 a frame with an exception handler. Then when an exception is
6306 raised, the context can be restored immediately, without the
6307 need for tracing stack frames. This method provides very fast
6308 exception propagation, but introduces significant overhead for
6309 the use of exception handlers, even if no exception is raised.
6310
6311 The other approach is called ``zero cost'' exception handling.
6312 With this method, the compiler builds static tables to describe
6313 the exception ranges. No dynamic code is required when entering
6314 a frame containing an exception handler. When an exception is
6315 raised, the tables are used to control a back trace of the
6316 subprogram invocation stack to locate the required exception
6317 handler. This method has considerably poorer performance for
6318 the propagation of exceptions, but there is no overhead for
6319 exception handlers if no exception is raised.
6320
6321 The following switches can be used to control which of the
6322 two exception handling methods is used.
6323
6324 @table @option
6325 @c !sort!
6326
6327 @item -gnatL
6328 @cindex @option{-gnatL} (@code{gcc})
6329 This switch causes the longjmp/setjmp approach to be used
6330 for exception handling. If this is the default mechanism for the
6331 target (see below), then this has no effect. If the default
6332 mechanism for the target is zero cost exceptions, then
6333 this switch can be used to modify this default, but it must be
6334 used for all units in the partition, including all run-time
6335 library units. One way to achieve this is to use the
6336 @option{-a} and @option{-f} switches for @code{gnatmake}.
6337 This option is rarely used. One case in which it may be
6338 advantageous is if you have an application where exception
6339 raising is common and the overall performance of the
6340 application is improved by favoring exception propagation.
6341
6342 @item -gnatZ
6343 @cindex @option{-gnatZ} (@code{gcc})
6344 @cindex Zero Cost Exceptions
6345 This switch causes the zero cost approach to be sed
6346 for exception handling. If this is the default mechanism for the
6347 target (see below), then this has no effect. If the default
6348 mechanism for the target is longjmp/setjmp exceptions, then
6349 this switch can be used to modify this default, but it must be
6350 used for all units in the partition, including all run-time
6351 library units. One way to achieve this is to use the
6352 @option{-a} and @option{-f} switches for @code{gnatmake}.
6353 This option can only be used if the zero cost approach
6354 is available for the target in use (see below).
6355 @end table
6356
6357 @noindent
6358 The @code{longjmp/setjmp} approach is available on all targets, but
6359 the @code{zero cost} approach is only available on selected targets.
6360 To determine whether zero cost exceptions can be used for a
6361 particular target, look at the private part of the file system.ads.
6362 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6363 be True to use the zero cost approach. If both of these switches
6364 are set to False, this means that zero cost exception handling
6365 is not yet available for that target. The switch
6366 @code{ZCX_By_Default} indicates the default approach. If this
6367 switch is set to True, then the @code{zero cost} approach is
6368 used by default.
6369
6370 @node Units to Sources Mapping Files
6371 @subsection Units to Sources Mapping Files
6372
6373 @table @option
6374
6375 @item -gnatem^^=^@var{path}
6376 @cindex @option{-gnatem} (@code{gcc})
6377 A mapping file is a way to communicate to the compiler two mappings:
6378 from unit names to file names (without any directory information) and from
6379 file names to path names (with full directory information). These mappings
6380 are used by the compiler to short-circuit the path search.
6381
6382 The use of mapping files is not required for correct operation of the
6383 compiler, but mapping files can improve efficiency, particularly when
6384 sources are read over a slow network connection. In normal operation,
6385 you need not be concerned with the format or use of mapping files,
6386 and the @option{-gnatem} switch is not a switch that you would use
6387 explicitly. it is intended only for use by automatic tools such as
6388 @code{gnatmake} running under the project file facility. The
6389 description here of the format of mapping files is provided
6390 for completeness and for possible use by other tools.
6391
6392 A mapping file is a sequence of sets of three lines. In each set,
6393 the first line is the unit name, in lower case, with ``@code{%s}''
6394 appended for
6395 specifications and ``@code{%b}'' appended for bodies; the second line is the
6396 file name; and the third line is the path name.
6397
6398 Example:
6399 @smallexample
6400    main%b
6401    main.2.ada
6402    /gnat/project1/sources/main.2.ada
6403 @end smallexample
6404
6405 When the switch @option{-gnatem} is specified, the compiler will create
6406 in memory the two mappings from the specified file. If there is any problem
6407 (non existent file, truncated file or duplicate entries), no mapping
6408 will be created.
6409
6410 Several @option{-gnatem} switches may be specified; however, only the last
6411 one on the command line will be taken into account.
6412
6413 When using a project file, @code{gnatmake} create a temporary mapping file
6414 and communicates it to the compiler using this switch.
6415
6416 @end table
6417
6418
6419 @node Integrated Preprocessing
6420 @subsection Integrated Preprocessing
6421
6422 @noindent
6423 GNAT sources may be preprocessed immediately before compilation; the actual
6424 text of the source is not the text of the source file, but is derived from it
6425 through a process called preprocessing. Integrated preprocessing is specified
6426 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6427 indicates, through a text file, the preprocessing data to be used.
6428 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6429
6430 @noindent
6431 It is recommended that @code{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6432 used when Integrated Preprocessing is used. The reason is that preprocessing
6433 with another Preprocessing Data file without changing the sources will
6434 not trigger recompilation without this switch.
6435
6436 @noindent
6437 Note that @code{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6438 always trigger recompilation for sources that are preprocessed,
6439 because @code{gnatmake} cannot compute the checksum of the source after
6440 preprocessing.
6441
6442 @noindent
6443 The actual preprocessing function is described in details in section
6444 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6445 preprocessing is triggered and parameterized.
6446
6447 @table @code
6448
6449 @item -gnatep=@var{file}
6450 @cindex @option{-gnatep} (@code{gcc})
6451 This switch indicates to the compiler the file name (without directory
6452 information) of the preprocessor data file to use. The preprocessor data file
6453 should be found in the source directories.
6454
6455 @noindent
6456 A preprocessing data file is a text file with significant lines indicating
6457 how should be preprocessed either a specific source or all sources not
6458 mentioned in other lines. A significant line is a non empty, non comment line.
6459 Comments are similar to Ada comments.
6460
6461 @noindent
6462 Each significant line starts with either a literal string or the character '*'.
6463 A literal string is the file name (without directory information) of the source
6464 to preprocess. A character '*' indicates the preprocessing for all the sources
6465 that are not specified explicitly on other lines (order of the lines is not
6466 significant). It is an error to have two lines with the same file name or two
6467 lines starting with the character '*'.
6468
6469 @noindent
6470 After the file name or the character '*', another optional literal string
6471 indicating the file name of the definition file to be used for preprocessing.
6472 (see @ref{Form of Definitions File}. The definition files are found by the
6473 compiler in one of the source directories. In some cases, when compiling
6474 a source in a directory other than the current directory, if the definition
6475 file is in the current directory, it may be necessary to add the current
6476 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6477 the compiler would not find the definition file.
6478
6479 @noindent
6480 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6481 be found. Those ^switches^switches^ are:
6482
6483 @table @code
6484
6485 @item -b
6486 Causes both preprocessor lines and the lines deleted by
6487 preprocessing to be replaced by blank lines, preserving the line number.
6488 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6489 it cancels the effect of @option{-c}.
6490
6491 @item -c
6492 Causes both preprocessor lines and the lines deleted
6493 by preprocessing to be retained as comments marked
6494 with the special string ``@code{--! }''.
6495
6496 @item -Dsymbol=value
6497 Define or redefine a symbol, associated with value. A symbol is an Ada
6498 identifier, or an Ada reserved word, with the exception of @code{if},
6499 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6500 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6501 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6502 same name defined in a definition file.
6503
6504 @item -s
6505 Causes a sorted list of symbol names and values to be
6506 listed on the standard output file.
6507
6508 @item -u
6509 Causes undefined symbols to be treated as having the value @code{FALSE}
6510 in the context
6511 of a preprocessor test. In the absence of this option, an undefined symbol in
6512 a @code{#if} or @code{#elsif} test will be treated as an error.
6513
6514 @end table
6515
6516 @noindent
6517 Examples of valid lines in a preprocessor data file:
6518
6519 @smallexample
6520   "toto.adb"  "prep.def" -u
6521   --  preprocess "toto.adb", using definition file "prep.def",
6522   --  undefined symbol are False.
6523
6524   * -c -DVERSION=V101
6525   --  preprocess all other sources without a definition file;
6526   --  suppressed lined are commented; symbol VERSION has the value V101.
6527
6528   "titi.adb" "prep2.def" -s
6529   --  preprocess "titi.adb", using definition file "prep2.def";
6530   --  list all symbols with their values.
6531 @end smallexample
6532
6533 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6534 @cindex @option{-gnateD} (@code{gcc})
6535 Define or redefine a preprocessing symbol, associated with value. If no value
6536 is given on the command line, then the value of the symbol is @code{True}.
6537 A symbol is an identifier, following normal Ada (case-insensitive)
6538 rules for its syntax, and value is any sequence (including an empty sequence)
6539 of characters from the set (letters, digits, period, underline).
6540 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6541 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6542
6543 @noindent
6544 A symbol declared with this ^switch^switch^ on the command line replaces a
6545 symbol with the same name either in a definition file or specified with a
6546 ^switch^switch^ -D in the preprocessor data file.
6547
6548 @noindent
6549 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6550
6551 @end table
6552
6553 @node Code Generation Control
6554 @subsection Code Generation Control
6555
6556 @noindent
6557
6558 The GCC technology provides a wide range of target dependent
6559 @option{-m} switches for controlling
6560 details of code generation with respect to different versions of
6561 architectures. This includes variations in instruction sets (e.g.
6562 different members of the power pc family), and different requirements
6563 for optimal arrangement of instructions (e.g. different members of
6564 the x86 family). The list of available @option{-m} switches may be
6565 found in the GCC documentation.
6566
6567 Use of the these @option{-m} switches may in some cases result in improved
6568 code performance.
6569
6570 The GNAT Pro technology is tested and qualified without any
6571 @option{-m} switches,
6572 so generally the most reliable approach is to avoid the use of these
6573 switches. However, we generally expect most of these switches to work
6574 successfully with GNAT Pro, and many customers have reported successful
6575 use of these options.
6576
6577 Our general advice is to avoid the use of @option{-m} switches unless
6578 special needs lead to requirements in this area. In particular,
6579 there is no point in using @option{-m} switches to improve performance
6580 unless you actually see a performance improvement.
6581
6582 @ifset vms
6583 @node Return Codes
6584 @subsection Return Codes
6585 @cindex Return Codes
6586 @cindex @option{/RETURN_CODES=VMS}
6587
6588 @noindent
6589 On VMS, GNAT compiled programs return POSIX-style codes by default,
6590 e.g. @option{/RETURN_CODES=POSIX}.
6591
6592 To enable VMS style return codes, GNAT LINK with the option
6593 @option{/RETURN_CODES=VMS}. For example:
6594
6595 @smallexample
6596 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6597 @end smallexample
6598
6599 @noindent
6600 Programs built with /RETURN_CODES=VMS are suitable to be called in
6601 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6602 are suitable for spawning with appropriate GNAT RTL routines.
6603
6604 @end ifset
6605
6606
6607 @node Search Paths and the Run-Time Library (RTL)
6608 @section Search Paths and the Run-Time Library (RTL)
6609
6610 @noindent
6611 With the GNAT source-based library system, the compiler must be able to
6612 find source files for units that are needed by the unit being compiled.
6613 Search paths are used to guide this process.
6614
6615 The compiler compiles one source file whose name must be given
6616 explicitly on the command line. In other words, no searching is done
6617 for this file. To find all other source files that are needed (the most
6618 common being the specs of units), the compiler examines the following
6619 directories, in the following order:
6620
6621 @enumerate
6622 @item
6623 The directory containing the source file of the main unit being compiled
6624 (the file name on the command line).
6625
6626 @item
6627 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6628 @code{gcc} command line, in the order given.
6629
6630 @item
6631 @findex ADA_INCLUDE_PATH
6632 Each of the directories listed in the value of the
6633 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6634 @ifclear vms
6635 Construct this value
6636 exactly as the @code{PATH} environment variable: a list of directory
6637 names separated by colons (semicolons when working with the NT version).
6638 @end ifclear
6639 @ifset vms
6640 Normally, define this value as a logical name containing a comma separated
6641 list of directory names.
6642
6643 This variable can also be defined by means of an environment string
6644 (an argument to the DEC C exec* set of functions).
6645
6646 Logical Name:
6647 @smallexample
6648 DEFINE ANOTHER_PATH FOO:[BAG]
6649 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6650 @end smallexample
6651
6652 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6653 first, followed by the standard Ada 95
6654 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6655 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
6656 (Text_IO, Sequential_IO, etc)
6657 instead of the Ada95 packages. Thus, in order to get the Ada 95
6658 packages by default, ADA_INCLUDE_PATH must be redefined.
6659 @end ifset
6660
6661 @item
6662 @findex ADA_PRJ_INCLUDE_FILE
6663 Each of the directories listed in the text file whose name is given
6664 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6665
6666 @noindent
6667 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6668 driver when project files are used. It should not normally be set
6669 by other means.
6670
6671 @item
6672 The content of the @file{ada_source_path} file which is part of the GNAT
6673 installation tree and is used to store standard libraries such as the
6674 GNAT Run Time Library (RTL) source files.
6675 @ifclear vms
6676 @ref{Installing the library}
6677 @end ifclear
6678 @end enumerate
6679
6680 @noindent
6681 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6682 inhibits the use of the directory
6683 containing the source file named in the command line. You can still
6684 have this directory on your search path, but in this case it must be
6685 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6686
6687 Specifying the switch @option{-nostdinc}
6688 inhibits the search of the default location for the GNAT Run Time
6689 Library (RTL) source files.
6690
6691 The compiler outputs its object files and ALI files in the current
6692 working directory.
6693 @ifclear vms
6694 Caution: The object file can be redirected with the @option{-o} switch;
6695 however, @code{gcc} and @code{gnat1} have not been coordinated on this
6696 so the @file{ALI} file will not go to the right place. Therefore, you should
6697 avoid using the @option{-o} switch.
6698 @end ifclear
6699
6700 @findex System.IO
6701 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6702 children make up the GNAT RTL, together with the simple @code{System.IO}
6703 package used in the @code{"Hello World"} example. The sources for these units
6704 are needed by the compiler and are kept together in one directory. Not
6705 all of the bodies are needed, but all of the sources are kept together
6706 anyway. In a normal installation, you need not specify these directory
6707 names when compiling or binding. Either the environment variables or
6708 the built-in defaults cause these files to be found.
6709
6710 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6711 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6712 consisting of child units of @code{GNAT}. This is a collection of generally
6713 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6714 further details.
6715
6716 Besides simplifying access to the RTL, a major use of search paths is
6717 in compiling sources from multiple directories. This can make
6718 development environments much more flexible.
6719
6720
6721 @node Order of Compilation Issues
6722 @section Order of Compilation Issues
6723
6724 @noindent
6725 If, in our earlier example, there was a spec for the @code{hello}
6726 procedure, it would be contained in the file @file{hello.ads}; yet this
6727 file would not have to be explicitly compiled. This is the result of the
6728 model we chose to implement library management. Some of the consequences
6729 of this model are as follows:
6730
6731 @itemize @bullet
6732 @item
6733 There is no point in compiling specs (except for package
6734 specs with no bodies) because these are compiled as needed by clients. If
6735 you attempt a useless compilation, you will receive an error message.
6736 It is also useless to compile subunits because they are compiled as needed
6737 by the parent.
6738
6739 @item
6740 There are no order of compilation requirements: performing a
6741 compilation never obsoletes anything. The only way you can obsolete
6742 something and require recompilations is to modify one of the
6743 source files on which it depends.
6744
6745 @item
6746 There is no library as such, apart from the ALI files
6747 (@pxref{The Ada Library Information Files}, for information on the format
6748 of these files). For now we find it convenient to create separate ALI files,
6749 but eventually the information therein may be incorporated into the object
6750 file directly.
6751
6752 @item
6753 When you compile a unit, the source files for the specs of all units
6754 that it @code{with}'s, all its subunits, and the bodies of any generics it
6755 instantiates must be available (reachable by the search-paths mechanism
6756 described above), or you will receive a fatal error message.
6757 @end itemize
6758
6759 @node Examples
6760 @section Examples
6761
6762 @noindent
6763 The following are some typical Ada compilation command line examples:
6764
6765 @table @code
6766 @item $ gcc -c xyz.adb
6767 Compile body in file @file{xyz.adb} with all default options.
6768
6769 @ifclear vms
6770 @item $ gcc -c -O2 -gnata xyz-def.adb
6771 @end ifclear
6772 @ifset vms
6773 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6774 @end ifset
6775
6776 Compile the child unit package in file @file{xyz-def.adb} with extensive
6777 optimizations, and pragma @code{Assert}/@code{Debug} statements
6778 enabled.
6779
6780 @item $ gcc -c -gnatc abc-def.adb
6781 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6782 mode.
6783 @end table
6784
6785 @node Binding Using gnatbind
6786 @chapter Binding Using @code{gnatbind}
6787 @findex gnatbind
6788
6789 @menu
6790 * Running gnatbind::
6791 * Switches for gnatbind::
6792 * Command-Line Access::
6793 * Search Paths for gnatbind::
6794 * Examples of gnatbind Usage::
6795 @end menu
6796
6797 @noindent
6798 This chapter describes the GNAT binder, @code{gnatbind}, which is used
6799 to bind compiled GNAT objects. The @code{gnatbind} program performs
6800 four separate functions:
6801
6802 @enumerate
6803 @item
6804 Checks that a program is consistent, in accordance with the rules in
6805 Chapter 10 of the Ada 95 Reference Manual. In particular, error
6806 messages are generated if a program uses inconsistent versions of a
6807 given unit.
6808
6809 @item
6810 Checks that an acceptable order of elaboration exists for the program
6811 and issues an error message if it cannot find an order of elaboration
6812 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6813
6814 @item
6815 Generates a main program incorporating the given elaboration order.
6816 This program is a small Ada package (body and spec) that
6817 must be subsequently compiled
6818 using the GNAT compiler. The necessary compilation step is usually
6819 performed automatically by @code{gnatlink}. The two most important
6820 functions of this program
6821 are to call the elaboration routines of units in an appropriate order
6822 and to call the main program.
6823
6824 @item
6825 Determines the set of object files required by the given main program.
6826 This information is output in the forms of comments in the generated program,
6827 to be read by the @code{gnatlink} utility used to link the Ada application.
6828 @end enumerate
6829
6830
6831 @node Running gnatbind
6832 @section Running @code{gnatbind}
6833
6834 @noindent
6835 The form of the @code{gnatbind} command is
6836
6837 @smallexample
6838 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
6839 @end smallexample
6840
6841 @noindent
6842 where @file{@i{mainprog}.adb} is the Ada file containing the main program
6843 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
6844 package in two files whose names are
6845 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
6846 For example, if given the
6847 parameter @file{hello.ali}, for a main program contained in file
6848 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
6849 and @file{b~hello.adb}.
6850
6851 When doing consistency checking, the binder takes into consideration
6852 any source files it can locate. For example, if the binder determines
6853 that the given main program requires the package @code{Pack}, whose
6854 @file{.ALI}
6855 file is @file{pack.ali} and whose corresponding source spec file is
6856 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
6857 (using the same search path conventions as previously described for the
6858 @code{gcc} command). If it can locate this source file, it checks that
6859 the time stamps
6860 or source checksums of the source and its references to in @file{ALI} files
6861 match. In other words, any @file{ALI} files that mentions this spec must have
6862 resulted from compiling this version of the source file (or in the case
6863 where the source checksums match, a version close enough that the
6864 difference does not matter).
6865
6866 @cindex Source files, use by binder
6867 The effect of this consistency checking, which includes source files, is
6868 that the binder ensures that the program is consistent with the latest
6869 version of the source files that can be located at bind time. Editing a
6870 source file without compiling files that depend on the source file cause
6871 error messages to be generated by the binder.
6872
6873 For example, suppose you have a main program @file{hello.adb} and a
6874 package @code{P}, from file @file{p.ads} and you perform the following
6875 steps:
6876
6877 @enumerate
6878 @item
6879 Enter @code{gcc -c hello.adb} to compile the main program.
6880
6881 @item
6882 Enter @code{gcc -c p.ads} to compile package @code{P}.
6883
6884 @item
6885 Edit file @file{p.ads}.
6886
6887 @item
6888 Enter @code{gnatbind hello}.
6889 @end enumerate
6890
6891 @noindent
6892 At this point, the file @file{p.ali} contains an out-of-date time stamp
6893 because the file @file{p.ads} has been edited. The attempt at binding
6894 fails, and the binder generates the following error messages:
6895
6896 @smallexample
6897 error: "hello.adb" must be recompiled ("p.ads" has been modified)
6898 error: "p.ads" has been modified and must be recompiled
6899 @end smallexample
6900
6901 @noindent
6902 Now both files must be recompiled as indicated, and then the bind can
6903 succeed, generating a main program. You need not normally be concerned
6904 with the contents of this file, but for reference purposes a sample
6905 binder output file is given in @ref{Example of Binder Output File}.
6906
6907 In most normal usage, the default mode of @command{gnatbind} which is to
6908 generate the main package in Ada, as described in the previous section.
6909 In particular, this means that any Ada programmer can read and understand
6910 the generated main program. It can also be debugged just like any other
6911 Ada code provided the @option{^-g^/DEBUG^} switch is used for
6912 @command{gnatbind} and @command{gnatlink}.
6913
6914 However for some purposes it may be convenient to generate the main
6915 program in C rather than Ada. This may for example be helpful when you
6916 are generating a mixed language program with the main program in C. The
6917 GNAT compiler itself is an example.
6918 The use of the @option{^-C^/BIND_FILE=C^} switch
6919 for both @code{gnatbind} and @code{gnatlink} will cause the program to
6920 be generated in C (and compiled using the gnu C compiler).
6921
6922
6923 @node Switches for gnatbind
6924 @section Switches for @command{gnatbind}
6925
6926 @noindent
6927 The following switches are available with @code{gnatbind}; details will
6928 be presented in subsequent sections.
6929
6930 @menu
6931 * Consistency-Checking Modes::
6932 * Binder Error Message Control::
6933 * Elaboration Control::
6934 * Output Control::
6935 * Binding with Non-Ada Main Programs::
6936 * Binding Programs with No Main Subprogram::
6937 @end menu
6938
6939 @table @option
6940 @c !sort!
6941 @item ^-aO^/OBJECT_SEARCH^
6942 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
6943 Specify directory to be searched for ALI files.
6944
6945 @item ^-aI^/SOURCE_SEARCH^
6946 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
6947 Specify directory to be searched for source file.
6948
6949 @item ^-A^/BIND_FILE=ADA^
6950 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
6951 Generate binder program in Ada (default)
6952
6953 @item ^-b^/REPORT_ERRORS=BRIEF^
6954 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
6955 Generate brief messages to @file{stderr} even if verbose mode set.
6956
6957 @item ^-c^/NOOUTPUT^
6958 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
6959 Check only, no generation of binder output file.
6960
6961 @item ^-C^/BIND_FILE=C^
6962 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
6963 Generate binder program in C
6964
6965 @item ^-e^/ELABORATION_DEPENDENCIES^
6966 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
6967 Output complete list of elaboration-order dependencies.
6968
6969 @item ^-E^/STORE_TRACEBACKS^
6970 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
6971 Store tracebacks in exception occurrences when the target supports it.
6972 This is the default with the zero cost exception mechanism.
6973 @ignore
6974 @c The following may get moved to an appendix
6975 This option is currently supported on the following targets:
6976 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6977 @end ignore
6978 See also the packages @code{GNAT.Traceback} and
6979 @code{GNAT.Traceback.Symbolic} for more information.
6980 @ifclear vms
6981 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
6982 @code{gcc} option.
6983 @end ifclear
6984
6985 @item ^-F^/FORCE_ELABS_FLAGS^
6986 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
6987 Force the checks of elaboration flags. @command{gnatbind} does not normally
6988 generate checks of elaboration flags for the main executable, except when
6989 a Stand-Alone Library is used. However, there are cases when this cannot be
6990 detected by gnatbind. An example is importing an interface of a Stand-Alone
6991 Library through a pragma Import and only specifying through a linker switch
6992 this Stand-Alone Library. This switch is used to guarantee that elaboration
6993 flag checks are generated.
6994
6995 @item ^-h^/HELP^
6996 @cindex @option{^-h^/HELP^} (@command{gnatbind})
6997 Output usage (help) information
6998
6999 @item ^-I^/SEARCH^
7000 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7001 Specify directory to be searched for source and ALI files.
7002
7003 @item ^-I-^/NOCURRENT_DIRECTORY^
7004 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7005 Do not look for sources in the current directory where @code{gnatbind} was
7006 invoked, and do not look for ALI files in the directory containing the
7007 ALI file named in the @code{gnatbind} command line.
7008
7009 @item ^-l^/ORDER_OF_ELABORATION^
7010 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7011 Output chosen elaboration order.
7012
7013 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7014 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7015 Binds the units for library building. In this case the adainit and
7016 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
7017 are renamed to ^xxxinit^XXXINIT^ and
7018 ^xxxfinal^XXXFINAL^.
7019 Implies ^-n^/NOCOMPILE^.
7020 @ifclear vms
7021 (@pxref{GNAT and Libraries}, for more details.)
7022 @end ifclear
7023 @ifset vms
7024 On OpenVMS, these init and final procedures are exported in uppercase
7025 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7026 the init procedure will be "TOTOINIT" and the exported name of the final
7027 procedure will be "TOTOFINAL".
7028 @end ifset
7029
7030 @item ^-Mxyz^/RENAME_MAIN=xyz^
7031 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7032 Rename generated main program from main to xyz
7033
7034 @item ^-m^/ERROR_LIMIT=^@var{n}
7035 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7036 Limit number of detected errors to @var{n}, where @var{n} is
7037 in the range 1..999_999. The default value if no switch is
7038 given is 9999. Binding is terminated if the limit is exceeded.
7039 @ifset unw
7040 Furthermore, under Windows, the sources pointed to by the libraries path
7041 set in the registry are not searched for.
7042 @end ifset
7043
7044 @item ^-n^/NOMAIN^
7045 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7046 No main program.
7047
7048 @item -nostdinc
7049 @cindex @option{-nostdinc} (@command{gnatbind})
7050 Do not look for sources in the system default directory.
7051
7052 @item -nostdlib
7053 @cindex @option{-nostdlib} (@command{gnatbind})
7054 Do not look for library files in the system default directory.
7055
7056 @item --RTS=@var{rts-path}
7057 @cindex @option{--RTS} (@code{gnatbind})
7058 Specifies the default location of the runtime library. Same meaning as the
7059 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
7060
7061 @item ^-o ^/OUTPUT=^@var{file}
7062 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7063 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7064 Note that if this option is used, then linking must be done manually,
7065 gnatlink cannot be used.
7066
7067 @item ^-O^/OBJECT_LIST^
7068 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7069 Output object list.
7070
7071 @item ^-p^/PESSIMISTIC_ELABORATION^
7072 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7073 Pessimistic (worst-case) elaboration order
7074
7075 @item ^-s^/READ_SOURCES=ALL^
7076 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7077 Require all source files to be present.
7078
7079 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7080 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7081 Specifies the value to be used when detecting uninitialized scalar
7082 objects with pragma Initialize_Scalars.
7083 The @var{xxx} ^string specified with the switch^option^ may be either
7084 @itemize @bullet
7085 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7086 @item ``@option{^lo^LOW^}'' for the lowest possible value
7087 possible, and the low
7088 @item ``@option{^hi^HIGH^}'' for the highest possible value
7089 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7090 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7091 @end itemize
7092
7093 In addition, you can specify @option{-Sev} to indicate that the value is
7094 to be set at run time. In this case, the program will look for an environment
7095 @cindex GNAT_INIT_SCALARS
7096 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7097 of @option{in/lo/hi/xx} with the same meanings as above.
7098 If no environment variable is found, or if it does not have a valid value,
7099 then the default is @option{in} (invalid values).
7100
7101 @ifclear vms
7102 @item -static
7103 @cindex @option{-static} (@code{gnatbind})
7104 Link against a static GNAT run time.
7105
7106 @item -shared
7107 @cindex @option{-shared} (@code{gnatbind})
7108 Link against a shared GNAT run time when available.
7109 @end ifclear
7110
7111 @item ^-t^/NOTIME_STAMP_CHECK^
7112 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7113 Tolerate time stamp and other consistency errors
7114
7115 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7116 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7117 Set the time slice value to @var{n} milliseconds. If the system supports
7118 the specification of a specific time slice value, then the indicated value
7119 is used. If the system does not support specific time slice values, but
7120 does support some general notion of round-robin scheduling, then any
7121 non-zero value will activate round-robin scheduling.
7122
7123 A value of zero is treated specially. It turns off time
7124 slicing, and in addition, indicates to the tasking run time that the
7125 semantics should match as closely as possible the Annex D
7126 requirements of the Ada RM, and in particular sets the default
7127 scheduling policy to @code{FIFO_Within_Priorities}.
7128
7129 @item ^-v^/REPORT_ERRORS=VERBOSE^
7130 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7131 Verbose mode. Write error messages, header, summary output to
7132 @file{stdout}.
7133
7134 @ifclear vms
7135 @item -w@var{x}
7136 @cindex @option{-w} (@code{gnatbind})
7137 Warning mode (@var{x}=s/e for suppress/treat as error)
7138 @end ifclear
7139
7140 @ifset vms
7141 @item /WARNINGS=NORMAL
7142 @cindex @option{/WARNINGS} (@code{gnatbind})
7143 Normal warnings mode. Warnings are issued but ignored
7144
7145 @item /WARNINGS=SUPPRESS
7146 @cindex @option{/WARNINGS} (@code{gnatbind})
7147 All warning messages are suppressed
7148
7149 @item /WARNINGS=ERROR
7150 @cindex @option{/WARNINGS} (@code{gnatbind})
7151 Warning messages are treated as fatal errors
7152 @end ifset
7153
7154 @item ^-x^/READ_SOURCES=NONE^
7155 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7156 Exclude source files (check object consistency only).
7157
7158 @ifset vms
7159 @item /READ_SOURCES=AVAILABLE
7160 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7161 Default mode, in which sources are checked for consistency only if
7162 they are available.
7163 @end ifset
7164
7165 @item ^-z^/ZERO_MAIN^
7166 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7167 No main subprogram.
7168 @end table
7169
7170 @ifclear vms
7171 @noindent
7172 You may obtain this listing of switches by running @code{gnatbind} with
7173 no arguments.
7174 @end ifclear
7175
7176
7177 @node Consistency-Checking Modes
7178 @subsection Consistency-Checking Modes
7179
7180 @noindent
7181 As described earlier, by default @code{gnatbind} checks
7182 that object files are consistent with one another and are consistent
7183 with any source files it can locate. The following switches control binder
7184 access to sources.
7185
7186 @table @option
7187 @c !sort!
7188 @item ^-s^/READ_SOURCES=ALL^
7189 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7190 Require source files to be present. In this mode, the binder must be
7191 able to locate all source files that are referenced, in order to check
7192 their consistency. In normal mode, if a source file cannot be located it
7193 is simply ignored. If you specify this switch, a missing source
7194 file is an error.
7195
7196 @item ^-x^/READ_SOURCES=NONE^
7197 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7198 Exclude source files. In this mode, the binder only checks that ALI
7199 files are consistent with one another. Source files are not accessed.
7200 The binder runs faster in this mode, and there is still a guarantee that
7201 the resulting program is self-consistent.
7202 If a source file has been edited since it was last compiled, and you
7203 specify this switch, the binder will not detect that the object
7204 file is out of date with respect to the source file. Note that this is the
7205 mode that is automatically used by @code{gnatmake} because in this
7206 case the checking against sources has already been performed by
7207 @code{gnatmake} in the course of compilation (i.e. before binding).
7208
7209 @ifset vms
7210 @item /READ_SOURCES=AVAILABLE
7211 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7212 This is the default mode in which source files are checked if they are
7213 available, and ignored if they are not available.
7214 @end ifset
7215 @end table
7216
7217 @node Binder Error Message Control
7218 @subsection Binder Error Message Control
7219
7220 @noindent
7221 The following switches provide control over the generation of error
7222 messages from the binder:
7223
7224 @table @option
7225 @c !sort!
7226 @item ^-v^/REPORT_ERRORS=VERBOSE^
7227 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7228 Verbose mode. In the normal mode, brief error messages are generated to
7229 @file{stderr}. If this switch is present, a header is written
7230 to @file{stdout} and any error messages are directed to @file{stdout}.
7231 All that is written to @file{stderr} is a brief summary message.
7232
7233 @item ^-b^/REPORT_ERRORS=BRIEF^
7234 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7235 Generate brief error messages to @file{stderr} even if verbose mode is
7236 specified. This is relevant only when used with the
7237 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7238
7239 @ifclear vms
7240 @item -m@var{n}
7241 @cindex @option{-m} (@code{gnatbind})
7242 Limits the number of error messages to @var{n}, a decimal integer in the
7243 range 1-999. The binder terminates immediately if this limit is reached.
7244
7245 @item -M@var{xxx}
7246 @cindex @option{-M} (@code{gnatbind})
7247 Renames the generated main program from @code{main} to @code{xxx}.
7248 This is useful in the case of some cross-building environments, where
7249 the actual main program is separate from the one generated
7250 by @code{gnatbind}.
7251 @end ifclear
7252
7253 @item ^-ws^/WARNINGS=SUPPRESS^
7254 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7255 @cindex Warnings
7256 Suppress all warning messages.
7257
7258 @item ^-we^/WARNINGS=ERROR^
7259 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7260 Treat any warning messages as fatal errors.
7261
7262 @ifset vms
7263 @item /WARNINGS=NORMAL
7264 Standard mode with warnings generated, but warnings do not get treated
7265 as errors.
7266 @end ifset
7267
7268 @item ^-t^/NOTIME_STAMP_CHECK^
7269 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7270 @cindex Time stamp checks, in binder
7271 @cindex Binder consistency checks
7272 @cindex Consistency checks, in binder
7273 The binder performs a number of consistency checks including:
7274
7275 @itemize @bullet
7276 @item
7277 Check that time stamps of a given source unit are consistent
7278 @item
7279 Check that checksums of a given source unit are consistent
7280 @item
7281 Check that consistent versions of @code{GNAT} were used for compilation
7282 @item
7283 Check consistency of configuration pragmas as required
7284 @end itemize
7285
7286 @noindent
7287 Normally failure of such checks, in accordance with the consistency
7288 requirements of the Ada Reference Manual, causes error messages to be
7289 generated which abort the binder and prevent the output of a binder
7290 file and subsequent link to obtain an executable.
7291
7292 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7293 into warnings, so that
7294 binding and linking can continue to completion even in the presence of such
7295 errors. The result may be a failed link (due to missing symbols), or a
7296 non-functional executable which has undefined semantics.
7297 @emph{This means that
7298 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7299 with extreme care.}
7300 @end table
7301
7302 @node Elaboration Control
7303 @subsection Elaboration Control
7304
7305 @noindent
7306 The following switches provide additional control over the elaboration
7307 order. For full details see @xref{Elaboration Order Handling in GNAT}.
7308
7309 @table @option
7310 @item ^-p^/PESSIMISTIC_ELABORATION^
7311 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7312 Normally the binder attempts to choose an elaboration order that is
7313 likely to minimize the likelihood of an elaboration order error resulting
7314 in raising a @code{Program_Error} exception. This switch reverses the
7315 action of the binder, and requests that it deliberately choose an order
7316 that is likely to maximize the likelihood of an elaboration error.
7317 This is useful in ensuring portability and avoiding dependence on
7318 accidental fortuitous elaboration ordering.
7319
7320 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7321 switch if dynamic
7322 elaboration checking is used (@option{-gnatE} switch used for compilation).
7323 This is because in the default static elaboration mode, all necessary
7324 @code{Elaborate_All} pragmas are implicitly inserted.
7325 These implicit pragmas are still respected by the binder in
7326 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7327 safe elaboration order is assured.
7328 @end table
7329
7330 @node Output Control
7331 @subsection Output Control
7332
7333 @noindent
7334 The following switches allow additional control over the output
7335 generated by the binder.
7336
7337 @table @option
7338 @c !sort!
7339
7340 @item ^-A^/BIND_FILE=ADA^
7341 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7342 Generate binder program in Ada (default). The binder program is named
7343 @file{b~@var{mainprog}.adb} by default. This can be changed with
7344 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7345
7346 @item ^-c^/NOOUTPUT^
7347 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7348 Check only. Do not generate the binder output file. In this mode the
7349 binder performs all error checks but does not generate an output file.
7350
7351 @item ^-C^/BIND_FILE=C^
7352 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7353 Generate binder program in C. The binder program is named
7354 @file{b_@var{mainprog}.c}.
7355 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7356 option.
7357
7358 @item ^-e^/ELABORATION_DEPENDENCIES^
7359 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7360 Output complete list of elaboration-order dependencies, showing the
7361 reason for each dependency. This output can be rather extensive but may
7362 be useful in diagnosing problems with elaboration order. The output is
7363 written to @file{stdout}.
7364
7365 @item ^-h^/HELP^
7366 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7367 Output usage information. The output is written to @file{stdout}.
7368
7369 @item ^-K^/LINKER_OPTION_LIST^
7370 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7371 Output linker options to @file{stdout}. Includes library search paths,
7372 contents of pragmas Ident and Linker_Options, and libraries added
7373 by @code{gnatbind}.
7374
7375 @item ^-l^/ORDER_OF_ELABORATION^
7376 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7377 Output chosen elaboration order. The output is written to @file{stdout}.
7378
7379 @item ^-O^/OBJECT_LIST^
7380 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7381 Output full names of all the object files that must be linked to provide
7382 the Ada component of the program. The output is written to @file{stdout}.
7383 This list includes the files explicitly supplied and referenced by the user
7384 as well as implicitly referenced run-time unit files. The latter are
7385 omitted if the corresponding units reside in shared libraries. The
7386 directory names for the run-time units depend on the system configuration.
7387
7388 @item ^-o ^/OUTPUT=^@var{file}
7389 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7390 Set name of output file to @var{file} instead of the normal
7391 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7392 binder generated body filename. In C mode you would normally give
7393 @var{file} an extension of @file{.c} because it will be a C source program.
7394 Note that if this option is used, then linking must be done manually.
7395 It is not possible to use gnatlink in this case, since it cannot locate
7396 the binder file.
7397
7398 @item ^-r^/RESTRICTION_LIST^
7399 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7400 Generate list of @code{pragma Restrictions} that could be applied to
7401 the current unit. This is useful for code audit purposes, and also may
7402 be used to improve code generation in some cases.
7403
7404 @end table
7405
7406 @node Binding with Non-Ada Main Programs
7407 @subsection Binding with Non-Ada Main Programs
7408
7409 @noindent
7410 In our description so far we have assumed that the main
7411 program is in Ada, and that the task of the binder is to generate a
7412 corresponding function @code{main} that invokes this Ada main
7413 program. GNAT also supports the building of executable programs where
7414 the main program is not in Ada, but some of the called routines are
7415 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7416 The following switch is used in this situation:
7417
7418 @table @option
7419 @item ^-n^/NOMAIN^
7420 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7421 No main program. The main program is not in Ada.
7422 @end table
7423
7424 @noindent
7425 In this case, most of the functions of the binder are still required,
7426 but instead of generating a main program, the binder generates a file
7427 containing the following callable routines:
7428
7429 @table @code
7430 @item adainit
7431 @findex adainit
7432 You must call this routine to initialize the Ada part of the program by
7433 calling the necessary elaboration routines. A call to @code{adainit} is
7434 required before the first call to an Ada subprogram.
7435
7436 Note that it is assumed that the basic execution environment must be setup
7437 to be appropriate for Ada execution at the point where the first Ada
7438 subprogram is called. In particular, if the Ada code will do any
7439 floating-point operations, then the FPU must be setup in an appropriate
7440 manner. For the case of the x86, for example, full precision mode is
7441 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7442 that the FPU is in the right state.
7443
7444 @item adafinal
7445 @findex adafinal
7446 You must call this routine to perform any library-level finalization
7447 required by the Ada subprograms. A call to @code{adafinal} is required
7448 after the last call to an Ada subprogram, and before the program
7449 terminates.
7450 @end table
7451
7452 @noindent
7453 If the @option{^-n^/NOMAIN^} switch
7454 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7455 @cindex Binder, multiple input files
7456 is given, more than one ALI file may appear on
7457 the command line for @code{gnatbind}. The normal @dfn{closure}
7458 calculation is performed for each of the specified units. Calculating
7459 the closure means finding out the set of units involved by tracing
7460 @code{with} references. The reason it is necessary to be able to
7461 specify more than one ALI file is that a given program may invoke two or
7462 more quite separate groups of Ada units.
7463
7464 The binder takes the name of its output file from the last specified ALI
7465 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7466 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7467 The output is an Ada unit in source form that can
7468 be compiled with GNAT unless the -C switch is used in which case the
7469 output is a C source file, which must be compiled using the C compiler.
7470 This compilation occurs automatically as part of the @code{gnatlink}
7471 processing.
7472
7473 Currently the GNAT run time requires a FPU using 80 bits mode
7474 precision. Under targets where this is not the default it is required to
7475 call GNAT.Float_Control.Reset before using floating point numbers (this
7476 include float computation, float input and output) in the Ada code. A
7477 side effect is that this could be the wrong mode for the foreign code
7478 where floating point computation could be broken after this call.
7479
7480 @node Binding Programs with No Main Subprogram
7481 @subsection Binding Programs with No Main Subprogram
7482
7483 @noindent
7484 It is possible to have an Ada program which does not have a main
7485 subprogram. This program will call the elaboration routines of all the
7486 packages, then the finalization routines.
7487
7488 The following switch is used to bind programs organized in this manner:
7489
7490 @table @option
7491 @item ^-z^/ZERO_MAIN^
7492 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7493 Normally the binder checks that the unit name given on the command line
7494 corresponds to a suitable main subprogram. When this switch is used,
7495 a list of ALI files can be given, and the execution of the program
7496 consists of elaboration of these units in an appropriate order.
7497 @end table
7498
7499
7500 @node Command-Line Access
7501 @section Command-Line Access
7502
7503 @noindent
7504 The package @code{Ada.Command_Line} provides access to the command-line
7505 arguments and program name. In order for this interface to operate
7506 correctly, the two variables
7507
7508 @smallexample
7509 @group
7510 int gnat_argc;
7511 char **gnat_argv;
7512 @end group
7513 @end smallexample
7514
7515 @noindent
7516 @findex gnat_argv
7517 @findex gnat_argc
7518 are declared in one of the GNAT library routines. These variables must
7519 be set from the actual @code{argc} and @code{argv} values passed to the
7520 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7521 generates the C main program to automatically set these variables.
7522 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7523 set these variables. If they are not set, the procedures in
7524 @code{Ada.Command_Line} will not be available, and any attempt to use
7525 them will raise @code{Constraint_Error}. If command line access is
7526 required, your main program must set @code{gnat_argc} and
7527 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7528 it.
7529
7530
7531 @node Search Paths for gnatbind
7532 @section Search Paths for @code{gnatbind}
7533
7534 @noindent
7535 The binder takes the name of an ALI file as its argument and needs to
7536 locate source files as well as other ALI files to verify object consistency.
7537
7538 For source files, it follows exactly the same search rules as @code{gcc}
7539 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7540 directories searched are:
7541
7542 @enumerate
7543 @item
7544 The directory containing the ALI file named in the command line, unless
7545 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7546
7547 @item
7548 All directories specified by @option{^-I^/SEARCH^}
7549 switches on the @code{gnatbind}
7550 command line, in the order given.
7551
7552 @item
7553 @findex ADA_OBJECTS_PATH
7554 Each of the directories listed in the value of the
7555 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7556 @ifset unw
7557 Construct this value
7558 exactly as the @code{PATH} environment variable: a list of directory
7559 names separated by colons (semicolons when working with the NT version
7560 of GNAT).
7561 @end ifset
7562 @ifset vms
7563 Normally, define this value as a logical name containing a comma separated
7564 list of directory names.
7565
7566 This variable can also be defined by means of an environment string
7567 (an argument to the DEC C exec* set of functions).
7568
7569 Logical Name:
7570 @smallexample
7571 DEFINE ANOTHER_PATH FOO:[BAG]
7572 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7573 @end smallexample
7574
7575 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7576 first, followed by the standard Ada 95
7577 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7578 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
7579 (Text_IO, Sequential_IO, etc)
7580 instead of the Ada95 packages. Thus, in order to get the Ada 95
7581 packages by default, ADA_OBJECTS_PATH must be redefined.
7582 @end ifset
7583
7584 @item
7585 @findex ADA_PRJ_OBJECTS_FILE
7586 Each of the directories listed in the text file whose name is given
7587 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7588
7589 @noindent
7590 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7591 driver when project files are used. It should not normally be set
7592 by other means.
7593
7594 @item
7595 The content of the @file{ada_object_path} file which is part of the GNAT
7596 installation tree and is used to store standard libraries such as the
7597 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7598 specified.
7599 @ifclear vms
7600 @ref{Installing the library}
7601 @end ifclear
7602 @end enumerate
7603
7604 @noindent
7605 In the binder the switch @option{^-I^/SEARCH^}
7606 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7607 is used to specify both source and
7608 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7609 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7610 instead if you want to specify
7611 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7612 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7613 if you want to specify library paths
7614 only. This means that for the binder
7615 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7616 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7617 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7618 The binder generates the bind file (a C language source file) in the
7619 current working directory.
7620
7621 @findex Ada
7622 @findex System
7623 @findex Interfaces
7624 @findex GNAT
7625 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7626 children make up the GNAT Run-Time Library, together with the package
7627 GNAT and its children, which contain a set of useful additional
7628 library functions provided by GNAT. The sources for these units are
7629 needed by the compiler and are kept together in one directory. The ALI
7630 files and object files generated by compiling the RTL are needed by the
7631 binder and the linker and are kept together in one directory, typically
7632 different from the directory containing the sources. In a normal
7633 installation, you need not specify these directory names when compiling
7634 or binding. Either the environment variables or the built-in defaults
7635 cause these files to be found.
7636
7637 Besides simplifying access to the RTL, a major use of search paths is
7638 in compiling sources from multiple directories. This can make
7639 development environments much more flexible.
7640
7641 @node Examples of gnatbind Usage
7642 @section Examples of @code{gnatbind} Usage
7643
7644 @noindent
7645 This section contains a number of examples of using the GNAT binding
7646 utility @code{gnatbind}.
7647
7648 @table @code
7649 @item gnatbind hello
7650 The main program @code{Hello} (source program in @file{hello.adb}) is
7651 bound using the standard switch settings. The generated main program is
7652 @file{b~hello.adb}. This is the normal, default use of the binder.
7653
7654 @ifclear vms
7655 @item gnatbind hello -o mainprog.adb
7656 @end ifclear
7657 @ifset vms
7658 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7659 @end ifset
7660 The main program @code{Hello} (source program in @file{hello.adb}) is
7661 bound using the standard switch settings. The generated main program is
7662 @file{mainprog.adb} with the associated spec in
7663 @file{mainprog.ads}. Note that you must specify the body here not the
7664 spec, in the case where the output is in Ada. Note that if this option
7665 is used, then linking must be done manually, since gnatlink will not
7666 be able to find the generated file.
7667
7668 @ifclear vms
7669 @item gnatbind main -C -o mainprog.c -x
7670 @end ifclear
7671 @ifset vms
7672 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7673 @end ifset
7674 The main program @code{Main} (source program in
7675 @file{main.adb}) is bound, excluding source files from the
7676 consistency checking, generating
7677 the file @file{mainprog.c}.
7678
7679 @ifclear vms
7680 @item gnatbind -x main_program -C -o mainprog.c
7681 This command is exactly the same as the previous example. Switches may
7682 appear anywhere in the command line, and single letter switches may be
7683 combined into a single switch.
7684 @end ifclear
7685
7686 @ifclear vms
7687 @item gnatbind -n math dbase -C -o ada-control.c
7688 @end ifclear
7689 @ifset vms
7690 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7691 @end ifset
7692 The main program is in a language other than Ada, but calls to
7693 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7694 to @code{gnatbind} generates the file @file{ada-control.c} containing
7695 the @code{adainit} and @code{adafinal} routines to be called before and
7696 after accessing the Ada units.
7697 @end table
7698
7699
7700 @c ------------------------------------
7701 @node Linking Using gnatlink
7702 @chapter Linking Using @code{gnatlink}
7703 @c ------------------------------------
7704 @findex gnatlink
7705
7706 @noindent
7707 This chapter discusses @code{gnatlink}, a tool that links
7708 an Ada program and builds an executable file. This utility
7709 invokes the system linker ^(via the @code{gcc} command)^^
7710 with a correct list of object files and library references.
7711 @code{gnatlink} automatically determines the list of files and
7712 references for the Ada part of a program. It uses the binder file
7713 generated by the @command{gnatbind} to determine this list.
7714
7715 @menu
7716 * Running gnatlink::
7717 * Switches for gnatlink::
7718 * Setting Stack Size from gnatlink::
7719 * Setting Heap Size from gnatlink::
7720 @end menu
7721
7722 @node Running gnatlink
7723 @section Running @code{gnatlink}
7724
7725 @noindent
7726 The form of the @code{gnatlink} command is
7727
7728 @smallexample
7729 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
7730            [@var{non-Ada objects}] [@var{linker options}]
7731 @end smallexample
7732
7733 @noindent
7734 The arguments of @code{gnatlink} (switches, main @file{ALI} file,
7735 non-Ada objects
7736 or linker options) may be in any order, provided that no non-Ada object may
7737 be mistaken for a main @file{ALI} file.
7738 Any file name @file{F} without the @file{.ali}
7739 extension will be taken as the main @file{ALI} file if a file exists
7740 whose name is the concatenation of @file{F} and @file{.ali}.
7741
7742 @noindent
7743 @file{@var{mainprog}.ali} references the ALI file of the main program.
7744 The @file{.ali} extension of this file can be omitted. From this
7745 reference, @code{gnatlink} locates the corresponding binder file
7746 @file{b~@var{mainprog}.adb} and, using the information in this file along
7747 with the list of non-Ada objects and linker options, constructs a
7748 linker command file to create the executable.
7749
7750 The arguments other than the @code{gnatlink} switches and the main @file{ALI}
7751 file are passed to the linker uninterpreted.
7752 They typically include the names of
7753 object files for units written in other languages than Ada and any library
7754 references required to resolve references in any of these foreign language
7755 units, or in @code{Import} pragmas in any Ada units.
7756
7757 @var{linker options} is an optional list of linker specific
7758 switches.
7759 The default linker called by gnatlink is @var{gcc} which in
7760 turn calls the appropriate system linker.
7761 Standard options for the linker such as @option{-lmy_lib} or
7762 @option{-Ldir} can be added as is.
7763 For options that are not recognized by
7764 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7765 @option{-Wl,}.
7766 Refer to the GCC documentation for
7767 details. Here is an example showing how to generate a linker map:
7768
7769 @ifclear vms
7770 @smallexample
7771 $ gnatlink my_prog -Wl,-Map,MAPFILE
7772 @end smallexample
7773 @end ifclear
7774
7775 @ifset vms
7776 <<Need example for VMS>>
7777 @end ifset
7778
7779 Using @var{linker options} it is possible to set the program stack and
7780 heap size. See @ref{Setting Stack Size from gnatlink}, and
7781 @ref{Setting Heap Size from gnatlink}.
7782
7783 @code{gnatlink} determines the list of objects required by the Ada
7784 program and prepends them to the list of objects passed to the linker.
7785 @code{gnatlink} also gathers any arguments set by the use of
7786 @code{pragma Linker_Options} and adds them to the list of arguments
7787 presented to the linker.
7788
7789 @ifset vms
7790 @code{gnatlink} accepts the following types of extra files on the command
7791 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7792 options files (.OPT). These are recognized and handled according to their
7793 extension.
7794 @end ifset
7795
7796 @node Switches for gnatlink
7797 @section Switches for @code{gnatlink}
7798
7799 @noindent
7800 The following switches are available with the @code{gnatlink} utility:
7801
7802 @table @option
7803 @c !sort!
7804
7805 @item ^-A^/BIND_FILE=ADA^
7806 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatlink})
7807 The binder has generated code in Ada. This is the default.
7808
7809 @item ^-C^/BIND_FILE=C^
7810 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatlink})
7811 If instead of generating a file in Ada, the binder has generated one in
7812 C, then the linker needs to know about it. Use this switch to signal
7813 to @code{gnatlink} that the binder has generated C code rather than
7814 Ada code.
7815
7816 @item ^-f^/FORCE_OBJECT_FILE_LIST^
7817 @cindex Command line length
7818 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@code{gnatlink})
7819 On some targets, the command line length is limited, and @code{gnatlink}
7820 will generate a separate file for the linker if the list of object files
7821 is too long.
7822 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
7823 to be generated even if
7824 the limit is not exceeded. This is useful in some cases to deal with
7825 special situations where the command line length is exceeded.
7826
7827 @item ^-g^/DEBUG^
7828 @cindex Debugging information, including
7829 @cindex @option{^-g^/DEBUG^} (@code{gnatlink})
7830 The option to include debugging information causes the Ada bind file (in
7831 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7832 @option{^-g^/DEBUG^}.
7833 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7834 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7835 Without @option{^-g^/DEBUG^}, the binder removes these files by
7836 default. The same procedure apply if a C bind file was generated using
7837 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
7838 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7839
7840 @item ^-n^/NOCOMPILE^
7841 @cindex @option{^-n^/NOCOMPILE^} (@code{gnatlink})
7842 Do not compile the file generated by the binder. This may be used when
7843 a link is rerun with different options, but there is no need to recompile
7844 the binder file.
7845
7846 @item ^-v^/VERBOSE^
7847 @cindex @option{^-v^/VERBOSE^} (@code{gnatlink})
7848 Causes additional information to be output, including a full list of the
7849 included object files. This switch option is most useful when you want
7850 to see what set of object files are being used in the link step.
7851
7852 @item ^-v -v^/VERBOSE/VERBOSE^
7853 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@code{gnatlink})
7854 Very verbose mode. Requests that the compiler operate in verbose mode when
7855 it compiles the binder file, and that the system linker run in verbose mode.
7856
7857 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7858 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatlink})
7859 @var{exec-name} specifies an alternate name for the generated
7860 executable program. If this switch is omitted, the executable has the same
7861 name as the main unit. For example, @code{gnatlink try.ali} creates
7862 an executable called @file{^try^TRY.EXE^}.
7863
7864 @ifclear vms
7865 @item -b @var{target}
7866 @cindex @option{-b} (@code{gnatlink})
7867 Compile your program to run on @var{target}, which is the name of a
7868 system configuration. You must have a GNAT cross-compiler built if
7869 @var{target} is not the same as your host system.
7870
7871 @item -B@var{dir}
7872 @cindex @option{-B} (@code{gnatlink})
7873 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7874 from @var{dir} instead of the default location. Only use this switch
7875 when multiple versions of the GNAT compiler are available. See the
7876 @code{gcc} manual page for further details. You would normally use the
7877 @option{-b} or @option{-V} switch instead.
7878
7879 @item --GCC=@var{compiler_name}
7880 @cindex @option{--GCC=compiler_name} (@code{gnatlink})
7881 Program used for compiling the binder file. The default is
7882 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
7883 @code{compiler_name} contains spaces or other separator characters. As
7884 an example @option{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
7885 @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
7886 inserted after your command name. Thus in the above example the compiler
7887 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
7888 If several @option{--GCC=compiler_name} are used, only the last
7889 @var{compiler_name} is taken into account. However, all the additional
7890 switches are also taken into account. Thus,
7891 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7892 @option{--GCC="bar -x -y -z -t"}.
7893
7894 @item --LINK=@var{name}
7895 @cindex @option{--LINK=} (@code{gnatlink})
7896 @var{name} is the name of the linker to be invoked. This is especially
7897 useful in mixed language programs since languages such as C++ require
7898 their own linker to be used. When this switch is omitted, the default
7899 name for the linker is (@file{gcc}). When this switch is used, the
7900 specified linker is called instead of (@file{gcc}) with exactly the same
7901 parameters that would have been passed to (@file{gcc}) so if the desired
7902 linker requires different parameters it is necessary to use a wrapper
7903 script that massages the parameters before invoking the real linker. It
7904 may be useful to control the exact invocation by using the verbose
7905 switch.
7906
7907 @end ifclear
7908
7909 @ifset vms
7910 @item /DEBUG=TRACEBACK
7911 @cindex @code{/DEBUG=TRACEBACK} (@code{gnatlink})
7912 This qualifier causes sufficient information to be included in the
7913 executable file to allow a traceback, but does not include the full
7914 symbol information needed by the debugger.
7915
7916 @item /IDENTIFICATION="<string>"
7917 @code{"<string>"} specifies the string to be stored in the image file
7918 identification field in the image header.
7919 It overrides any pragma @code{Ident} specified string.
7920
7921 @item /NOINHIBIT-EXEC
7922 Generate the executable file even if there are linker warnings.
7923
7924 @item /NOSTART_FILES
7925 Don't link in the object file containing the ``main'' transfer address.
7926 Used when linking with a foreign language main program compiled with a
7927 Digital compiler.
7928
7929 @item /STATIC
7930 Prefer linking with object libraries over sharable images, even without
7931 /DEBUG.
7932 @end ifset
7933
7934 @end table
7935
7936 @node Setting Stack Size from gnatlink
7937 @section Setting Stack Size from @code{gnatlink}
7938
7939 @noindent
7940 Under Windows systems, it is possible to specify the program stack size from
7941 @code{gnatlink} using either:
7942
7943 @itemize @bullet
7944
7945 @item using @option{-Xlinker} linker option
7946
7947 @smallexample
7948 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
7949 @end smallexample
7950
7951 This sets the stack reserve size to 0x10000 bytes and the stack commit
7952 size to 0x1000 bytes.
7953
7954 @item using @option{-Wl} linker option
7955
7956 @smallexample
7957 $ gnatlink hello -Wl,--stack=0x1000000
7958 @end smallexample
7959
7960 This sets the stack reserve size to 0x1000000 bytes. Note that with
7961 @option{-Wl} option it is not possible to set the stack commit size
7962 because the coma is a separator for this option.
7963
7964 @end itemize
7965
7966 @node Setting Heap Size from gnatlink
7967 @section Setting Heap Size from @code{gnatlink}
7968
7969 @noindent
7970 Under Windows systems, it is possible to specify the program heap size from
7971 @code{gnatlink} using either:
7972
7973 @itemize @bullet
7974
7975 @item using @option{-Xlinker} linker option
7976
7977 @smallexample
7978 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
7979 @end smallexample
7980
7981 This sets the heap reserve size to 0x10000 bytes and the heap commit
7982 size to 0x1000 bytes.
7983
7984 @item using @option{-Wl} linker option
7985
7986 @smallexample
7987 $ gnatlink hello -Wl,--heap=0x1000000
7988 @end smallexample
7989
7990 This sets the heap reserve size to 0x1000000 bytes. Note that with
7991 @option{-Wl} option it is not possible to set the heap commit size
7992 because the coma is a separator for this option.
7993
7994 @end itemize
7995
7996 @node The GNAT Make Program gnatmake
7997 @chapter The GNAT Make Program @code{gnatmake}
7998 @findex gnatmake
7999
8000 @menu
8001 * Running gnatmake::
8002 * Switches for gnatmake::
8003 * Mode Switches for gnatmake::
8004 * Notes on the Command Line::
8005 * How gnatmake Works::
8006 * Examples of gnatmake Usage::
8007 @end menu
8008 @noindent
8009 A typical development cycle when working on an Ada program consists of
8010 the following steps:
8011
8012 @enumerate
8013 @item
8014 Edit some sources to fix bugs.
8015
8016 @item
8017 Add enhancements.
8018
8019 @item
8020 Compile all sources affected.
8021
8022 @item
8023 Rebind and relink.
8024
8025 @item
8026 Test.
8027 @end enumerate
8028
8029 @noindent
8030 The third step can be tricky, because not only do the modified files
8031 @cindex Dependency rules
8032 have to be compiled, but any files depending on these files must also be
8033 recompiled. The dependency rules in Ada can be quite complex, especially
8034 in the presence of overloading, @code{use} clauses, generics and inlined
8035 subprograms.
8036
8037 @code{gnatmake} automatically takes care of the third and fourth steps
8038 of this process. It determines which sources need to be compiled,
8039 compiles them, and binds and links the resulting object files.
8040
8041 Unlike some other Ada make programs, the dependencies are always
8042 accurately recomputed from the new sources. The source based approach of
8043 the GNAT compilation model makes this possible. This means that if
8044 changes to the source program cause corresponding changes in
8045 dependencies, they will always be tracked exactly correctly by
8046 @code{gnatmake}.
8047
8048 @node Running gnatmake
8049 @section Running @code{gnatmake}
8050
8051 @noindent
8052 The usual form of the @code{gnatmake} command is
8053
8054 @smallexample
8055 $ gnatmake [@var{switches}] @var{file_name}
8056       [@var{file_names}] [@var{mode_switches}]
8057 @end smallexample
8058
8059 @noindent
8060 The only required argument is one @var{file_name}, which specifies
8061 a compilation unit that is a main program. Several @var{file_names} can be
8062 specified: this will result in several executables being built.
8063 If @code{switches} are present, they can be placed before the first
8064 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8065 If @var{mode_switches} are present, they must always be placed after
8066 the last @var{file_name} and all @code{switches}.
8067
8068 If you are using standard file extensions (.adb and .ads), then the
8069 extension may be omitted from the @var{file_name} arguments. However, if
8070 you are using non-standard extensions, then it is required that the
8071 extension be given. A relative or absolute directory path can be
8072 specified in a @var{file_name}, in which case, the input source file will
8073 be searched for in the specified directory only. Otherwise, the input
8074 source file will first be searched in the directory where
8075 @code{gnatmake} was invoked and if it is not found, it will be search on
8076 the source path of the compiler as described in
8077 @ref{Search Paths and the Run-Time Library (RTL)}.
8078
8079 All @code{gnatmake} output (except when you specify
8080 @option{^-M^/DEPENDENCIES_LIST^}) is to
8081 @file{stderr}. The output produced by the
8082 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8083 @file{stdout}.
8084
8085 @node Switches for gnatmake
8086 @section Switches for @code{gnatmake}
8087
8088 @noindent
8089 You may specify any of the following switches to @code{gnatmake}:
8090
8091 @table @option
8092 @c !sort!
8093 @ifclear vms
8094 @item --GCC=@var{compiler_name}
8095 @cindex @option{--GCC=compiler_name} (@code{gnatmake})
8096 Program used for compiling. The default is `@code{gcc}'. You need to use
8097 quotes around @var{compiler_name} if @code{compiler_name} contains
8098 spaces or other separator characters. As an example @option{--GCC="foo -x
8099 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
8100 compiler. Note that switch @option{-c} is always inserted after your
8101 command name. Thus in the above example the compiler command that will
8102 be used by @code{gnatmake} will be @code{foo -c -x -y}.
8103 If several @option{--GCC=compiler_name} are used, only the last
8104 @var{compiler_name} is taken into account. However, all the additional
8105 switches are also taken into account. Thus,
8106 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8107 @option{--GCC="bar -x -y -z -t"}.
8108
8109 @item --GNATBIND=@var{binder_name}
8110 @cindex @option{--GNATBIND=binder_name} (@code{gnatmake})
8111 Program used for binding. The default is `@code{gnatbind}'. You need to
8112 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8113 or other separator characters. As an example @option{--GNATBIND="bar -x
8114 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
8115 binder. Binder switches that are normally appended by @code{gnatmake} to
8116 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8117
8118 @item --GNATLINK=@var{linker_name}
8119 @cindex @option{--GNATLINK=linker_name} (@code{gnatmake})
8120 Program used for linking. The default is `@code{gnatlink}'. You need to
8121 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8122 or other separator characters. As an example @option{--GNATLINK="lan -x
8123 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
8124 linker. Linker switches that are normally appended by @code{gnatmake} to
8125 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
8126
8127 @end ifclear
8128
8129 @item ^-a^/ALL_FILES^
8130 @cindex @option{^-a^/ALL_FILES^} (@code{gnatmake})
8131 Consider all files in the make process, even the GNAT internal system
8132 files (for example, the predefined Ada library files), as well as any
8133 locked files. Locked files are files whose ALI file is write-protected.
8134 By default,
8135 @code{gnatmake} does not check these files,
8136 because the assumption is that the GNAT internal files are properly up
8137 to date, and also that any write protected ALI files have been properly
8138 installed. Note that if there is an installation problem, such that one
8139 of these files is not up to date, it will be properly caught by the
8140 binder.
8141 You may have to specify this switch if you are working on GNAT
8142 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8143 in conjunction with @option{^-f^/FORCE_COMPILE^}
8144 if you need to recompile an entire application,
8145 including run-time files, using special configuration pragmas,
8146 such as a @code{Normalize_Scalars} pragma.
8147
8148 By default
8149 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8150 internal files with
8151 @ifclear vms
8152 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8153 @end ifclear
8154 @ifset vms
8155 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8156 @end ifset
8157
8158 @item ^-b^/ACTIONS=BIND^
8159 @cindex @option{^-b^/ACTIONS=BIND^} (@code{gnatmake})
8160 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8161 compilation and binding, but no link.
8162 Can be combined with @option{^-l^/ACTIONS=LINK^}
8163 to do binding and linking. When not combined with
8164 @option{^-c^/ACTIONS=COMPILE^}
8165 all the units in the closure of the main program must have been previously
8166 compiled and must be up to date. The root unit specified by @var{file_name}
8167 may be given without extension, with the source extension or, if no GNAT
8168 Project File is specified, with the ALI file extension.
8169
8170 @item ^-c^/ACTIONS=COMPILE^
8171 @cindex @option{^-c^/ACTIONS=COMPILE^} (@code{gnatmake})
8172 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8173 is also specified. Do not perform linking, except if both
8174 @option{^-b^/ACTIONS=BIND^} and
8175  @option{^-l^/ACTIONS=LINK^} are also specified.
8176 If the root unit specified by @var{file_name} is not a main unit, this is the
8177 default. Otherwise @code{gnatmake} will attempt binding and linking
8178 unless all objects are up to date and the executable is more recent than
8179 the objects.
8180
8181 @item ^-C^/MAPPING^
8182 @cindex @option{^-C^/MAPPING^} (@code{gnatmake})
8183 Use a temporary mapping file. A mapping file is a way to communicate to the
8184 compiler two mappings: from unit names to file names (without any directory
8185 information) and from file names to path names (with full directory
8186 information). These mappings are used by the compiler to short-circuit the path
8187 search. When @code{gnatmake} is invoked with this switch, it will create
8188 a temporary mapping file, initially populated by the project manager,
8189 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8190 Each invocation of the compiler will add the newly accessed sources to the
8191 mapping file. This will improve the source search during the next invocation
8192 of the compiler.
8193
8194 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8195 @cindex @option{^-C=^/USE_MAPPING^} (@code{gnatmake})
8196 Use a specific mapping file. The file, specified as a path name (absolute or
8197 relative) by this switch, should already exist, otherwise the switch is
8198 ineffective. The specified mapping file will be communicated to the compiler.
8199 This switch is not compatible with a project file
8200 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8201 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8202
8203 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8204 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatmake})
8205 Put all object files and ALI file in directory @var{dir}.
8206 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8207 and ALI files go in the current working directory.
8208
8209 This switch cannot be used when using a project file.
8210
8211 @ifclear vms
8212 @item -eL
8213 @cindex @option{-eL} (@code{gnatmake})
8214 Follow all symbolic links when processing project files.
8215 @end ifclear
8216
8217 @item ^-f^/FORCE_COMPILE^
8218 @cindex @option{^-f^/FORCE_COMPILE^} (@code{gnatmake})
8219 Force recompilations. Recompile all sources, even though some object
8220 files may be up to date, but don't recompile predefined or GNAT internal
8221 files or locked files (files with a write-protected ALI file),
8222 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8223
8224 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8225 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatmake})
8226 When using project files, if some errors or warnings are detected during
8227 parsing and verbose mode is not in effect (no use of switch
8228 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8229 file, rather than its simple file name.
8230
8231 @item ^-i^/IN_PLACE^
8232 @cindex @option{^-i^/IN_PLACE^} (@code{gnatmake})
8233 In normal mode, @code{gnatmake} compiles all object files and ALI files
8234 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8235 then instead object files and ALI files that already exist are overwritten
8236 in place. This means that once a large project is organized into separate
8237 directories in the desired manner, then @code{gnatmake} will automatically
8238 maintain and update this organization. If no ALI files are found on the
8239 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8240 the new object and ALI files are created in the
8241 directory containing the source being compiled. If another organization
8242 is desired, where objects and sources are kept in different directories,
8243 a useful technique is to create dummy ALI files in the desired directories.
8244 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
8245 the corresponding source file, and it will be put the resulting object
8246 and ALI files in the directory where it found the dummy file.
8247
8248 @item ^-j^/PROCESSES=^@var{n}
8249 @cindex @option{^-j^/PROCESSES^} (@code{gnatmake})
8250 @cindex Parallel make
8251 Use @var{n} processes to carry out the (re)compilations. On a
8252 multiprocessor machine compilations will occur in parallel. In the
8253 event of compilation errors, messages from various compilations might
8254 get interspersed (but @code{gnatmake} will give you the full ordered
8255 list of failing compiles at the end). If this is problematic, rerun
8256 the make process with n set to 1 to get a clean list of messages.
8257
8258 @item ^-k^/CONTINUE_ON_ERROR^
8259 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@code{gnatmake})
8260 Keep going. Continue as much as possible after a compilation error. To
8261 ease the programmer's task in case of compilation errors, the list of
8262 sources for which the compile fails is given when @code{gnatmake}
8263 terminates.
8264
8265 If @code{gnatmake} is invoked with several @file{file_names} and with this
8266 switch, if there are compilation errors when building an executable,
8267 @code{gnatmake} will not attempt to build the following executables.
8268
8269 @item ^-l^/ACTIONS=LINK^
8270 @cindex @option{^-l^/ACTIONS=LINK^} (@code{gnatmake})
8271 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8272 and linking. Linking will not be performed if combined with
8273 @option{^-c^/ACTIONS=COMPILE^}
8274 but not with @option{^-b^/ACTIONS=BIND^}.
8275 When not combined with @option{^-b^/ACTIONS=BIND^}
8276 all the units in the closure of the main program must have been previously
8277 compiled and must be up to date, and the main program need to have been bound.
8278 The root unit specified by @var{file_name}
8279 may be given without extension, with the source extension or, if no GNAT
8280 Project File is specified, with the ALI file extension.
8281
8282 @item ^-m^/MINIMAL_RECOMPILATION^
8283 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@code{gnatmake})
8284 Specifies that the minimum necessary amount of recompilations
8285 be performed. In this mode @code{gnatmake} ignores time
8286 stamp differences when the only
8287 modifications to a source file consist in adding/removing comments,
8288 empty lines, spaces or tabs. This means that if you have changed the
8289 comments in a source file or have simply reformatted it, using this
8290 switch will tell gnatmake not to recompile files that depend on it
8291 (provided other sources on which these files depend have undergone no
8292 semantic modifications). Note that the debugging information may be
8293 out of date with respect to the sources if the @option{-m} switch causes
8294 a compilation to be switched, so the use of this switch represents a
8295 trade-off between compilation time and accurate debugging information.
8296
8297 @item ^-M^/DEPENDENCIES_LIST^
8298 @cindex Dependencies, producing list
8299 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@code{gnatmake})
8300 Check if all objects are up to date. If they are, output the object
8301 dependences to @file{stdout} in a form that can be directly exploited in
8302 a @file{Makefile}. By default, each source file is prefixed with its
8303 (relative or absolute) directory name. This name is whatever you
8304 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8305 and @option{^-I^/SEARCH^} switches. If you use
8306 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8307 @option{^-q^/QUIET^}
8308 (see below), only the source file names,
8309 without relative paths, are output. If you just specify the
8310 @option{^-M^/DEPENDENCIES_LIST^}
8311 switch, dependencies of the GNAT internal system files are omitted. This
8312 is typically what you want. If you also specify
8313 the @option{^-a^/ALL_FILES^} switch,
8314 dependencies of the GNAT internal files are also listed. Note that
8315 dependencies of the objects in external Ada libraries (see switch
8316 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8317 are never reported.
8318
8319 @item ^-n^/DO_OBJECT_CHECK^
8320 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@code{gnatmake})
8321 Don't compile, bind, or link. Checks if all objects are up to date.
8322 If they are not, the full name of the first file that needs to be
8323 recompiled is printed.
8324 Repeated use of this option, followed by compiling the indicated source
8325 file, will eventually result in recompiling all required units.
8326
8327 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8328 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatmake})
8329 Output executable name. The name of the final executable program will be
8330 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8331 name for the executable will be the name of the input file in appropriate form
8332 for an executable file on the host system.
8333
8334 This switch cannot be used when invoking @code{gnatmake} with several
8335 @file{file_names}.
8336
8337 @item ^-P^/PROJECT_FILE=^@var{project}
8338 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatmake})
8339 Use project file @var{project}. Only one such switch can be used.
8340 See @ref{gnatmake and Project Files}.
8341
8342 @item ^-q^/QUIET^
8343 @cindex @option{^-q^/QUIET^} (@code{gnatmake})
8344 Quiet. When this flag is not set, the commands carried out by
8345 @code{gnatmake} are displayed.
8346
8347 @item ^-s^/SWITCH_CHECK/^
8348 @cindex @option{^-s^/SWITCH_CHECK^} (@code{gnatmake})
8349 Recompile if compiler switches have changed since last compilation.
8350 All compiler switches but -I and -o are taken into account in the
8351 following way:
8352 orders between different ``first letter'' switches are ignored, but
8353 orders between same switches are taken into account. For example,
8354 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8355 is equivalent to @option{-O -g}.
8356
8357 This switch is recommended when Integrated Preprocessing is used.
8358
8359 @item ^-u^/UNIQUE^
8360 @cindex @option{^-u^/UNIQUE^} (@code{gnatmake})
8361 Unique. Recompile at most the main files. It implies -c. Combined with
8362 -f, it is equivalent to calling the compiler directly. Note that using
8363 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8364 (see @ref{Project Files and Main Subprograms}).
8365
8366 @item ^-U^/ALL_PROJECTS^
8367 @cindex @option{^-U^/ALL_PROJECTS^} (@code{gnatmake})
8368 When used without a project file or with one or several mains on the command
8369 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8370 on the command line, all sources of all project files are checked and compiled
8371 if not up to date, and libraries are rebuilt, if necessary.
8372
8373 @item ^-v^/REASONS^
8374 @cindex @option{^-v^/REASONS^} (@code{gnatmake})
8375 Verbose. Displays the reason for all recompilations @code{gnatmake}
8376 decides are necessary.
8377
8378 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8379 Indicates the verbosity of the parsing of GNAT project files.
8380 See @ref{Switches Related to Project Files}.
8381
8382 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8383 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@code{gnatmake})
8384 Indicates that sources that are not part of any Project File may be compiled.
8385 Normally, when using Project Files, only sources that are part of a Project
8386 File may be compile. When this switch is used, a source outside of all Project
8387 Files may be compiled. The ALI file and the object file will be put in the
8388 object directory of the main Project. The compilation switches used will only
8389 be those specified on the command line.
8390
8391 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8392 Indicates that external variable @var{name} has the value @var{value}.
8393 The Project Manager will use this value for occurrences of
8394 @code{external(name)} when parsing the project file.
8395 See @ref{Switches Related to Project Files}.
8396
8397 @item ^-z^/NOMAIN^
8398 @cindex @option{^-z^/NOMAIN^} (@code{gnatmake})
8399 No main subprogram. Bind and link the program even if the unit name
8400 given on the command line is a package name. The resulting executable
8401 will execute the elaboration routines of the package and its closure,
8402 then the finalization routines.
8403
8404 @item ^-g^/DEBUG^
8405 @cindex @option{^-g^/DEBUG^} (@code{gnatmake})
8406 Enable debugging. This switch is simply passed to the compiler and to the
8407 linker.
8408
8409 @end table
8410
8411 @table @asis
8412 @item @code{gcc} @asis{switches}
8413 @ifclear vms
8414 Any uppercase or multi-character switch that is not a @code{gnatmake} switch
8415 is passed to @code{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8416 @end ifclear
8417 @ifset vms
8418 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8419 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8420 automatically treated as a compiler switch, and passed on to all
8421 compilations that are carried out.
8422 @end ifset
8423 @end table
8424
8425 @noindent
8426 Source and library search path switches:
8427
8428 @table @option
8429 @c !sort!
8430 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8431 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatmake})
8432 When looking for source files also look in directory @var{dir}.
8433 The order in which source files search is undertaken is
8434 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8435
8436 @item ^-aL^/SKIP_MISSING=^@var{dir}
8437 @cindex @option{^-aL^/SKIP_MISSING^} (@code{gnatmake})
8438 Consider @var{dir} as being an externally provided Ada library.
8439 Instructs @code{gnatmake} to skip compilation units whose @file{.ALI}
8440 files have been located in directory @var{dir}. This allows you to have
8441 missing bodies for the units in @var{dir} and to ignore out of date bodies
8442 for the same units. You still need to specify
8443 the location of the specs for these units by using the switches
8444 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8445 or @option{^-I^/SEARCH=^@var{dir}}.
8446 Note: this switch is provided for compatibility with previous versions
8447 of @code{gnatmake}. The easier method of causing standard libraries
8448 to be excluded from consideration is to write-protect the corresponding
8449 ALI files.
8450
8451 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8452 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatmake})
8453 When searching for library and object files, look in directory
8454 @var{dir}. The order in which library files are searched is described in
8455 @ref{Search Paths for gnatbind}.
8456
8457 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8458 @cindex Search paths, for @code{gnatmake}
8459 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@code{gnatmake})
8460 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8461 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8462
8463 @item ^-I^/SEARCH=^@var{dir}
8464 @cindex @option{^-I^/SEARCH^} (@code{gnatmake})
8465 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8466 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8467
8468 @item ^-I-^/NOCURRENT_DIRECTORY^
8469 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatmake})
8470 @cindex Source files, suppressing search
8471 Do not look for source files in the directory containing the source
8472 file named in the command line.
8473 Do not look for ALI or object files in the directory
8474 where @code{gnatmake} was invoked.
8475
8476 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8477 @cindex @option{^-L^/LIBRARY_SEARCH^} (@code{gnatmake})
8478 @cindex Linker libraries
8479 Add directory @var{dir} to the list of directories in which the linker
8480 will search for libraries. This is equivalent to
8481 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8482 @ifclear vms
8483 Furthermore, under Windows, the sources pointed to by the libraries path
8484 set in the registry are not searched for.
8485 @end ifclear
8486
8487 @item -nostdinc
8488 @cindex @option{-nostdinc} (@code{gnatmake})
8489 Do not look for source files in the system default directory.
8490
8491 @item -nostdlib
8492 @cindex @option{-nostdlib} (@code{gnatmake})
8493 Do not look for library files in the system default directory.
8494
8495 @item --RTS=@var{rts-path}
8496 @cindex @option{--RTS} (@code{gnatmake})
8497 Specifies the default location of the runtime library. GNAT looks for the
8498 runtime
8499 in the following directories, and stops as soon as a valid runtime is found
8500 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8501 @file{ada_object_path} present):
8502
8503 @itemize @bullet
8504 @item <current directory>/$rts_path
8505
8506 @item <default-search-dir>/$rts_path
8507
8508 @item <default-search-dir>/rts-$rts_path
8509 @end itemize
8510
8511 @noindent
8512 The selected path is handled like a normal RTS path.
8513
8514 @end table
8515
8516 @node Mode Switches for gnatmake
8517 @section Mode Switches for @code{gnatmake}
8518
8519 @noindent
8520 The mode switches (referred to as @code{mode_switches}) allow the
8521 inclusion of switches that are to be passed to the compiler itself, the
8522 binder or the linker. The effect of a mode switch is to cause all
8523 subsequent switches up to the end of the switch list, or up to the next
8524 mode switch, to be interpreted as switches to be passed on to the
8525 designated component of GNAT.
8526
8527 @table @option
8528 @c !sort!
8529 @item -cargs @var{switches}
8530 @cindex @option{-cargs} (@code{gnatmake})
8531 Compiler switches. Here @var{switches} is a list of switches
8532 that are valid switches for @code{gcc}. They will be passed on to
8533 all compile steps performed by @code{gnatmake}.
8534
8535 @item -bargs @var{switches}
8536 @cindex @option{-bargs} (@code{gnatmake})
8537 Binder switches. Here @var{switches} is a list of switches
8538 that are valid switches for @code{gnatbind}. They will be passed on to
8539 all bind steps performed by @code{gnatmake}.
8540
8541 @item -largs @var{switches}
8542 @cindex @option{-largs} (@code{gnatmake})
8543 Linker switches. Here @var{switches} is a list of switches
8544 that are valid switches for @code{gnatlink}. They will be passed on to
8545 all link steps performed by @code{gnatmake}.
8546
8547 @item -margs @var{switches}
8548 @cindex @option{-margs} (@code{gnatmake})
8549 Make switches. The switches are directly interpreted by @code{gnatmake},
8550 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8551 or @option{-largs}.
8552 @end table
8553
8554 @node Notes on the Command Line
8555 @section Notes on the Command Line
8556
8557 @noindent
8558 This section contains some additional useful notes on the operation
8559 of the @code{gnatmake} command.
8560
8561 @itemize @bullet
8562 @item
8563 @cindex Recompilation, by @code{gnatmake}
8564 If @code{gnatmake} finds no ALI files, it recompiles the main program
8565 and all other units required by the main program.
8566 This means that @code{gnatmake}
8567 can be used for the initial compile, as well as during subsequent steps of
8568 the development cycle.
8569
8570 @item
8571 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8572 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8573 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8574 warning.
8575
8576 @item
8577 In @code{gnatmake} the switch @option{^-I^/SEARCH^}
8578 is used to specify both source and
8579 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8580 instead if you just want to specify
8581 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8582 if you want to specify library paths
8583 only.
8584
8585 @item
8586 @code{gnatmake} examines both an ALI file and its corresponding object file
8587 for consistency. If an ALI is more recent than its corresponding object,
8588 or if the object file is missing, the corresponding source will be recompiled.
8589 Note that @code{gnatmake} expects an ALI and the corresponding object file
8590 to be in the same directory.
8591
8592 @item
8593 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8594 This may conveniently be used to exclude standard libraries from
8595 consideration and in particular it means that the use of the
8596 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8597 unless @option{^-a^/ALL_FILES^} is also specified.
8598
8599 @item
8600 @code{gnatmake} has been designed to make the use of Ada libraries
8601 particularly convenient. Assume you have an Ada library organized
8602 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8603 of your Ada compilation units,
8604 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8605 specs of these units, but no bodies. Then to compile a unit
8606 stored in @code{main.adb}, which uses this Ada library you would just type
8607
8608 @smallexample
8609 @ifclear vms
8610 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8611 @end ifclear
8612 @ifset vms
8613 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8614            /SKIP_MISSING=@i{[OBJ_DIR]} main
8615 @end ifset
8616 @end smallexample
8617
8618 @item
8619 Using @code{gnatmake} along with the
8620 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8621 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8622 this switch,
8623 you can update the comments/format of your
8624 source files without having to recompile everything. Note, however, that
8625 adding or deleting lines in a source files may render its debugging
8626 info obsolete. If the file in question is a spec, the impact is rather
8627 limited, as that debugging info will only be useful during the
8628 elaboration phase of your program. For bodies the impact can be more
8629 significant. In all events, your debugger will warn you if a source file
8630 is more recent than the corresponding object, and alert you to the fact
8631 that the debugging information may be out of date.
8632 @end itemize
8633
8634 @node How gnatmake Works
8635 @section How @code{gnatmake} Works
8636
8637 @noindent
8638 Generally @code{gnatmake} automatically performs all necessary
8639 recompilations and you don't need to worry about how it works. However,
8640 it may be useful to have some basic understanding of the @code{gnatmake}
8641 approach and in particular to understand how it uses the results of
8642 previous compilations without incorrectly depending on them.
8643
8644 First a definition: an object file is considered @dfn{up to date} if the
8645 corresponding ALI file exists and its time stamp predates that of the
8646 object file and if all the source files listed in the
8647 dependency section of this ALI file have time stamps matching those in
8648 the ALI file. This means that neither the source file itself nor any
8649 files that it depends on have been modified, and hence there is no need
8650 to recompile this file.
8651
8652 @code{gnatmake} works by first checking if the specified main unit is up
8653 to date. If so, no compilations are required for the main unit. If not,
8654 @code{gnatmake} compiles the main program to build a new ALI file that
8655 reflects the latest sources. Then the ALI file of the main unit is
8656 examined to find all the source files on which the main program depends,
8657 and @code{gnatmake} recursively applies the above procedure on all these files.
8658
8659 This process ensures that @code{gnatmake} only trusts the dependencies
8660 in an existing ALI file if they are known to be correct. Otherwise it
8661 always recompiles to determine a new, guaranteed accurate set of
8662 dependencies. As a result the program is compiled ``upside down'' from what may
8663 be more familiar as the required order of compilation in some other Ada
8664 systems. In particular, clients are compiled before the units on which
8665 they depend. The ability of GNAT to compile in any order is critical in
8666 allowing an order of compilation to be chosen that guarantees that
8667 @code{gnatmake} will recompute a correct set of new dependencies if
8668 necessary.
8669
8670 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
8671 imported by several of the executables, it will be recompiled at most once.
8672
8673 Note: when using non-standard naming conventions
8674 (See @ref{Using Other File Names}), changing through a configuration pragmas
8675 file the version of a source and invoking @code{gnatmake} to recompile may
8676 have no effect, if the previous version of the source is still accessible
8677 by @code{gnatmake}. It may be necessary to use the switch ^-f^/FORCE_COMPILE^.
8678
8679 @node Examples of gnatmake Usage
8680 @section Examples of @code{gnatmake} Usage
8681
8682 @table @code
8683 @item gnatmake hello.adb
8684 Compile all files necessary to bind and link the main program
8685 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8686 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8687
8688 @item gnatmake main1 main2 main3
8689 Compile all files necessary to bind and link the main programs
8690 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8691 (containing unit @code{Main2}) and @file{main3.adb}
8692 (containing unit @code{Main3}) and bind and link the resulting object files
8693 to generate three executable files @file{^main1^MAIN1.EXE^},
8694 @file{^main2^MAIN2.EXE^}
8695 and @file{^main3^MAIN3.EXE^}.
8696
8697 @ifclear vms
8698 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8699 @end ifclear
8700
8701 @ifset vms
8702 @item gnatmake Main_Unit /QUIET
8703    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8704    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8705 @end ifset
8706 Compile all files necessary to bind and link the main program unit
8707 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8708 be done with optimization level 2 and the order of elaboration will be
8709 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8710 displaying commands it is executing.
8711 @end table
8712
8713
8714 @c *************************
8715 @node Improving Performance
8716 @chapter Improving Performance
8717 @cindex Improving performance
8718
8719 @noindent
8720 This chapter presents several topics related to program performance.
8721 It first describes some of the tradeoffs that need to be considered
8722 and some of the techniques for making your program run faster.
8723 It then documents the @command{gnatelim} tool, which can reduce
8724 the size of program executables.
8725
8726 @ifnottex
8727 @menu
8728 * Performance Considerations::
8729 * Reducing the Size of Ada Executables with gnatelim::
8730 @end menu
8731 @end ifnottex
8732
8733
8734 @c *****************************
8735 @node Performance Considerations
8736 @section Performance Considerations
8737
8738 @noindent
8739 The GNAT system provides a number of options that allow a trade-off
8740 between
8741
8742 @itemize @bullet
8743 @item
8744 performance of the generated code
8745
8746 @item
8747 speed of compilation
8748
8749 @item
8750 minimization of dependences and recompilation
8751
8752 @item
8753 the degree of run-time checking.
8754 @end itemize
8755
8756 @noindent
8757 The defaults (if no options are selected) aim at improving the speed
8758 of compilation and minimizing dependences, at the expense of performance
8759 of the generated code:
8760
8761 @itemize @bullet
8762 @item
8763 no optimization
8764
8765 @item
8766 no inlining of subprogram calls
8767
8768 @item
8769 all run-time checks enabled except overflow and elaboration checks
8770 @end itemize
8771
8772 @noindent
8773 These options are suitable for most program development purposes. This
8774 chapter describes how you can modify these choices, and also provides
8775 some guidelines on debugging optimized code.
8776
8777 @menu
8778 * Controlling Run-Time Checks::
8779 * Use of Restrictions::
8780 * Optimization Levels::
8781 * Debugging Optimized Code::
8782 * Inlining of Subprograms::
8783 * Optimization and Strict Aliasing::
8784 @ifset vms
8785 * Coverage Analysis::
8786 @end ifset
8787 @end menu
8788
8789 @node Controlling Run-Time Checks
8790 @subsection Controlling Run-Time Checks
8791
8792 @noindent
8793 By default, GNAT generates all run-time checks, except arithmetic overflow
8794 checking for integer operations and checks for access before elaboration on
8795 subprogram calls. The latter are not required in default mode, because all
8796 necessary checking is done at compile time.
8797 @cindex @option{-gnatp} (@code{gcc})
8798 @cindex @option{-gnato} (@code{gcc})
8799 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8800 be modified. @xref{Run-Time Checks}.
8801
8802 Our experience is that the default is suitable for most development
8803 purposes.
8804
8805 We treat integer overflow specially because these
8806 are quite expensive and in our experience are not as important as other
8807 run-time checks in the development process. Note that division by zero
8808 is not considered an overflow check, and divide by zero checks are
8809 generated where required by default.
8810
8811 Elaboration checks are off by default, and also not needed by default, since
8812 GNAT uses a static elaboration analysis approach that avoids the need for
8813 run-time checking. This manual contains a full chapter discussing the issue
8814 of elaboration checks, and if the default is not satisfactory for your use,
8815 you should read this chapter.
8816
8817 For validity checks, the minimal checks required by the Ada Reference
8818 Manual (for case statements and assignments to array elements) are on
8819 by default. These can be suppressed by use of the @option{-gnatVn} switch.
8820 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8821 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8822 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8823 are also suppressed entirely if @option{-gnatp} is used.
8824
8825 @cindex Overflow checks
8826 @cindex Checks, overflow
8827 @findex Suppress
8828 @findex Unsuppress
8829 @cindex pragma Suppress
8830 @cindex pragma Unsuppress
8831 Note that the setting of the switches controls the default setting of
8832 the checks. They may be modified using either @code{pragma Suppress} (to
8833 remove checks) or @code{pragma Unsuppress} (to add back suppressed
8834 checks) in the program source.
8835
8836 @node Use of Restrictions
8837 @subsection Use of Restrictions
8838
8839 @noindent
8840 The use of pragma Restrictions allows you to control which features are
8841 permitted in your program. Apart from the obvious point that if you avoid
8842 relatively expensive features like finalization (enforceable by the use
8843 of pragma Restrictions (No_Finalization), the use of this pragma does not
8844 affect the generated code in most cases.
8845
8846 One notable exception to this rule is that the possibility of task abort
8847 results in some distributed overhead, particularly if finalization or
8848 exception handlers are used. The reason is that certain sections of code
8849 have to be marked as non-abortable.
8850
8851 If you use neither the @code{abort} statement, nor asynchronous transfer
8852 of control (@code{select .. then abort}), then this distributed overhead
8853 is removed, which may have a general positive effect in improving
8854 overall performance.  Especially code involving frequent use of tasking
8855 constructs and controlled types will show much improved performance.
8856 The relevant restrictions pragmas are
8857
8858 @smallexample
8859    pragma Restrictions (No_Abort_Statements);
8860    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
8861 @end smallexample
8862
8863 @noindent
8864 It is recommended that these restriction pragmas be used if possible. Note
8865 that this also means that you can write code without worrying about the
8866 possibility of an immediate abort at any point.
8867
8868 @node Optimization Levels
8869 @subsection Optimization Levels
8870 @cindex @option{^-O^/OPTIMIZE^} (@code{gcc})
8871
8872 @noindent
8873 The default is optimization off. This results in the fastest compile
8874 times, but GNAT makes absolutely no attempt to optimize, and the
8875 generated programs are considerably larger and slower than when
8876 optimization is enabled. You can use the
8877 @ifclear vms
8878 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
8879 @end ifclear
8880 @ifset vms
8881 @code{OPTIMIZE} qualifier
8882 @end ifset
8883 to @code{gcc} to control the optimization level:
8884
8885 @table @option
8886 @item ^-O0^/OPTIMIZE=NONE^
8887 No optimization (the default);
8888 generates unoptimized code but has
8889 the fastest compilation time.
8890
8891 @item ^-O1^/OPTIMIZE=SOME^
8892 Medium level optimization;
8893 optimizes reasonably well but does not
8894 degrade compilation time significantly.
8895
8896 @item ^-O2^/OPTIMIZE=ALL^
8897 @ifset vms
8898 @itemx /OPTIMIZE=DEVELOPMENT
8899 @end ifset
8900 Full optimization;
8901 generates highly optimized code and has
8902 the slowest compilation time.
8903
8904 @item ^-O3^/OPTIMIZE=INLINING^
8905 Full optimization as in @option{-O2},
8906 and also attempts automatic inlining of small
8907 subprograms within a unit (@pxref{Inlining of Subprograms}).
8908 @end table
8909
8910 @noindent
8911 Higher optimization levels perform more global transformations on the
8912 program and apply more expensive analysis algorithms in order to generate
8913 faster and more compact code. The price in compilation time, and the
8914 resulting improvement in execution time,
8915 both depend on the particular application and the hardware environment.
8916 You should experiment to find the best level for your application.
8917
8918 Since the precise set of optimizations done at each level will vary from
8919 release to release (and sometime from target to target), it is best to think
8920 of the optimization settings in general terms.
8921 The @cite{Using GNU GCC} manual contains details about
8922 ^the @option{-O} settings and a number of @option{-f} options that^how to^
8923 individually enable or disable specific optimizations.
8924
8925 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
8926 been tested extensively at all optimization levels. There are some bugs
8927 which appear only with optimization turned on, but there have also been
8928 bugs which show up only in @emph{unoptimized} code. Selecting a lower
8929 level of optimization does not improve the reliability of the code
8930 generator, which in practice is highly reliable at all optimization
8931 levels.
8932
8933 Note regarding the use of @option{-O3}: The use of this optimization level
8934 is generally discouraged with GNAT, since it often results in larger
8935 executables which run more slowly. See further discussion of this point
8936 in @pxref{Inlining of Subprograms}.
8937
8938
8939 @node Debugging Optimized Code
8940 @subsection Debugging Optimized Code
8941 @cindex Debugging optimized code
8942 @cindex Optimization and debugging
8943
8944 @noindent
8945 Although it is possible to do a reasonable amount of debugging at
8946 @ifclear vms
8947 non-zero optimization levels,
8948 the higher the level the more likely that
8949 @end ifclear
8950 @ifset vms
8951 @option{/OPTIMIZE} settings other than @code{NONE},
8952 such settings will make it more likely that
8953 @end ifset
8954 source-level constructs will have been eliminated by optimization.
8955 For example, if a loop is strength-reduced, the loop
8956 control variable may be completely eliminated and thus cannot be
8957 displayed in the debugger.
8958 This can only happen at @option{-O2} or @option{-O3}.
8959 Explicit temporary variables that you code might be eliminated at
8960 ^level^setting^ @option{-O1} or higher.
8961
8962 The use of the @option{^-g^/DEBUG^} switch,
8963 @cindex @option{^-g^/DEBUG^} (@code{gcc})
8964 which is needed for source-level debugging,
8965 affects the size of the program executable on disk,
8966 and indeed the debugging information can be quite large.
8967 However, it has no effect on the generated code (and thus does not
8968 degrade performance)
8969
8970 Since the compiler generates debugging tables for a compilation unit before
8971 it performs optimizations, the optimizing transformations may invalidate some
8972 of the debugging data.  You therefore need to anticipate certain
8973 anomalous situations that may arise while debugging optimized code.
8974 These are the most common cases:
8975
8976 @enumerate
8977 @item
8978 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
8979 commands show
8980 the PC bouncing back and forth in the code.  This may result from any of
8981 the following optimizations:
8982
8983 @itemize @bullet
8984 @item
8985 @i{Common subexpression elimination:} using a single instance of code for a
8986 quantity that the source computes several times.  As a result you
8987 may not be able to stop on what looks like a statement.
8988
8989 @item
8990 @i{Invariant code motion:} moving an expression that does not change within a
8991 loop, to the beginning of the loop.
8992
8993 @item
8994 @i{Instruction scheduling:} moving instructions so as to
8995 overlap loads and stores (typically) with other code, or in
8996 general to move computations of values closer to their uses. Often
8997 this causes you to pass an assignment statement without the assignment
8998 happening and then later bounce back to the statement when the
8999 value is actually needed.  Placing a breakpoint on a line of code
9000 and then stepping over it may, therefore, not always cause all the
9001 expected side-effects.
9002 @end itemize
9003
9004 @item
9005 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9006 two identical pieces of code are merged and the program counter suddenly
9007 jumps to a statement that is not supposed to be executed, simply because
9008 it (and the code following) translates to the same thing as the code
9009 that @emph{was} supposed to be executed.  This effect is typically seen in
9010 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9011 a @code{break} in a C @code{^switch^switch^} statement.
9012
9013 @item
9014 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9015 There are various reasons for this effect:
9016
9017 @itemize @bullet
9018 @item
9019 In a subprogram prologue, a parameter may not yet have been moved to its
9020 ``home''.
9021
9022 @item
9023 A variable may be dead, and its register re-used.  This is
9024 probably the most common cause.
9025
9026 @item
9027 As mentioned above, the assignment of a value to a variable may
9028 have been moved.
9029
9030 @item
9031 A variable may be eliminated entirely by value propagation or
9032 other means.  In this case, GCC may incorrectly generate debugging
9033 information for the variable
9034 @end itemize
9035
9036 @noindent
9037 In general, when an unexpected value appears for a local variable or parameter
9038 you should first ascertain if that value was actually computed by
9039 your program, as opposed to being incorrectly reported by the debugger.
9040 Record fields or
9041 array elements in an object designated by an access value
9042 are generally less of a problem, once you have ascertained that the access
9043 value is sensible.
9044 Typically, this means checking variables in the preceding code and in the
9045 calling subprogram to verify that the value observed is explainable from other
9046 values (one must apply the procedure recursively to those
9047 other values); or re-running the code and stopping a little earlier
9048 (perhaps before the call) and stepping to better see how the variable obtained
9049 the value in question; or continuing to step @emph{from} the point of the
9050 strange value to see if code motion had simply moved the variable's
9051 assignments later.
9052 @end enumerate
9053
9054 @noindent
9055 In light of such anomalies, a recommended technique is to use @option{-O0}
9056 early in the software development cycle, when extensive debugging capabilities
9057 are most needed, and then move to @option{-O1} and later @option{-O2} as
9058 the debugger becomes less critical.
9059 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9060 a release management issue.
9061 @ifclear vms
9062 Note that if you use @option{-g} you can then use the @command{strip} program
9063 on the resulting executable,
9064 which removes both debugging information and global symbols.
9065 @end ifclear
9066
9067
9068 @node Inlining of Subprograms
9069 @subsection Inlining of Subprograms
9070
9071 @noindent
9072 A call to a subprogram in the current unit is inlined if all the
9073 following conditions are met:
9074
9075 @itemize @bullet
9076 @item
9077 The optimization level is at least @option{-O1}.
9078
9079 @item
9080 The called subprogram is suitable for inlining: It must be small enough
9081 and not contain nested subprograms or anything else that @code{gcc}
9082 cannot support in inlined subprograms.
9083
9084 @item
9085 The call occurs after the definition of the body of the subprogram.
9086
9087 @item
9088 @cindex pragma Inline
9089 @findex Inline
9090 Either @code{pragma Inline} applies to the subprogram or it is
9091 small and automatic inlining (optimization level @option{-O3}) is
9092 specified.
9093 @end itemize
9094
9095 @noindent
9096 Calls to subprograms in @code{with}'ed units are normally not inlined.
9097 To achieve this level of inlining, the following conditions must all be
9098 true:
9099
9100 @itemize @bullet
9101 @item
9102 The optimization level is at least @option{-O1}.
9103
9104 @item
9105 The called subprogram is suitable for inlining: It must be small enough
9106 and not contain nested subprograms or anything else @code{gcc} cannot
9107 support in inlined subprograms.
9108
9109 @item
9110 The call appears in a body (not in a package spec).
9111
9112 @item
9113 There is a @code{pragma Inline} for the subprogram.
9114
9115 @item
9116 @cindex @option{-gnatn} (@code{gcc})
9117 The @option{^-gnatn^/INLINE^} switch
9118 is used in the @code{gcc} command line
9119 @end itemize
9120
9121 Note that specifying the @option{-gnatn} switch causes additional
9122 compilation dependencies. Consider the following:
9123
9124 @smallexample @c ada
9125 @cartouche
9126 package R is
9127    procedure Q;
9128    pragma Inline (Q);
9129 end R;
9130 package body R is
9131    ...
9132 end R;
9133
9134 with R;
9135 procedure Main is
9136 begin
9137    ...
9138    R.Q;
9139 end Main;
9140 @end cartouche
9141 @end smallexample
9142
9143 @noindent
9144 With the default behavior (no @option{-gnatn} switch specified), the
9145 compilation of the @code{Main} procedure depends only on its own source,
9146 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9147 means that editing the body of @code{R} does not require recompiling
9148 @code{Main}.
9149
9150 On the other hand, the call @code{R.Q} is not inlined under these
9151 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9152 is compiled, the call will be inlined if the body of @code{Q} is small
9153 enough, but now @code{Main} depends on the body of @code{R} in
9154 @file{r.adb} as well as on the spec. This means that if this body is edited,
9155 the main program must be recompiled. Note that this extra dependency
9156 occurs whether or not the call is in fact inlined by @code{gcc}.
9157
9158 The use of front end inlining with @option{-gnatN} generates similar
9159 additional dependencies.
9160
9161 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@code{gcc})
9162 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9163 can be used to prevent
9164 all inlining. This switch overrides all other conditions and ensures
9165 that no inlining occurs. The extra dependences resulting from
9166 @option{-gnatn} will still be active, even if
9167 this switch is used to suppress the resulting inlining actions.
9168
9169 Note regarding the use of @option{-O3}: There is no difference in inlining
9170 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9171 pragma @code{Inline} assuming the use of @option{-gnatn}
9172 or @option{-gnatN} (the switches that activate inlining). If you have used
9173 pragma @code{Inline} in appropriate cases, then it is usually much better
9174 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9175 in this case only has the effect of inlining subprograms you did not
9176 think should be inlined. We often find that the use of @option{-O3} slows
9177 down code by performing excessive inlining, leading to increased instruction
9178 cache pressure from the increased code size. So the bottom line here is
9179 that you should not automatically assume that @option{-O3} is better than
9180 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9181 it actually improves performance.
9182
9183 @node Optimization and Strict Aliasing
9184 @subsection Optimization and Strict Aliasing
9185 @cindex Aliasing
9186 @cindex Strict Aliasing
9187 @cindex No_Strict_Aliasing
9188
9189 @noindent
9190 The strong typing capabilities of Ada allow an optimizer to generate
9191 efficient code in situations where other languages would be forced to
9192 make worst case assumptions preventing such optimizations. Consider
9193 the following example:
9194
9195 @smallexample @c ada
9196 @cartouche
9197 procedure R is
9198    type Int1 is new Integer;
9199    type Int2 is new Integer;
9200    type Int1A is access Int1;
9201    type Int2A is access Int2;
9202    Int1V : Int1A;
9203    Int2V : Int2A;
9204    ...
9205
9206 begin
9207    ...
9208    for J in Data'Range loop
9209       if Data (J) = Int1V.all then
9210          Int2V.all := Int2V.all + 1;
9211       end if;
9212    end loop;
9213    ...
9214 end R;
9215 @end cartouche
9216 @end smallexample
9217
9218 @noindent
9219 In this example, since the variable @code{Int1V} can only access objects
9220 of type @code{Int1}, and @code{Int2V} can only access objects of type
9221 @code{Int2}, there is no possibility that the assignment to
9222 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9223 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9224 for all iterations of the loop and avoid the extra memory reference
9225 required to dereference it each time through the loop.
9226
9227 This kind of optimziation, called strict aliasing analysis, is
9228 triggered by specifying an optimization level of @option{-O2} or
9229 higher and allows @code{GNAT} to generate more efficient code
9230 when access values are involved.
9231
9232 However, although this optimization is always correct in terms of
9233 the formal semantics of the Ada Reference Manual, difficulties can
9234 arise if features like @code{Unchecked_Conversion} are used to break
9235 the typing system. Consider the following complete program example:
9236
9237 @smallexample @c ada
9238 @cartouche
9239 package p1 is
9240    type int1 is new integer;
9241    type int2 is new integer;
9242    type a1 is access int1;
9243    type a2 is access int2;
9244 end p1;
9245
9246 with p1; use p1;
9247 package p2 is
9248    function to_a2 (Input : a1) return a2;
9249 end p2;
9250
9251 with Unchecked_Conversion;
9252 package body p2 is
9253    function to_a2 (Input : a1) return a2 is
9254       function to_a2u is
9255         new Unchecked_Conversion (a1, a2);
9256    begin
9257       return to_a2u (Input);
9258    end to_a2;
9259 end p2;
9260
9261 with p2; use p2;
9262 with p1; use p1;
9263 with Text_IO; use Text_IO;
9264 procedure m is
9265    v1 : a1 := new int1;
9266    v2 : a2 := to_a2 (v1);
9267 begin
9268    v1.all := 1;
9269    v2.all := 0;
9270    put_line (int1'image (v1.all));
9271 end;
9272 @end cartouche
9273 @end smallexample
9274
9275 @noindent
9276 This program prints out 0 in @code{-O0} or @code{-O1}
9277 mode, but it prints out 1 in @code{-O2} mode. That's
9278 because in strict aliasing mode, the compiler can and
9279 does assume that the assignment to @code{v2.all} could not
9280 affect the value of @code{v1.all}, since different types
9281 are involved.
9282
9283 This behavior is not a case of non-conformance with the standard, since
9284 the Ada RM specifies that an unchecked conversion where the resulting
9285 bit pattern is not a correct value of the target type can result in an
9286 abnormal value and attempting to reference an abnormal value makes the
9287 execution of a program erroneous.  That's the case here since the result
9288 does not point to an object of type @code{int2}.  This means that the
9289 effect is entirely unpredictable.
9290
9291 However, although that explanation may satisfy a language
9292 lawyer, in practice an applications programmer expects an
9293 unchecked conversion involving pointers to create true
9294 aliases and the behavior of printing 1 seems plain wrong.
9295 In this case, the strict aliasing optimization is unwelcome.
9296
9297 Indeed the compiler recognizes this possibility, and the
9298 unchecked conversion generates a warning:
9299
9300 @smallexample
9301 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9302 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9303 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9304 @end smallexample
9305
9306 @noindent
9307 Unfortunately the problem is recognized when compiling the body of
9308 package @code{p2}, but the actual "bad" code is generated while
9309 compiling the body of @code{m} and this latter compilation does not see
9310 the suspicious @code{Unchecked_Conversion}.
9311
9312 As implied by the warning message, there are approaches you can use to
9313 avoid the unwanted strict aliasing optimization in a case like this.
9314
9315 One possibility is to simply avoid the use of @code{-O2}, but
9316 that is a bit drastic, since it throws away a number of useful
9317 optimizations that do not involve strict aliasing assumptions.
9318
9319 A less drastic approach is to compile the program using the
9320 option @code{-fno-strict-aliasing}. Actually it is only the
9321 unit containing the dereferencing of the suspicious pointer
9322 that needs to be compiled. So in this case, if we compile
9323 unit @code{m} with this switch, then we get the expected
9324 value of zero printed. Analyzing which units might need
9325 the switch can be painful, so a more reasonable approach
9326 is to compile the entire program with options @code{-O2}
9327 and @code{-fno-strict-aliasing}. If the performance is
9328 satisfactory with this combination of options, then the
9329 advantage is that the entire issue of possible "wrong"
9330 optimization due to strict aliasing is avoided.
9331
9332 To avoid the use of compiler switches, the configuration
9333 pragma @code{No_Strict_Aliasing} with no parameters may be
9334 used to specify that for all access types, the strict
9335 aliasing optimization should be suppressed.
9336
9337 However, these approaches are still overkill, in that they causes
9338 all manipulations of all access values to be deoptimized. A more
9339 refined approach is to concentrate attention on the specific
9340 access type identified as problematic.
9341
9342 First, if a careful analysis of uses of the pointer shows
9343 that there are no possible problematic references, then
9344 the warning can be suppressed by bracketing the
9345 instantiation of @code{Unchecked_Conversion} to turn
9346 the warning off:
9347
9348 @smallexample @c ada
9349    pragma Warnings (Off);
9350    function to_a2u is
9351      new Unchecked_Conversion (a1, a2);
9352    pragma Warnings (On);
9353 @end smallexample
9354
9355 @noindent
9356 Of course that approach is not appropriate for this particular
9357 example, since indeed there is a problematic reference. In this
9358 case we can take one of two other approaches.
9359
9360 The first possibility is to move the instantiation of unchecked
9361 conversion to the unit in which the type is declared. In
9362 this example, we would move the instantiation of
9363 @code{Unchecked_Conversion} from the body of package
9364 @code{p2} to the spec of package @code{p1}. Now the
9365 warning disappears. That's because any use of the
9366 access type knows there is a suspicious unchecked
9367 conversion, and the strict aliasing optimization
9368 is automatically suppressed for the type.
9369
9370 If it is not practical to move the unchecked conversion to the same unit
9371 in which the destination access type is declared (perhaps because the
9372 source type is not visible in that unit), you may use pragma
9373 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9374 same declarative sequence as the declaration of the access type:
9375
9376 @smallexample @c ada
9377    type a2 is access int2;
9378    pragma No_Strict_Aliasing (a2);
9379 @end smallexample
9380
9381 @noindent
9382 Here again, the compiler now knows that the strict aliasing optimization
9383 should be suppressed for any reference to type @code{a2} and the
9384 expected behavior is obtained.
9385
9386 Finally, note that although the compiler can generate warnings for
9387 simple cases of unchecked conversions, there are tricker and more
9388 indirect ways of creating type incorrect aliases which the compiler
9389 cannot detect. Examples are the use of address overlays and unchecked
9390 conversions involving composite types containing access types as
9391 components. In such cases, no warnings are generated, but there can
9392 still be aliasing problems. One safe coding practice is to forbid the
9393 use of address clauses for type overlaying, and to allow unchecked
9394 conversion only for primitive types. This is not really a significant
9395 restriction since any possible desired effect can be achieved by
9396 unchecked conversion of access values.
9397
9398 @ifset vms
9399 @node Coverage Analysis
9400 @subsection Coverage Analysis
9401
9402 @noindent
9403 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
9404 the user to determine the distribution of execution time across a program,
9405 @pxref{Profiling} for details of usage.
9406 @end ifset
9407
9408 @node Reducing the Size of Ada Executables with gnatelim
9409 @section Reducing the Size of Ada Executables with @code{gnatelim}
9410 @findex gnatelim
9411
9412 @noindent
9413 This section describes @command{gnatelim}, a tool which detects unused
9414 subprograms and helps the compiler to create a smaller executable for your
9415 program.
9416
9417 @menu
9418 * About gnatelim::
9419 * Running gnatelim::
9420 * Correcting the List of Eliminate Pragmas::
9421 * Making Your Executables Smaller::
9422 * Summary of the gnatelim Usage Cycle::
9423 @end menu
9424
9425 @node About gnatelim
9426 @subsection About @code{gnatelim}
9427
9428 @noindent
9429 When a program shares a set of Ada
9430 packages with other programs, it may happen that this program uses
9431 only a fraction of the subprograms defined in these packages. The code
9432 created for these unused subprograms increases the size of the executable.
9433
9434 @code{gnatelim} tracks unused subprograms in an Ada program and
9435 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9436 subprograms that are declared but never called. By placing the list of
9437 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9438 recompiling your program, you may decrease the size of its executable,
9439 because the compiler will not generate the code for 'eliminated' subprograms.
9440 See GNAT Reference Manual for more information about this pragma.
9441
9442 @code{gnatelim} needs as its input data the name of the main subprogram
9443 and a bind file for a main subprogram.
9444
9445 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9446 the main subprogram. @code{gnatelim} can work with both Ada and C
9447 bind files; when both are present, it uses the Ada bind file.
9448 The following commands will build the program and create the bind file:
9449
9450 @smallexample
9451 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9452 $ gnatbind main_prog
9453 @end smallexample
9454
9455 Note that @code{gnatelim} needs neither object nor ALI files.
9456
9457 @node Running gnatelim
9458 @subsection Running @code{gnatelim}
9459
9460 @noindent
9461 @code{gnatelim} has the following command-line interface:
9462
9463 @smallexample
9464 $ gnatelim [options] name
9465 @end smallexample
9466
9467 @noindent
9468 @code{name} should be a name of a source file that contains the main subprogram
9469 of a program (partition).
9470
9471 @code{gnatelim} has the following switches:
9472
9473 @table @option
9474 @c !sort!
9475 @item ^-q^/QUIET^
9476 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9477 Quiet mode: by default @code{gnatelim} outputs to the standard error
9478 stream the number of program units left to be processed. This option turns
9479 this trace off.
9480
9481 @item ^-v^/VERBOSE^
9482 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9483 Verbose mode: @code{gnatelim} version information is printed as Ada
9484 comments to the standard output stream. Also, in addition to the number of
9485 program units left @code{gnatelim} will output the name of the current unit
9486 being processed.
9487
9488 @item ^-a^/ALL^
9489 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9490 Also look for subprograms from the GNAT run time that can be eliminated. Note
9491 that when @file{gnat.adc} is produced using this switch, the entire program
9492 must be recompiled with switch @option{^-a^/ALL_FILES^} to @code{gnatmake}.
9493
9494 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9495 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9496 When looking for source files also look in directory @var{dir}. Specifying
9497 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9498 sources in the current directory.
9499
9500 @item ^-b^/BIND_FILE=^@var{bind_file}
9501 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9502 Specifies @var{bind_file} as the bind file to process. If not set, the name
9503 of the bind file is computed from the full expanded Ada name
9504 of a main subprogram.
9505
9506 @item ^-C^/CONFIG_FILE=^@var{config_file}
9507 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9508 Specifies a file @var{config_file} that contains configuration pragmas. The
9509 file must be specified with full path.
9510
9511 @item ^--GCC^/COMPILER^=@var{compiler_name}
9512 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9513 Instructs @code{gnatelim} to use specific @code{gcc} compiler instead of one
9514 available on the path.
9515
9516 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9517 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9518 Instructs @code{gnatelim} to use specific @code{gnatmake} instead of one
9519 available on the path.
9520
9521 @item -d@var{x}
9522 @cindex @option{-d@var{x}} (@command{gnatelim})
9523 Activate internal debugging switches. @var{x} is a letter or digit, or
9524 string of letters or digits, which specifies the type of debugging
9525 mode desired.  Normally these are used only for internal development
9526 or system debugging purposes. You can find full documentation for these
9527 switches in the spec of the @code{Gnatelim} unit in the compiler
9528 source file @file{gnatelim.ads}.
9529 @end table
9530
9531 @noindent
9532 @code{gnatelim} sends its output to the standard output stream, and all the
9533 tracing and debug information is sent to the standard error stream.
9534 In order to produce a proper GNAT configuration file
9535 @file{gnat.adc}, redirection must be used:
9536
9537 @smallexample
9538 @ifset vms
9539 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9540 @end ifset
9541 @ifclear vms
9542 $ gnatelim main_prog.adb > gnat.adc
9543 @end ifclear
9544 @end smallexample
9545
9546 @ifclear vms
9547 @noindent
9548 or
9549
9550 @smallexample
9551 $ gnatelim main_prog.adb >> gnat.adc
9552 @end smallexample
9553
9554 @noindent
9555 in order to append the @code{gnatelim} output to the existing contents of
9556 @file{gnat.adc}.
9557 @end ifclear
9558
9559 @node Correcting the List of Eliminate Pragmas
9560 @subsection Correcting the List of Eliminate Pragmas
9561
9562 @noindent
9563 In some rare cases @code{gnatelim} may try to eliminate
9564 subprograms that are actually called in the program. In this case, the
9565 compiler will generate an error message of the form:
9566
9567 @smallexample
9568 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9569 @end smallexample
9570
9571 @noindent
9572 You will need to manually remove the wrong @code{Eliminate} pragmas from
9573 the @file{gnat.adc} file. You should recompile your program
9574 from scratch after that, because you need a consistent @file{gnat.adc} file
9575 during the entire compilation.
9576
9577
9578 @node Making Your Executables Smaller
9579 @subsection Making Your Executables Smaller
9580
9581 @noindent
9582 In order to get a smaller executable for your program you now have to
9583 recompile the program completely with the new @file{gnat.adc} file
9584 created by @code{gnatelim} in your current directory:
9585
9586 @smallexample
9587 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9588 @end smallexample
9589
9590 @noindent
9591 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9592 recompile everything
9593 with the set of pragmas @code{Eliminate} that you have obtained with
9594 @command{gnatelim}).
9595
9596 Be aware that the set of @code{Eliminate} pragmas is specific to each
9597 program. It is not recommended to merge sets of @code{Eliminate}
9598 pragmas created for different programs in one @file{gnat.adc} file.
9599
9600 @node Summary of the gnatelim Usage Cycle
9601 @subsection Summary of the gnatelim Usage Cycle
9602
9603 @noindent
9604 Here is a quick summary of the steps to be taken in order to reduce
9605 the size of your executables with @code{gnatelim}. You may use
9606 other GNAT options to control the optimization level,
9607 to produce the debugging information, to set search path, etc.
9608
9609 @enumerate
9610 @item
9611 Produce a bind file
9612
9613 @smallexample
9614 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9615 $ gnatbind main_prog
9616 @end smallexample
9617
9618 @item
9619 Generate a list of @code{Eliminate} pragmas
9620 @smallexample
9621 @ifset vms
9622 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9623 @end ifset
9624 @ifclear vms
9625 $ gnatelim main_prog >[>] gnat.adc
9626 @end ifclear
9627 @end smallexample
9628
9629 @item
9630 Recompile the application
9631
9632 @smallexample
9633 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9634 @end smallexample
9635
9636 @end enumerate
9637
9638
9639
9640
9641 @c ********************************
9642 @node Renaming Files Using gnatchop
9643 @chapter Renaming Files Using @code{gnatchop}
9644 @findex gnatchop
9645
9646 @noindent
9647 This chapter discusses how to handle files with multiple units by using
9648 the @code{gnatchop} utility. This utility is also useful in renaming
9649 files to meet the standard GNAT default file naming conventions.
9650
9651 @menu
9652 * Handling Files with Multiple Units::
9653 * Operating gnatchop in Compilation Mode::
9654 * Command Line for gnatchop::
9655 * Switches for gnatchop::
9656 * Examples of gnatchop Usage::
9657 @end menu
9658
9659 @node Handling Files with Multiple Units
9660 @section Handling Files with Multiple Units
9661
9662 @noindent
9663 The basic compilation model of GNAT requires that a file submitted to the
9664 compiler have only one unit and there be a strict correspondence
9665 between the file name and the unit name.
9666
9667 The @code{gnatchop} utility allows both of these rules to be relaxed,
9668 allowing GNAT to process files which contain multiple compilation units
9669 and files with arbitrary file names. @code{gnatchop}
9670 reads the specified file and generates one or more output files,
9671 containing one unit per file. The unit and the file name correspond,
9672 as required by GNAT.
9673
9674 If you want to permanently restructure a set of ``foreign'' files so that
9675 they match the GNAT rules, and do the remaining development using the
9676 GNAT structure, you can simply use @command{gnatchop} once, generate the
9677 new set of files and work with them from that point on.
9678
9679 Alternatively, if you want to keep your files in the ``foreign'' format,
9680 perhaps to maintain compatibility with some other Ada compilation
9681 system, you can set up a procedure where you use @command{gnatchop} each
9682 time you compile, regarding the source files that it writes as temporary
9683 files that you throw away.
9684
9685
9686 @node Operating gnatchop in Compilation Mode
9687 @section Operating gnatchop in Compilation Mode
9688
9689 @noindent
9690 The basic function of @code{gnatchop} is to take a file with multiple units
9691 and split it into separate files. The boundary between files is reasonably
9692 clear, except for the issue of comments and pragmas. In default mode, the
9693 rule is that any pragmas between units belong to the previous unit, except
9694 that configuration pragmas always belong to the following unit. Any comments
9695 belong to the following unit. These rules
9696 almost always result in the right choice of
9697 the split point without needing to mark it explicitly and most users will
9698 find this default to be what they want. In this default mode it is incorrect to
9699 submit a file containing only configuration pragmas, or one that ends in
9700 configuration pragmas, to @code{gnatchop}.
9701
9702 However, using a special option to activate ``compilation mode'',
9703 @code{gnatchop}
9704 can perform another function, which is to provide exactly the semantics
9705 required by the RM for handling of configuration pragmas in a compilation.
9706 In the absence of configuration pragmas (at the main file level), this
9707 option has no effect, but it causes such configuration pragmas to be handled
9708 in a quite different manner.
9709
9710 First, in compilation mode, if @code{gnatchop} is given a file that consists of
9711 only configuration pragmas, then this file is appended to the
9712 @file{gnat.adc} file in the current directory. This behavior provides
9713 the required behavior described in the RM for the actions to be taken
9714 on submitting such a file to the compiler, namely that these pragmas
9715 should apply to all subsequent compilations in the same compilation
9716 environment. Using GNAT, the current directory, possibly containing a
9717 @file{gnat.adc} file is the representation
9718 of a compilation environment. For more information on the
9719 @file{gnat.adc} file, see the section on handling of configuration
9720 pragmas @pxref{Handling of Configuration Pragmas}.
9721
9722 Second, in compilation mode, if @code{gnatchop}
9723 is given a file that starts with
9724 configuration pragmas, and contains one or more units, then these
9725 configuration pragmas are prepended to each of the chopped files. This
9726 behavior provides the required behavior described in the RM for the
9727 actions to be taken on compiling such a file, namely that the pragmas
9728 apply to all units in the compilation, but not to subsequently compiled
9729 units.
9730
9731 Finally, if configuration pragmas appear between units, they are appended
9732 to the previous unit. This results in the previous unit being illegal,
9733 since the compiler does not accept configuration pragmas that follow
9734 a unit. This provides the required RM behavior that forbids configuration
9735 pragmas other than those preceding the first compilation unit of a
9736 compilation.
9737
9738 For most purposes, @code{gnatchop} will be used in default mode. The
9739 compilation mode described above is used only if you need exactly
9740 accurate behavior with respect to compilations, and you have files
9741 that contain multiple units and configuration pragmas. In this
9742 circumstance the use of @code{gnatchop} with the compilation mode
9743 switch provides the required behavior, and is for example the mode
9744 in which GNAT processes the ACVC tests.
9745
9746 @node Command Line for gnatchop
9747 @section Command Line for @code{gnatchop}
9748
9749 @noindent
9750 The @code{gnatchop} command has the form:
9751
9752 @smallexample
9753 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9754       [@var{directory}]
9755 @end smallexample
9756
9757 @noindent
9758 The only required argument is the file name of the file to be chopped.
9759 There are no restrictions on the form of this file name. The file itself
9760 contains one or more Ada units, in normal GNAT format, concatenated
9761 together. As shown, more than one file may be presented to be chopped.
9762
9763 When run in default mode, @code{gnatchop} generates one output file in
9764 the current directory for each unit in each of the files.
9765
9766 @var{directory}, if specified, gives the name of the directory to which
9767 the output files will be written. If it is not specified, all files are
9768 written to the current directory.
9769
9770 For example, given a
9771 file called @file{hellofiles} containing
9772
9773 @smallexample @c ada
9774 @group
9775 @cartouche
9776 procedure hello;
9777
9778 with Text_IO; use Text_IO;
9779 procedure hello is
9780 begin
9781    Put_Line ("Hello");
9782 end hello;
9783 @end cartouche
9784 @end group
9785 @end smallexample
9786
9787 @noindent
9788 the command
9789
9790 @smallexample
9791 $ gnatchop ^hellofiles^HELLOFILES.^
9792 @end smallexample
9793
9794 @noindent
9795 generates two files in the current directory, one called
9796 @file{hello.ads} containing the single line that is the procedure spec,
9797 and the other called @file{hello.adb} containing the remaining text. The
9798 original file is not affected. The generated files can be compiled in
9799 the normal manner.
9800
9801 @noindent
9802 When gnatchop is invoked on a file that is empty or that contains only empty
9803 lines and/or comments, gnatchop will not fail, but will not produce any
9804 new sources.
9805
9806 For example, given a
9807 file called @file{toto.txt} containing
9808
9809 @smallexample @c ada
9810 @group
9811 @cartouche
9812 --  Just a comment
9813 @end cartouche
9814 @end group
9815 @end smallexample
9816
9817 @noindent
9818 the command
9819
9820 @smallexample
9821 $ gnatchop ^toto.txt^TOT.TXT^
9822 @end smallexample
9823
9824 @noindent
9825 will not produce any new file and will result in the following warnings:
9826
9827 @smallexample
9828 toto.txt:1:01: warning: empty file, contains no compilation units
9829 no compilation units found
9830 no source files written
9831 @end smallexample
9832
9833 @node Switches for gnatchop
9834 @section Switches for @code{gnatchop}
9835
9836 @noindent
9837 @command{gnatchop} recognizes the following switches:
9838
9839 @table @option
9840 @c !sort!
9841
9842 @item ^-c^/COMPILATION^
9843 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
9844 Causes @code{gnatchop} to operate in compilation mode, in which
9845 configuration pragmas are handled according to strict RM rules. See
9846 previous section for a full description of this mode.
9847
9848 @ifclear vms
9849 @item -gnatxxx
9850 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
9851 used to parse the given file. Not all @code{xxx} options make sense,
9852 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
9853 process a source file that uses Latin-2 coding for identifiers.
9854 @end ifclear
9855
9856 @item ^-h^/HELP^
9857 Causes @code{gnatchop} to generate a brief help summary to the standard
9858 output file showing usage information.
9859
9860 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
9861 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
9862 Limit generated file names to the specified number @code{mm}
9863 of characters.
9864 This is useful if the
9865 resulting set of files is required to be interoperable with systems
9866 which limit the length of file names.
9867 @ifset vms
9868 If no value is given, or
9869 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
9870 a default of 39, suitable for OpenVMS Alpha
9871 Systems, is assumed
9872 @end ifset
9873 @ifclear vms
9874 No space is allowed between the @option{-k} and the numeric value. The numeric
9875 value may be omitted in which case a default of @option{-k8},
9876 suitable for use
9877 with DOS-like file systems, is used. If no @option{-k} switch
9878 is present then
9879 there is no limit on the length of file names.
9880 @end ifclear
9881
9882 @item ^-p^/PRESERVE^
9883 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
9884 Causes the file ^modification^creation^ time stamp of the input file to be
9885 preserved and used for the time stamp of the output file(s). This may be
9886 useful for preserving coherency of time stamps in an environment where
9887 @code{gnatchop} is used as part of a standard build process.
9888
9889 @item ^-q^/QUIET^
9890 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
9891 Causes output of informational messages indicating the set of generated
9892 files to be suppressed. Warnings and error messages are unaffected.
9893
9894 @item ^-r^/REFERENCE^
9895 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
9896 @findex Source_Reference
9897 Generate @code{Source_Reference} pragmas. Use this switch if the output
9898 files are regarded as temporary and development is to be done in terms
9899 of the original unchopped file. This switch causes
9900 @code{Source_Reference} pragmas to be inserted into each of the
9901 generated files to refers back to the original file name and line number.
9902 The result is that all error messages refer back to the original
9903 unchopped file.
9904 In addition, the debugging information placed into the object file (when
9905 the @option{^-g^/DEBUG^} switch of @code{gcc} or @code{gnatmake} is specified)
9906 also refers back to this original file so that tools like profilers and
9907 debuggers will give information in terms of the original unchopped file.
9908
9909 If the original file to be chopped itself contains
9910 a @code{Source_Reference}
9911 pragma referencing a third file, then gnatchop respects
9912 this pragma, and the generated @code{Source_Reference} pragmas
9913 in the chopped file refer to the original file, with appropriate
9914 line numbers. This is particularly useful when @code{gnatchop}
9915 is used in conjunction with @code{gnatprep} to compile files that
9916 contain preprocessing statements and multiple units.
9917
9918 @item ^-v^/VERBOSE^
9919 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
9920 Causes @code{gnatchop} to operate in verbose mode. The version
9921 number and copyright notice are output, as well as exact copies of
9922 the gnat1 commands spawned to obtain the chop control information.
9923
9924 @item ^-w^/OVERWRITE^
9925 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
9926 Overwrite existing file names. Normally @code{gnatchop} regards it as a
9927 fatal error if there is already a file with the same name as a
9928 file it would otherwise output, in other words if the files to be
9929 chopped contain duplicated units. This switch bypasses this
9930 check, and causes all but the last instance of such duplicated
9931 units to be skipped.
9932
9933 @ifclear vms
9934 @item --GCC=xxxx
9935 @cindex @option{--GCC=} (@code{gnatchop})
9936 Specify the path of the GNAT parser to be used. When this switch is used,
9937 no attempt is made to add the prefix to the GNAT parser executable.
9938 @end ifclear
9939 @end table
9940
9941 @node Examples of gnatchop Usage
9942 @section Examples of @code{gnatchop} Usage
9943
9944 @table @code
9945 @ifset vms
9946 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
9947 @end ifset
9948 @ifclear vms
9949 @item gnatchop -w hello_s.ada prerelease/files
9950 @end ifclear
9951
9952 Chops the source file @file{hello_s.ada}. The output files will be
9953 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
9954 overwriting any
9955 files with matching names in that directory (no files in the current
9956 directory are modified).
9957
9958 @item gnatchop ^archive^ARCHIVE.^
9959 Chops the source file @file{^archive^ARCHIVE.^}
9960 into the current directory. One
9961 useful application of @code{gnatchop} is in sending sets of sources
9962 around, for example in email messages. The required sources are simply
9963 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
9964 command), and then
9965 @code{gnatchop} is used at the other end to reconstitute the original
9966 file names.
9967
9968 @item gnatchop file1 file2 file3 direc
9969 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
9970 the resulting files in the directory @file{direc}. Note that if any units
9971 occur more than once anywhere within this set of files, an error message
9972 is generated, and no files are written. To override this check, use the
9973 @option{^-w^/OVERWRITE^} switch,
9974 in which case the last occurrence in the last file will
9975 be the one that is output, and earlier duplicate occurrences for a given
9976 unit will be skipped.
9977 @end table
9978
9979 @node Configuration Pragmas
9980 @chapter Configuration Pragmas
9981 @cindex Configuration pragmas
9982 @cindex Pragmas, configuration
9983
9984 @noindent
9985 In Ada 95, configuration pragmas include those pragmas described as
9986 such in the Ada 95 Reference Manual, as well as
9987 implementation-dependent pragmas that are configuration pragmas. See the
9988 individual descriptions of pragmas in the GNAT Reference Manual for
9989 details on these additional GNAT-specific configuration pragmas. Most
9990 notably, the pragma @code{Source_File_Name}, which allows
9991 specifying non-default names for source files, is a configuration
9992 pragma. The following is a complete list of configuration pragmas
9993 recognized by @code{GNAT}:
9994
9995 @smallexample
9996    Ada_83
9997    Ada_95
9998    C_Pass_By_Copy
9999    Component_Alignment
10000    Discard_Names
10001    Elaboration_Checks
10002    Eliminate
10003    Extend_System
10004    Extensions_Allowed
10005    External_Name_Casing
10006    Float_Representation
10007    Initialize_Scalars
10008    License
10009    Locking_Policy
10010    Long_Float
10011    Normalize_Scalars
10012    Polling
10013    Profile
10014    Profile_Warnings
10015    Propagate_Exceptions
10016    Queuing_Policy
10017    Ravenscar
10018    Restricted_Run_Time
10019    Restrictions
10020    Restrictions_Warnings
10021    Reviewable
10022    Source_File_Name
10023    Style_Checks
10024    Suppress
10025    Task_Dispatching_Policy
10026    Universal_Data
10027    Unsuppress
10028    Use_VADS_Size
10029    Warnings
10030    Validity_Checks
10031 @end smallexample
10032
10033 @menu
10034 * Handling of Configuration Pragmas::
10035 * The Configuration Pragmas Files::
10036 @end menu
10037
10038 @node Handling of Configuration Pragmas
10039 @section Handling of Configuration Pragmas
10040
10041 Configuration pragmas may either appear at the start of a compilation
10042 unit, in which case they apply only to that unit, or they may apply to
10043 all compilations performed in a given compilation environment.
10044
10045 GNAT also provides the @code{gnatchop} utility to provide an automatic
10046 way to handle configuration pragmas following the semantics for
10047 compilations (that is, files with multiple units), described in the RM.
10048 See section @pxref{Operating gnatchop in Compilation Mode} for details.
10049 However, for most purposes, it will be more convenient to edit the
10050 @file{gnat.adc} file that contains configuration pragmas directly,
10051 as described in the following section.
10052
10053 @node The Configuration Pragmas Files
10054 @section The Configuration Pragmas Files
10055 @cindex @file{gnat.adc}
10056
10057 @noindent
10058 In GNAT a compilation environment is defined by the current
10059 directory at the time that a compile command is given. This current
10060 directory is searched for a file whose name is @file{gnat.adc}. If
10061 this file is present, it is expected to contain one or more
10062 configuration pragmas that will be applied to the current compilation.
10063 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10064 considered.
10065
10066 Configuration pragmas may be entered into the @file{gnat.adc} file
10067 either by running @code{gnatchop} on a source file that consists only of
10068 configuration pragmas, or more conveniently  by
10069 direct editing of the @file{gnat.adc} file, which is a standard format
10070 source file.
10071
10072 In addition to @file{gnat.adc}, one additional file containing configuration
10073 pragmas may be applied to the current compilation using the switch
10074 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10075 contains only configuration pragmas. These configuration pragmas are
10076 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10077 is present and switch @option{-gnatA} is not used).
10078
10079 It is allowed to specify several switches @option{-gnatec}, however only
10080 the last one on the command line will be taken into account.
10081
10082 If you are using project file, a separate mechanism is provided using
10083 project attributes, see @ref{Specifying Configuration Pragmas} for more
10084 details.
10085
10086 @ifset vms
10087 Of special interest to GNAT OpenVMS Alpha is the following
10088 configuration pragma:
10089
10090 @smallexample @c ada
10091 @cartouche
10092 pragma Extend_System (Aux_DEC);
10093 @end cartouche
10094 @end smallexample
10095
10096 @noindent
10097 In the presence of this pragma, GNAT adds to the definition of the
10098 predefined package SYSTEM all the additional types and subprograms that are
10099 defined in DEC Ada. See @pxref{Compatibility with DEC Ada} for details.
10100 @end ifset
10101
10102 @node Handling Arbitrary File Naming Conventions Using gnatname
10103 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10104 @cindex Arbitrary File Naming Conventions
10105
10106 @menu
10107 * Arbitrary File Naming Conventions::
10108 * Running gnatname::
10109 * Switches for gnatname::
10110 * Examples of gnatname Usage::
10111 @end menu
10112
10113 @node Arbitrary File Naming Conventions
10114 @section Arbitrary File Naming Conventions
10115
10116 @noindent
10117 The GNAT compiler must be able to know the source file name of a compilation
10118 unit.  When using the standard GNAT default file naming conventions
10119 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10120 does not need additional information.
10121
10122 @noindent
10123 When the source file names do not follow the standard GNAT default file naming
10124 conventions, the GNAT compiler must be given additional information through
10125 a configuration pragmas file (see @ref{Configuration Pragmas})
10126 or a project file.
10127 When the non standard file naming conventions are well-defined,
10128 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10129 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
10130 if the file naming conventions are irregular or arbitrary, a number
10131 of pragma @code{Source_File_Name} for individual compilation units
10132 must be defined.
10133 To help maintain the correspondence between compilation unit names and
10134 source file names within the compiler,
10135 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10136 set of files.
10137
10138 @node Running gnatname
10139 @section Running @code{gnatname}
10140
10141 @noindent
10142 The usual form of the @code{gnatname} command is
10143
10144 @smallexample
10145 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10146 @end smallexample
10147
10148 @noindent
10149 All of the arguments are optional. If invoked without any argument,
10150 @code{gnatname} will display its usage.
10151
10152 @noindent
10153 When used with at least one naming pattern, @code{gnatname} will attempt to
10154 find all the compilation units in files that follow at least one of the
10155 naming patterns. To find these compilation units,
10156 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10157 regular files.
10158
10159 @noindent
10160 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10161 Each Naming Pattern is enclosed between double quotes.
10162 A Naming Pattern is a regular expression similar to the wildcard patterns
10163 used in file names by the Unix shells or the DOS prompt.
10164
10165 @noindent
10166 Examples of Naming Patterns are
10167
10168 @smallexample
10169    "*.[12].ada"
10170    "*.ad[sb]*"
10171    "body_*"    "spec_*"
10172 @end smallexample
10173
10174 @noindent
10175 For a more complete description of the syntax of Naming Patterns,
10176 see the second kind of regular expressions described in @file{g-regexp.ads}
10177 (the ``Glob'' regular expressions).
10178
10179 @noindent
10180 When invoked with no switches, @code{gnatname} will create a configuration
10181 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10182 @code{Source_File_Name} for each file that contains a valid Ada unit.
10183
10184 @node Switches for gnatname
10185 @section Switches for @code{gnatname}
10186
10187 @noindent
10188 Switches for @code{gnatname} must precede any specified Naming Pattern.
10189
10190 @noindent
10191 You may specify any of the following switches to @code{gnatname}:
10192
10193 @table @option
10194 @c !sort!
10195
10196 @item ^-c^/CONFIG_FILE=^@file{file}
10197 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10198 Create a configuration pragmas file @file{file} (instead of the default
10199 @file{gnat.adc}).
10200 @ifclear vms
10201 There may be zero, one or more space between @option{-c} and
10202 @file{file}.
10203 @end ifclear
10204 @file{file} may include directory information. @file{file} must be
10205 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10206 When a switch @option{^-c^/CONFIG_FILE^} is
10207 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10208
10209 @item ^-d^/SOURCE_DIRS=^@file{dir}
10210 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10211 Look for source files in directory @file{dir}. There may be zero, one or more
10212 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10213 When a switch @option{^-d^/SOURCE_DIRS^}
10214 is specified, the current working directory will not be searched for source
10215 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10216 or @option{^-D^/DIR_FILES^} switch.
10217 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10218 If @file{dir} is a relative path, it is relative to the directory of
10219 the configuration pragmas file specified with switch
10220 @option{^-c^/CONFIG_FILE^},
10221 or to the directory of the project file specified with switch
10222 @option{^-P^/PROJECT_FILE^} or,
10223 if neither switch @option{^-c^/CONFIG_FILE^}
10224 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10225 current working directory. The directory
10226 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10227
10228 @item ^-D^/DIRS_FILE=^@file{file}
10229 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10230 Look for source files in all directories listed in text file @file{file}.
10231 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10232 and @file{file}.
10233 @file{file} must be an existing, readable text file.
10234 Each non empty line in @file{file} must be a directory.
10235 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10236 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10237 @file{file}.
10238
10239 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10240 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10241 Foreign patterns. Using this switch, it is possible to add sources of languages
10242 other than Ada to the list of sources of a project file.
10243 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10244 For example,
10245 @smallexample
10246 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10247 @end smallexample
10248 @noindent
10249 will look for Ada units in all files with the @file{.ada} extension,
10250 and will add to the list of file for project @file{prj.gpr} the C files
10251 with extension ".^c^C^".
10252
10253 @item ^-h^/HELP^
10254 @cindex @option{^-h^/HELP^} (@code{gnatname})
10255 Output usage (help) information. The output is written to @file{stdout}.
10256
10257 @item ^-P^/PROJECT_FILE=^@file{proj}
10258 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10259 Create or update project file @file{proj}. There may be zero, one or more space
10260 between @option{-P} and @file{proj}. @file{proj} may include directory
10261 information. @file{proj} must be writable.
10262 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10263 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10264 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10265
10266 @item ^-v^/VERBOSE^
10267 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10268 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10269 This includes name of the file written, the name of the directories to search
10270 and, for each file in those directories whose name matches at least one of
10271 the Naming Patterns, an indication of whether the file contains a unit,
10272 and if so the name of the unit.
10273
10274 @item ^-v -v^/VERBOSE /VERBOSE^
10275 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10276 Very Verbose mode. In addition to the output produced in verbose mode,
10277 for each file in the searched directories whose name matches none of
10278 the Naming Patterns, an indication is given that there is no match.
10279
10280 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10281 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10282 Excluded patterns. Using this switch, it is possible to exclude some files
10283 that would match the name patterns. For example,
10284 @smallexample
10285 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10286 @end smallexample
10287 @noindent
10288 will look for Ada units in all files with the @file{.ada} extension,
10289 except those whose names end with @file{_nt.ada}.
10290
10291 @end table
10292
10293 @node Examples of gnatname Usage
10294 @section Examples of @code{gnatname} Usage
10295
10296 @ifset vms
10297 @smallexample
10298 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10299 @end smallexample
10300 @end ifset
10301
10302 @ifclear vms
10303 @smallexample
10304 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10305 @end smallexample
10306 @end ifclear
10307
10308 @noindent
10309 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10310 and be writable. In addition, the directory
10311 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10312 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10313
10314 @ifclear vms
10315 Note the optional spaces after @option{-c} and @option{-d}.
10316 @end ifclear
10317
10318 @smallexample
10319 @ifclear vms
10320 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10321   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10322 @end ifclear
10323 @ifset vms
10324 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
10325   /EXCLUDED_PATTERN=*_nt_body.ada
10326   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10327   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10328 @end ifset
10329 @end smallexample
10330
10331 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10332 even in conjunction with one or several switches
10333 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10334 are used in this example.
10335
10336
10337 @c *****************************************
10338 @c * G N A T  P r o j e c t  M a n a g e r *
10339 @c *****************************************
10340 @node GNAT Project Manager
10341 @chapter GNAT Project Manager
10342
10343 @menu
10344 * Introduction::
10345 * Examples of Project Files::
10346 * Project File Syntax::
10347 * Objects and Sources in Project Files::
10348 * Importing Projects::
10349 * Project Extension::
10350 * External References in Project Files::
10351 * Packages in Project Files::
10352 * Variables from Imported Projects::
10353 * Naming Schemes::
10354 * Library Projects::
10355 * Using Third-Party Libraries through Projects::
10356 * Stand-alone Library Projects::
10357 * Switches Related to Project Files::
10358 * Tools Supporting Project Files::
10359 * An Extended Example::
10360 * Project File Complete Syntax::
10361 @end menu
10362
10363 @c ****************
10364 @c * Introduction *
10365 @c ****************
10366
10367 @node Introduction
10368 @section Introduction
10369
10370 @noindent
10371 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10372 you to manage complex builds involving a number of source files, directories,
10373 and compilation options for different system configurations. In particular,
10374 project files allow you to specify:
10375 @itemize @bullet
10376 @item
10377 The directory or set of directories containing the source files, and/or the
10378 names of the specific source files themselves
10379 @item
10380 The directory in which the compiler's output
10381 (@file{ALI} files, object files, tree files) is to be placed
10382 @item
10383 The directory in which the executable programs is to be placed
10384 @item
10385 ^Switch^Switch^ settings for any of the project-enabled tools
10386 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10387 @code{gnatfind}); you can apply these settings either globally or to individual
10388 compilation units.
10389 @item
10390 The source files containing the main subprogram(s) to be built
10391 @item
10392 The source programming language(s) (currently Ada and/or C)
10393 @item
10394 Source file naming conventions; you can specify these either globally or for
10395 individual compilation units
10396 @end itemize
10397
10398 @menu
10399 * Project Files::
10400 @end menu
10401
10402 @node Project Files
10403 @subsection Project Files
10404
10405 @noindent
10406 Project files are written in a syntax close to that of Ada, using  familiar
10407 notions such as packages, context clauses, declarations, default values,
10408 assignments, and inheritance. Finally, project files can be built
10409 hierarchically from other project files, simplifying complex system
10410 integration and project reuse.
10411
10412 A @dfn{project} is a specific set of values for various compilation properties.
10413 The settings for a given project are described by means of
10414 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10415 Property values in project files are either strings or lists of strings.
10416 Properties that are not explicitly set receive default values.  A project
10417 file may interrogate the values of @dfn{external variables} (user-defined
10418 command-line switches or environment variables), and it may specify property
10419 settings conditionally, based on the value of such variables.
10420
10421 In simple cases, a project's source files depend only on other source files
10422 in the same project, or on the predefined libraries.  (@emph{Dependence} is
10423 used in
10424 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10425 the Project Manager also allows more sophisticated arrangements,
10426 where the source files in one project depend on source files in other
10427 projects:
10428 @itemize @bullet
10429 @item
10430 One project can @emph{import} other projects containing needed source files.
10431 @item
10432 You can organize GNAT projects in a hierarchy: a @emph{child} project
10433 can extend a @emph{parent} project, inheriting the parent's source files and
10434 optionally overriding any of them with alternative versions
10435 @end itemize
10436
10437 @noindent
10438 More generally, the Project Manager lets you structure large development
10439 efforts into hierarchical subsystems, where build decisions are delegated
10440 to the subsystem level, and thus different compilation environments
10441 (^switch^switch^ settings) used for different subsystems.
10442
10443 The Project Manager is invoked through the
10444 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10445 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10446 @ifclear vms
10447 There may be zero, one or more spaces between @option{-P} and
10448 @option{@emph{projectfile}}.
10449 @end ifclear
10450 If you want to define (on the command line) an external variable that is
10451 queried by the project file, you must use the
10452 @option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10453 The Project Manager parses and interprets the project file, and drives the
10454 invoked tool based on the project settings.
10455
10456 The Project Manager supports a wide range of development strategies,
10457 for systems of all sizes.  Here are some typical practices that are
10458 easily handled:
10459 @itemize @bullet
10460 @item
10461 Using a common set of source files, but generating object files in different
10462 directories via different ^switch^switch^ settings
10463 @item
10464 Using a mostly-shared set of source files, but with different versions of
10465 some unit or units
10466 @end itemize
10467
10468 @noindent
10469 The destination of an executable can be controlled inside a project file
10470 using the @option{^-o^-o^}
10471 ^switch^switch^.
10472 In the absence of such a ^switch^switch^ either inside
10473 the project file or on the command line, any executable files generated by
10474 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10475 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10476 in the object directory of the project.
10477
10478 You can use project files to achieve some of the effects of a source
10479 versioning system (for example, defining separate projects for
10480 the different sets of sources that comprise different releases) but the
10481 Project Manager is independent of any source configuration management tools
10482 that might be used by the developers.
10483
10484 The next section introduces the main features of GNAT's project facility
10485 through a sequence of examples; subsequent sections will present the syntax
10486 and semantics in more detail. A more formal description of the project
10487 facility appears in the GNAT Reference Manual.
10488
10489 @c *****************************
10490 @c * Examples of Project Files *
10491 @c *****************************
10492
10493 @node Examples of Project Files
10494 @section Examples of Project Files
10495 @noindent
10496 This section illustrates some of the typical uses of project files and
10497 explains their basic structure and behavior.
10498
10499 @menu
10500 * Common Sources with Different ^Switches^Switches^ and Directories::
10501 * Using External Variables::
10502 * Importing Other Projects::
10503 * Extending a Project::
10504 @end menu
10505
10506 @node Common Sources with Different ^Switches^Switches^ and Directories
10507 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10508
10509 @menu
10510 * Source Files::
10511 * Specifying the Object Directory::
10512 * Specifying the Exec Directory::
10513 * Project File Packages::
10514 * Specifying ^Switch^Switch^ Settings::
10515 * Main Subprograms::
10516 * Executable File Names::
10517 * Source File Naming Conventions::
10518 * Source Language(s)::
10519 @end menu
10520
10521 @noindent
10522 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10523 @file{proc.adb} are in the @file{/common} directory.  The file
10524 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10525 package @code{Pack}.  We want to compile these source files under two sets
10526 of ^switches^switches^:
10527 @itemize @bullet
10528 @item
10529 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10530 and the @option{^-gnata^-gnata^},
10531 @option{^-gnato^-gnato^},
10532 and @option{^-gnatE^-gnatE^} switches to the
10533 compiler; the compiler's output is to appear in @file{/common/debug}
10534 @item
10535 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10536 to the compiler; the compiler's output is to appear in @file{/common/release}
10537 @end itemize
10538
10539 @noindent
10540 The GNAT project files shown below, respectively @file{debug.gpr} and
10541 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10542
10543 Schematically:
10544 @smallexample
10545 @group
10546 ^/common^[COMMON]^
10547   debug.gpr
10548   release.gpr
10549   pack.ads
10550   pack.adb
10551   proc.adb
10552 @end group
10553 @group
10554 ^/common/debug^[COMMON.DEBUG]^
10555   proc.ali, proc.o
10556   pack.ali, pack.o
10557 @end group
10558 @group
10559 ^/common/release^[COMMON.RELEASE]^
10560   proc.ali, proc.o
10561   pack.ali, pack.o
10562 @end group
10563 @end smallexample
10564 Here are the corresponding project files:
10565
10566 @smallexample @c projectfile
10567 @group
10568 project Debug is
10569   for Object_Dir use "debug";
10570   for Main use ("proc");
10571
10572   package Builder is
10573     for ^Default_Switches^Default_Switches^ ("Ada")
10574         use ("^-g^-g^");
10575     for Executable ("proc.adb") use "proc1";
10576   end Builder;
10577 @end group
10578
10579 @group
10580   package Compiler is
10581     for ^Default_Switches^Default_Switches^ ("Ada")
10582        use ("-fstack-check",
10583             "^-gnata^-gnata^",
10584             "^-gnato^-gnato^",
10585             "^-gnatE^-gnatE^");
10586   end Compiler;
10587 end Debug;
10588 @end group
10589 @end smallexample
10590
10591 @smallexample @c projectfile
10592 @group
10593 project Release is
10594   for Object_Dir use "release";
10595   for Exec_Dir use ".";
10596   for Main use ("proc");
10597
10598   package Compiler is
10599     for ^Default_Switches^Default_Switches^ ("Ada")
10600         use ("^-O2^-O2^");
10601   end Compiler;
10602 end Release;
10603 @end group
10604 @end smallexample
10605
10606 @noindent
10607 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10608 insensitive), and analogously the project defined by @file{release.gpr} is
10609 @code{"Release"}.  For consistency the file should have the same name as the
10610 project, and the project file's extension should be @code{"gpr"}. These
10611 conventions are not required, but a warning is issued if they are not followed.
10612
10613 If the current directory is @file{^/temp^[TEMP]^}, then the command
10614 @smallexample
10615 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10616 @end smallexample
10617
10618 @noindent
10619 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10620 as well as the @code{^proc1^PROC1.EXE^} executable,
10621 using the ^switch^switch^ settings defined in the project file.
10622
10623 Likewise, the command
10624 @smallexample
10625 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10626 @end smallexample
10627
10628 @noindent
10629 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10630 and the @code{^proc^PROC.EXE^}
10631 executable in @file{^/common^[COMMON]^},
10632 using the ^switch^switch^ settings from the project file.
10633
10634 @node Source Files
10635 @unnumberedsubsubsec Source Files
10636
10637 @noindent
10638 If a project file does not explicitly specify a set of source directories or
10639 a set of source files, then by default the project's source files are the
10640 Ada source files in the project file directory.  Thus @file{pack.ads},
10641 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10642
10643 @node Specifying the Object Directory
10644 @unnumberedsubsubsec Specifying the Object Directory
10645
10646 @noindent
10647 Several project properties are modeled by Ada-style @emph{attributes};
10648 a property is defined by supplying the equivalent of an Ada attribute
10649 definition clause in the project file.
10650 A project's object directory is another such a property; the corresponding
10651 attribute is @code{Object_Dir}, and its value is also a string expression,
10652 specified either as absolute or relative. In the later case,
10653 it is relative to the project file directory. Thus the compiler's
10654 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10655 (for the @code{Debug} project)
10656 and to @file{^/common/release^[COMMON.RELEASE]^}
10657 (for the @code{Release} project).
10658 If @code{Object_Dir} is not specified, then the default is the project file
10659 directory itself.
10660
10661 @node Specifying the Exec Directory
10662 @unnumberedsubsubsec Specifying the Exec Directory
10663
10664 @noindent
10665 A project's exec directory is another property; the corresponding
10666 attribute is @code{Exec_Dir}, and its value is also a string expression,
10667 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10668 then the default is the object directory (which may also be the project file
10669 directory if attribute @code{Object_Dir} is not specified). Thus the executable
10670 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10671 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10672 and in @file{^/common^[COMMON]^} for the @code{Release} project.
10673
10674 @node Project File Packages
10675 @unnumberedsubsubsec Project File Packages
10676
10677 @noindent
10678 A GNAT tool that is integrated with the Project Manager is modeled by a
10679 corresponding package in the project file. In the example above,
10680 The @code{Debug} project defines the packages @code{Builder}
10681 (for @command{gnatmake}) and @code{Compiler};
10682 the @code{Release} project defines only the @code{Compiler} package.
10683
10684 The Ada-like package syntax is not to be taken literally.  Although packages in
10685 project files bear a surface resemblance to packages in Ada source code, the
10686 notation is simply a way to convey a grouping of properties for a named
10687 entity.  Indeed, the package names permitted in project files are restricted
10688 to a predefined set, corresponding to the project-aware tools, and the contents
10689 of packages are limited to a small set of constructs.
10690 The packages in the example above contain attribute definitions.
10691
10692 @node Specifying ^Switch^Switch^ Settings
10693 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10694
10695 @noindent
10696 ^Switch^Switch^ settings for a project-aware tool can be specified through
10697 attributes in the package that corresponds to the tool.
10698 The example above illustrates one of the relevant attributes,
10699 @code{^Default_Switches^Default_Switches^}, which is defined in packages
10700 in both project files.
10701 Unlike simple attributes like @code{Source_Dirs},
10702 @code{^Default_Switches^Default_Switches^} is
10703 known as an @emph{associative array}.  When you define this attribute, you must
10704 supply an ``index'' (a literal string), and the effect of the attribute
10705 definition is to set the value of the array at the specified index.
10706 For the @code{^Default_Switches^Default_Switches^} attribute,
10707 the index is a programming language (in our case, Ada),
10708 and the value specified (after @code{use}) must be a list
10709 of string expressions.
10710
10711 The attributes permitted in project files are restricted to a predefined set.
10712 Some may appear at project level, others in packages.
10713 For any attribute that is an associative array, the index must always be a
10714 literal string, but the restrictions on this string (e.g., a file name or a
10715 language name) depend on the individual attribute.
10716 Also depending on the attribute, its specified value will need to be either a
10717 string or a string list.
10718
10719 In the @code{Debug} project, we set the switches for two tools,
10720 @command{gnatmake} and the compiler, and thus we include the two corresponding
10721 packages; each package defines the @code{^Default_Switches^Default_Switches^}
10722 attribute with index @code{"Ada"}.
10723 Note that the package corresponding to
10724 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
10725 similar, but only includes the @code{Compiler} package.
10726
10727 In project @code{Debug} above, the ^switches^switches^ starting with
10728 @option{-gnat} that are specified in package @code{Compiler}
10729 could have been placed in package @code{Builder}, since @command{gnatmake}
10730 transmits all such ^switches^switches^ to the compiler.
10731
10732 @node Main Subprograms
10733 @unnumberedsubsubsec Main Subprograms
10734
10735 @noindent
10736 One of the specifiable properties of a project is a list of files that contain
10737 main subprograms.  This property is captured in the @code{Main} attribute,
10738 whose value is a list of strings.  If a project defines the @code{Main}
10739 attribute, it is not necessary to identify the main subprogram(s) when
10740 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
10741
10742 @node Executable File Names
10743 @unnumberedsubsubsec Executable File Names
10744
10745 @noindent
10746 By default, the executable file name corresponding to a main source is
10747 deducted from the main source file name. Through the attributes
10748 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10749 it is possible to change this default.
10750 In project @code{Debug} above, the executable file name
10751 for main source @file{^proc.adb^PROC.ADB^} is
10752 @file{^proc1^PROC1.EXE^}.
10753 Attribute @code{Executable_Suffix}, when specified, may change the suffix
10754 of the the executable files, when no attribute @code{Executable} applies:
10755 its value replace the platform-specific executable suffix.
10756 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10757 specify a non default executable file name when several mains are built at once
10758 in a single @command{gnatmake} command.
10759
10760 @node Source File Naming Conventions
10761 @unnumberedsubsubsec Source File Naming Conventions
10762
10763 @noindent
10764 Since the project files above do not specify any source file naming
10765 conventions, the GNAT defaults are used.  The mechanism for defining source
10766 file naming conventions -- a package named @code{Naming} --
10767 is described below (@pxref{Naming Schemes}).
10768
10769 @node Source Language(s)
10770 @unnumberedsubsubsec Source Language(s)
10771
10772 @noindent
10773 Since the project files do not specify a @code{Languages} attribute, by
10774 default the GNAT tools assume that the language of the project file is Ada.
10775 More generally, a project can comprise source files
10776 in Ada, C, and/or other languages.
10777
10778 @node Using External Variables
10779 @subsection Using External Variables
10780
10781 @noindent
10782 Instead of supplying different project files for debug and release, we can
10783 define a single project file that queries an external variable (set either
10784 on the command line or via an ^environment variable^logical name^) in order to
10785 conditionally define the appropriate settings.  Again, assume that the
10786 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
10787 located in directory @file{^/common^[COMMON]^}.  The following project file,
10788 @file{build.gpr}, queries the external variable named @code{STYLE} and
10789 defines an object directory and ^switch^switch^ settings based on whether
10790 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
10791 the default is @code{"deb"}.
10792
10793 @smallexample @c projectfile
10794 @group
10795 project Build is
10796   for Main use ("proc");
10797
10798   type Style_Type is ("deb", "rel");
10799   Style : Style_Type := external ("STYLE", "deb");
10800
10801   case Style is
10802     when "deb" =>
10803       for Object_Dir use "debug";
10804
10805     when "rel" =>
10806       for Object_Dir use "release";
10807       for Exec_Dir use ".";
10808   end case;
10809 @end group
10810
10811 @group
10812   package Builder is
10813
10814     case Style is
10815       when "deb" =>
10816         for ^Default_Switches^Default_Switches^ ("Ada")
10817             use ("^-g^-g^");
10818         for Executable ("proc") use "proc1";
10819       when others =>
10820         null;
10821     end case;
10822
10823   end Builder;
10824 @end group
10825
10826 @group
10827   package Compiler is
10828
10829     case Style is
10830       when "deb" =>
10831         for ^Default_Switches^Default_Switches^ ("Ada")
10832             use ("^-gnata^-gnata^",
10833                  "^-gnato^-gnato^",
10834                  "^-gnatE^-gnatE^");
10835
10836       when "rel" =>
10837         for ^Default_Switches^Default_Switches^ ("Ada")
10838             use ("^-O2^-O2^");
10839     end case;
10840
10841   end Compiler;
10842
10843 end Build;
10844 @end group
10845 @end smallexample
10846
10847 @noindent
10848 @code{Style_Type} is an example of a @emph{string type}, which is the project
10849 file analog of an Ada enumeration type but whose components are string literals
10850 rather than identifiers.  @code{Style} is declared as a variable of this type.
10851
10852 The form @code{external("STYLE", "deb")} is known as an
10853 @emph{external reference}; its first argument is the name of an
10854 @emph{external variable}, and the second argument is a default value to be
10855 used if the external variable doesn't exist.  You can define an external
10856 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
10857 or you can use ^an environment variable^a logical name^
10858 as an external variable.
10859
10860 Each @code{case} construct is expanded by the Project Manager based on the
10861 value of @code{Style}. Thus the command
10862 @ifclear vms
10863 @smallexample
10864 gnatmake -P/common/build.gpr -XSTYLE=deb
10865 @end smallexample
10866 @end ifclear
10867
10868 @ifset vms
10869 @smallexample
10870 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
10871 @end smallexample
10872 @end ifset
10873
10874 @noindent
10875 is equivalent to the @command{gnatmake} invocation using the project file
10876 @file{debug.gpr} in the earlier example.  So is the command
10877 @smallexample
10878 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
10879 @end smallexample
10880
10881 @noindent
10882 since @code{"deb"} is the default for @code{STYLE}.
10883
10884 Analogously,
10885
10886 @ifclear vms
10887 @smallexample
10888 gnatmake -P/common/build.gpr -XSTYLE=rel
10889 @end smallexample
10890 @end ifclear
10891
10892 @ifset vms
10893 @smallexample
10894 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
10895 @end smallexample
10896 @end ifset
10897
10898 @noindent
10899 is equivalent to the @command{gnatmake} invocation using the project file
10900 @file{release.gpr} in the earlier example.
10901
10902 @node Importing Other Projects
10903 @subsection Importing Other Projects
10904
10905 @noindent
10906 A compilation unit in a source file in one project may depend on compilation
10907 units in source files in other projects.  To compile this unit under
10908 control of a project file, the
10909 dependent project must @emph{import} the projects containing the needed source
10910 files.
10911 This effect is obtained using syntax similar to an Ada @code{with} clause,
10912 but where @code{with}ed entities are strings that denote project files.
10913
10914 As an example, suppose that the two projects @code{GUI_Proj} and
10915 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
10916 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
10917 and @file{^/comm^[COMM]^}, respectively.
10918 Suppose that the source files for @code{GUI_Proj} are
10919 @file{gui.ads} and @file{gui.adb}, and that the source files for
10920 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
10921 files is located in its respective project file directory.  Schematically:
10922
10923 @smallexample
10924 @group
10925 ^/gui^[GUI]^
10926   gui_proj.gpr
10927   gui.ads
10928   gui.adb
10929 @end group
10930
10931 @group
10932 ^/comm^[COMM]^
10933   comm_proj.gpr
10934   comm.ads
10935   comm.adb
10936 @end group
10937 @end smallexample
10938
10939 @noindent
10940 We want to develop an application in directory @file{^/app^[APP]^} that
10941 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
10942 the corresponding project files (e.g. the ^switch^switch^ settings
10943 and object directory).
10944 Skeletal code for a main procedure might be something like the following:
10945
10946 @smallexample @c ada
10947 @group
10948 with GUI, Comm;
10949 procedure App_Main is
10950    ...
10951 begin
10952    ...
10953 end App_Main;
10954 @end group
10955 @end smallexample
10956
10957 @noindent
10958 Here is a project file, @file{app_proj.gpr}, that achieves the desired
10959 effect:
10960
10961 @smallexample @c projectfile
10962 @group
10963 with "/gui/gui_proj", "/comm/comm_proj";
10964 project App_Proj is
10965    for Main use ("app_main");
10966 end App_Proj;
10967 @end group
10968 @end smallexample
10969
10970 @noindent
10971 Building an executable is achieved through the command:
10972 @smallexample
10973 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
10974 @end smallexample
10975 @noindent
10976 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
10977 in the directory where @file{app_proj.gpr} resides.
10978
10979 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
10980 (as illustrated above) the @code{with} clause can omit the extension.
10981
10982 Our example specified an absolute path for each imported project file.
10983 Alternatively, the directory name of an imported object can be omitted
10984 if either
10985 @itemize @bullet
10986 @item
10987 The imported project file is in the same directory as the importing project
10988 file, or
10989 @item
10990 You have defined ^an environment variable^a logical name^
10991 that includes the directory containing
10992 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
10993 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
10994 directory names separated by colons (semicolons on Windows).
10995 @end itemize
10996
10997 @noindent
10998 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
10999 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
11000 as follows:
11001
11002 @smallexample @c projectfile
11003 @group
11004 with "gui_proj", "comm_proj";
11005 project App_Proj is
11006    for Main use ("app_main");
11007 end App_Proj;
11008 @end group
11009 @end smallexample
11010
11011 @noindent
11012 Importing other projects can create ambiguities.
11013 For example, the same unit might be present in different imported projects, or
11014 it might be present in both the importing project and in an imported project.
11015 Both of these conditions are errors.  Note that in the current version of
11016 the Project Manager, it is illegal to have an ambiguous unit even if the
11017 unit is never referenced by the importing project.  This restriction may be
11018 relaxed in a future release.
11019
11020 @node Extending a Project
11021 @subsection Extending a Project
11022
11023 @noindent
11024 In large software systems it is common to have multiple
11025 implementations of a common interface; in Ada terms, multiple versions of a
11026 package body for the same specification.  For example, one implementation
11027 might be safe for use in tasking programs, while another might only be used
11028 in sequential applications.  This can be modeled in GNAT using the concept
11029 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
11030 another project (the ``parent'') then by default all source files of the
11031 parent project are inherited by the child, but the child project can
11032 override any of the parent's source files with new versions, and can also
11033 add new files.  This facility is the project analog of a type extension in
11034 Object-Oriented Programming.  Project hierarchies are permitted (a child
11035 project may be the parent of yet another project), and a project that
11036 inherits one project can also import other projects.
11037
11038 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11039 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11040 @file{pack.adb}, and @file{proc.adb}:
11041
11042 @smallexample
11043 @group
11044 ^/seq^[SEQ]^
11045   pack.ads
11046   pack.adb
11047   proc.adb
11048   seq_proj.gpr
11049 @end group
11050 @end smallexample
11051
11052 @noindent
11053 Note that the project file can simply be empty (that is, no attribute or
11054 package is defined):
11055
11056 @smallexample @c projectfile
11057 @group
11058 project Seq_Proj is
11059 end Seq_Proj;
11060 @end group
11061 @end smallexample
11062
11063 @noindent
11064 implying that its source files are all the Ada source files in the project
11065 directory.
11066
11067 Suppose we want to supply an alternate version of @file{pack.adb}, in
11068 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11069 @file{pack.ads} and @file{proc.adb}.  We can define a project
11070 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11071
11072 @smallexample
11073 @group
11074 ^/tasking^[TASKING]^
11075   pack.adb
11076   tasking_proj.gpr
11077 @end group
11078
11079 @group
11080 project Tasking_Proj extends "/seq/seq_proj" is
11081 end Tasking_Proj;
11082 @end group
11083 @end smallexample
11084
11085 @noindent
11086 The version of @file{pack.adb} used in a build depends on which project file
11087 is specified.
11088
11089 Note that we could have obtained the desired behavior using project import
11090 rather than project inheritance; a @code{base} project would contain the
11091 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11092 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11093 would import @code{base} and add a different version of @file{pack.adb}.  The
11094 choice depends on whether other sources in the original project need to be
11095 overridden.  If they do, then project extension is necessary, otherwise,
11096 importing is sufficient.
11097
11098 @noindent
11099 In a project file that extends another project file, it is possible to
11100 indicate that an inherited source is not part of the sources of the extending
11101 project. This is necessary sometimes when a package spec has been overloaded
11102 and no longer requires a body: in this case, it is necessary to indicate that
11103 the inherited body is not part of the sources of the project, otherwise there
11104 will be a compilation error when compiling the spec.
11105
11106 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11107 Its value is a string list: a list of file names.
11108
11109 @smallexample @c @projectfile
11110 project B extends "a" is
11111    for Source_Files use ("pkg.ads");
11112    --  New spec of Pkg does not need a completion
11113    for Locally_Removed_Files use ("pkg.adb");
11114 end B;
11115 @end smallexample
11116
11117 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11118 is still needed: if it is possible to build using @code{gnatmake} when such
11119 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11120 it is possible to remove the source completely from a system that includes
11121 project P.
11122
11123 @c ***********************
11124 @c * Project File Syntax *
11125 @c ***********************
11126
11127 @node Project File Syntax
11128 @section Project File Syntax
11129
11130 @menu
11131 * Basic Syntax::
11132 * Packages::
11133 * Expressions::
11134 * String Types::
11135 * Variables::
11136 * Attributes::
11137 * Associative Array Attributes::
11138 * case Constructions::
11139 @end menu
11140
11141 @noindent
11142 This section describes the structure of project files.
11143
11144 A project may be an @emph{independent project}, entirely defined by a single
11145 project file. Any Ada source file in an independent project depends only
11146 on the predefined library and other Ada source files in the same project.
11147
11148 @noindent
11149 A project may also @dfn{depend on} other projects, in either or both of
11150 the following ways:
11151 @itemize @bullet
11152 @item It may import any number of projects
11153 @item It may extend at most one other project
11154 @end itemize
11155
11156 @noindent
11157 The dependence relation is a directed acyclic graph (the subgraph reflecting
11158 the ``extends'' relation is a tree).
11159
11160 A project's @dfn{immediate sources} are the source files directly defined by
11161 that project, either implicitly by residing in the project file's directory,
11162 or explicitly through any of the source-related attributes described below.
11163 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11164 of @var{proj} together with the immediate sources (unless overridden) of any
11165 project on which @var{proj} depends (either directly or indirectly).
11166
11167 @node Basic Syntax
11168 @subsection Basic Syntax
11169
11170 @noindent
11171 As seen in the earlier examples, project files have an Ada-like syntax.
11172 The minimal project file is:
11173 @smallexample @c projectfile
11174 @group
11175 project Empty is
11176
11177 end Empty;
11178 @end group
11179 @end smallexample
11180
11181 @noindent
11182 The identifier @code{Empty} is the name of the project.
11183 This project name must be present after the reserved
11184 word @code{end} at the end of the project file, followed by a semi-colon.
11185
11186 Any name in a project file, such as the project name or a variable name,
11187 has the same syntax as an Ada identifier.
11188
11189 The reserved words of project files are the Ada reserved words plus
11190 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11191 reserved words currently used in project file syntax are:
11192
11193 @itemize @bullet
11194 @item
11195 @code{case}
11196 @item
11197 @code{end}
11198 @item
11199 @code{for}
11200 @item
11201 @code{is}
11202 @item
11203 @code{others}
11204 @item
11205 @code{package}
11206 @item
11207 @code{renames}
11208 @item
11209 @code{type}
11210 @item
11211 @code{use}
11212 @item
11213 @code{when}
11214 @item
11215 @code{with}
11216 @end itemize
11217
11218 @noindent
11219 Comments in project files have the same syntax as in Ada, two consecutives
11220 hyphens through the end of the line.
11221
11222 @node Packages
11223 @subsection Packages
11224
11225 @noindent
11226 A project file may contain @emph{packages}. The name of a package must be one
11227 of the identifiers from the following list. A package
11228 with a given name may only appear once in a project file. Package names are
11229 case insensitive. The following package names are legal:
11230
11231 @itemize @bullet
11232 @item
11233 @code{Naming}
11234 @item
11235 @code{Builder}
11236 @item
11237 @code{Compiler}
11238 @item
11239 @code{Binder}
11240 @item
11241 @code{Linker}
11242 @item
11243 @code{Finder}
11244 @item
11245 @code{Cross_Reference}
11246 @item
11247 @code{Eliminate}
11248 @item
11249 @code{gnatls}
11250 @item
11251 @code{gnatstub}
11252 @item
11253 @code{IDE}
11254 @end itemize
11255
11256 @noindent
11257 In its simplest form, a package may be empty:
11258
11259 @smallexample @c projectfile
11260 @group
11261 project Simple is
11262   package Builder is
11263   end Builder;
11264 end Simple;
11265 @end group
11266 @end smallexample
11267
11268 @noindent
11269 A package may contain @emph{attribute declarations},
11270 @emph{variable declarations} and @emph{case constructions}, as will be
11271 described below.
11272
11273 When there is ambiguity between a project name and a package name,
11274 the name always designates the project. To avoid possible confusion, it is
11275 always a good idea to avoid naming a project with one of the
11276 names allowed for packages or any name that starts with @code{gnat}.
11277
11278 @node Expressions
11279 @subsection Expressions
11280
11281 @noindent
11282 An @emph{expression} is either a @emph{string expression} or a
11283 @emph{string list expression}.
11284
11285 A @emph{string expression} is either a @emph{simple string expression} or a
11286 @emph{compound string expression}.
11287
11288 A @emph{simple string expression} is one of the following:
11289 @itemize @bullet
11290 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11291 @item A string-valued variable reference (see @ref{Variables})
11292 @item A string-valued attribute reference (see @ref{Attributes})
11293 @item An external reference (see @ref{External References in Project Files})
11294 @end itemize
11295
11296 @noindent
11297 A @emph{compound string expression} is a concatenation of string expressions,
11298 using the operator @code{"&"}
11299 @smallexample
11300        Path & "/" & File_Name & ".ads"
11301 @end smallexample
11302
11303 @noindent
11304 A @emph{string list expression} is either a
11305 @emph{simple string list expression} or a
11306 @emph{compound string list expression}.
11307
11308 A @emph{simple string list expression} is one of the following:
11309 @itemize @bullet
11310 @item A parenthesized list of zero or more string expressions,
11311 separated by commas
11312 @smallexample
11313    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11314    Empty_List := ();
11315 @end smallexample
11316 @item A string list-valued variable reference
11317 @item A string list-valued attribute reference
11318 @end itemize
11319
11320 @noindent
11321 A @emph{compound string list expression} is the concatenation (using
11322 @code{"&"}) of a simple string list expression and an expression.  Note that
11323 each term in a compound string list expression, except the first, may be
11324 either a string expression or a string list expression.
11325
11326 @smallexample @c projectfile
11327 @group
11328    File_Name_List := () & File_Name; --  One string in this list
11329    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11330    --  Two strings
11331    Big_List := File_Name_List & Extended_File_Name_List;
11332    --  Concatenation of two string lists: three strings
11333    Illegal_List := "gnat.adc" & Extended_File_Name_List;
11334    --  Illegal: must start with a string list
11335 @end group
11336 @end smallexample
11337
11338 @node String Types
11339 @subsection String Types
11340
11341 @noindent
11342 A @emph{string type declaration} introduces a discrete set of string literals.
11343 If a string variable is declared to have this type, its value
11344 is restricted to the given set of literals.
11345
11346 Here is an example of a string type declaration:
11347
11348 @smallexample @c projectfile
11349    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11350 @end smallexample
11351
11352 @noindent
11353 Variables of a string type are called @emph{typed variables}; all other
11354 variables are called @emph{untyped variables}. Typed variables are
11355 particularly useful in @code{case} constructions, to support conditional
11356 attribute declarations.
11357 (see @ref{case Constructions}).
11358
11359 The string literals in the list are case sensitive and must all be different.
11360 They may include any graphic characters allowed in Ada, including spaces.
11361
11362 A string type may only be declared at the project level, not inside a package.
11363
11364 A string type may be referenced by its name if it has been declared in the same
11365 project file, or by an expanded name whose prefix is the name of the project
11366 in which it is declared.
11367
11368 @node Variables
11369 @subsection Variables
11370
11371 @noindent
11372 A variable may be declared at the project file level, or within a package.
11373 Here are some examples of variable declarations:
11374
11375 @smallexample @c projectfile
11376 @group
11377    This_OS : OS := external ("OS"); --  a typed variable declaration
11378    That_OS := "GNU/Linux";          --  an untyped variable declaration
11379 @end group
11380 @end smallexample
11381
11382 @noindent
11383 The syntax of a @emph{typed variable declaration} is identical to the Ada
11384 syntax for an object declaration. By contrast, the syntax of an untyped
11385 variable declaration is identical to an Ada assignment statement. In fact,
11386 variable declarations in project files have some of the characteristics of
11387 an assignment, in that successive declarations for the same variable are
11388 allowed. Untyped variable declarations do establish the expected kind of the
11389 variable (string or string list), and successive declarations for it must
11390 respect the initial kind.
11391
11392 @noindent
11393 A string variable declaration (typed or untyped) declares a variable
11394 whose value is a string. This variable may be used as a string expression.
11395 @smallexample @c projectfile
11396    File_Name       := "readme.txt";
11397    Saved_File_Name := File_Name & ".saved";
11398 @end smallexample
11399
11400 @noindent
11401 A string list variable declaration declares a variable whose value is a list
11402 of strings. The list may contain any number (zero or more) of strings.
11403
11404 @smallexample @c projectfile
11405    Empty_List := ();
11406    List_With_One_Element := ("^-gnaty^-gnaty^");
11407    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11408    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11409                  "pack2.ada", "util_.ada", "util.ada");
11410 @end smallexample
11411
11412 @noindent
11413 The same typed variable may not be declared more than once at project level,
11414 and it may not be declared more than once in any package; it is in effect
11415 a constant.
11416
11417 The same untyped variable may be declared several times. Declarations are
11418 elaborated in the order in which they appear, so  the new value replaces
11419 the old one, and any subsequent reference to the variable uses the new value.
11420 However, as noted above, if a variable has been declared as a string, all
11421 subsequent
11422 declarations must give it a string value. Similarly, if a variable has
11423 been declared as a string list, all subsequent declarations
11424 must give it a string list value.
11425
11426 A @emph{variable reference} may take several forms:
11427
11428 @itemize @bullet
11429 @item The simple variable name, for a variable in the current package (if any)
11430 or in the current project
11431 @item An expanded name, whose prefix is a context name.
11432 @end itemize
11433
11434 @noindent
11435 A @emph{context} may be one of the following:
11436
11437 @itemize @bullet
11438 @item The name of an existing package in the current project
11439 @item The name of an imported project of the current project
11440 @item The name of an ancestor project (i.e., a project extended by the current
11441 project, either directly or indirectly)
11442 @item An expanded name whose prefix is an imported/parent project name, and
11443 whose selector is a package name in that project.
11444 @end itemize
11445
11446 @noindent
11447 A variable reference may be used in an expression.
11448
11449 @node Attributes
11450 @subsection Attributes
11451
11452 @noindent
11453 A project (and its packages) may have @emph{attributes} that define
11454 the project's properties.  Some attributes have values that are strings;
11455 others have values that are string lists.
11456
11457 There are two categories of attributes: @emph{simple attributes}
11458 and @emph{associative arrays} (see @ref{Associative Array Attributes}).
11459
11460 Legal project attribute names, and attribute names for each legal package are
11461 listed below. Attributes names are case-insensitive.
11462
11463 The following attributes are defined on projects (all are simple attributes):
11464
11465 @multitable @columnfractions .4 .3
11466 @item @emph{Attribute Name}
11467 @tab @emph{Value}
11468 @item @code{Source_Files}
11469 @tab string list
11470 @item @code{Source_Dirs}
11471 @tab string list
11472 @item @code{Source_List_File}
11473 @tab string
11474 @item @code{Object_Dir}
11475 @tab string
11476 @item @code{Exec_Dir}
11477 @tab string
11478 @item @code{Locally_Removed_Files}
11479 @tab string list
11480 @item @code{Main}
11481 @tab string list
11482 @item @code{Languages}
11483 @tab string list
11484 @item @code{Main_Language}
11485 @tab string
11486 @item @code{Library_Dir}
11487 @tab string
11488 @item @code{Library_Name}
11489 @tab string
11490 @item @code{Library_Kind}
11491 @tab string
11492 @item @code{Library_Version}
11493 @tab string
11494 @item @code{Library_Interface}
11495 @tab string
11496 @item @code{Library_Auto_Init}
11497 @tab string
11498 @item @code{Library_Options}
11499 @tab string list
11500 @item @code{Library_GCC}
11501 @tab string
11502 @end multitable
11503
11504 @noindent
11505 The following attributes are defined for package  @code{Naming}
11506 (see @ref{Naming Schemes}):
11507
11508 @multitable @columnfractions .4 .2 .2 .2
11509 @item Attribute Name @tab Category @tab Index @tab Value
11510 @item @code{Spec_Suffix}
11511 @tab associative array
11512 @tab language name
11513 @tab string
11514 @item @code{Body_Suffix}
11515 @tab associative array
11516 @tab language name
11517 @tab string
11518 @item @code{Separate_Suffix}
11519 @tab simple attribute
11520 @tab n/a
11521 @tab string
11522 @item @code{Casing}
11523 @tab simple attribute
11524 @tab n/a
11525 @tab string
11526 @item @code{Dot_Replacement}
11527 @tab simple attribute
11528 @tab n/a
11529 @tab string
11530 @item @code{Spec}
11531 @tab associative array
11532 @tab Ada unit name
11533 @tab string
11534 @item @code{Body}
11535 @tab associative array
11536 @tab Ada unit name
11537 @tab string
11538 @item @code{Specification_Exceptions}
11539 @tab associative array
11540 @tab language name
11541 @tab string list
11542 @item @code{Implementation_Exceptions}
11543 @tab associative array
11544 @tab language name
11545 @tab string list
11546 @end multitable
11547
11548 @noindent
11549 The following attributes are defined for packages @code{Builder},
11550 @code{Compiler}, @code{Binder},
11551 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
11552 (see @ref{^Switches^Switches^ and Project Files}).
11553
11554 @multitable @columnfractions .4 .2 .2 .2
11555 @item Attribute Name @tab Category @tab Index @tab Value
11556 @item @code{^Default_Switches^Default_Switches^}
11557 @tab associative array
11558 @tab language name
11559 @tab string list
11560 @item @code{^Switches^Switches^}
11561 @tab associative array
11562 @tab file name
11563 @tab string list
11564 @end multitable
11565
11566 @noindent
11567 In addition, package @code{Compiler} has a single string attribute
11568 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11569 string attribute @code{Global_Configuration_Pragmas}.
11570
11571 @noindent
11572 Each simple attribute has a default value: the empty string (for string-valued
11573 attributes) and the empty list (for string list-valued attributes).
11574
11575 An attribute declaration defines a new value for an attribute.
11576
11577 Examples of simple attribute declarations:
11578
11579 @smallexample @c projectfile
11580    for Object_Dir use "objects";
11581    for Source_Dirs use ("units", "test/drivers");
11582 @end smallexample
11583
11584 @noindent
11585 The syntax of a @dfn{simple attribute declaration} is similar to that of an
11586 attribute definition clause in Ada.
11587
11588 Attributes references may be appear in expressions.
11589 The general form for such a reference is @code{<entity>'<attribute>}:
11590 Associative array attributes are functions. Associative
11591 array attribute references must have an argument that is a string literal.
11592
11593 Examples are:
11594
11595 @smallexample @c projectfile
11596   project'Object_Dir
11597   Naming'Dot_Replacement
11598   Imported_Project'Source_Dirs
11599   Imported_Project.Naming'Casing
11600   Builder'^Default_Switches^Default_Switches^("Ada")
11601 @end smallexample
11602
11603 @noindent
11604 The prefix of an attribute may be:
11605 @itemize @bullet
11606 @item @code{project} for an attribute of the current project
11607 @item The name of an existing package of the current project
11608 @item The name of an imported project
11609 @item The name of a parent project that is extended by the current project
11610 @item An expanded name whose prefix is imported/parent project name,
11611       and whose selector is a package name
11612 @end itemize
11613
11614 @noindent
11615 Example:
11616 @smallexample @c projectfile
11617 @group
11618    project Prj is
11619      for Source_Dirs use project'Source_Dirs & "units";
11620      for Source_Dirs use project'Source_Dirs & "test/drivers"
11621    end Prj;
11622 @end group
11623 @end smallexample
11624
11625 @noindent
11626 In the first attribute declaration, initially the attribute @code{Source_Dirs}
11627 has the default value: an empty string list. After this declaration,
11628 @code{Source_Dirs} is a string list of one element: @code{"units"}.
11629 After the second attribute declaration @code{Source_Dirs} is a string list of
11630 two elements: @code{"units"} and @code{"test/drivers"}.
11631
11632 Note: this example is for illustration only. In practice,
11633 the project file would contain only one attribute declaration:
11634
11635 @smallexample @c projectfile
11636    for Source_Dirs use ("units", "test/drivers");
11637 @end smallexample
11638
11639 @node Associative Array Attributes
11640 @subsection Associative Array Attributes
11641
11642 @noindent
11643 Some attributes are defined as @emph{associative arrays}. An associative
11644 array may be regarded as a function that takes a string as a parameter
11645 and delivers a string or string list value as its result.
11646
11647 Here are some examples of single associative array attribute associations:
11648
11649 @smallexample @c projectfile
11650    for Body ("main") use "Main.ada";
11651    for ^Switches^Switches^ ("main.ada")
11652        use ("^-v^-v^",
11653             "^-gnatv^-gnatv^");
11654    for ^Switches^Switches^ ("main.ada")
11655             use Builder'^Switches^Switches^ ("main.ada")
11656               & "^-g^-g^";
11657 @end smallexample
11658
11659 @noindent
11660 Like untyped variables and simple attributes, associative array attributes
11661 may be declared several times. Each declaration supplies a new value for the
11662 attribute, and replaces the previous setting.
11663
11664 @noindent
11665 An associative array attribute may be declared as a full associative array
11666 declaration, with the value of the same attribute in an imported or extended
11667 project.
11668
11669 @smallexample @c projectfile
11670    package Builder is
11671       for Default_Switches use Default.Builder'Default_Switches;
11672    end Builder;
11673 @end smallexample
11674
11675 @noindent
11676 In this example, @code{Default} must be either an project imported by the
11677 current project, or the project that the current project extends. If the
11678 attribute is in a package (in this case, in package @code{Builder}), the same
11679 package needs to be specified.
11680
11681 @noindent
11682 A full associative array declaration replaces any other declaration for the
11683 attribute, including other full associative array declaration. Single
11684 associative array associations may be declare after a full associative
11685 declaration, modifying the value for a single association of the attribute.
11686
11687 @node case Constructions
11688 @subsection @code{case} Constructions
11689
11690 @noindent
11691 A @code{case} construction is used in a project file to effect conditional
11692 behavior.
11693 Here is a typical example:
11694
11695 @smallexample @c projectfile
11696 @group
11697 project MyProj is
11698    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11699
11700    OS : OS_Type := external ("OS", "GNU/Linux");
11701 @end group
11702
11703 @group
11704    package Compiler is
11705      case OS is
11706        when "GNU/Linux" | "Unix" =>
11707          for ^Default_Switches^Default_Switches^ ("Ada")
11708              use ("^-gnath^-gnath^");
11709        when "NT" =>
11710          for ^Default_Switches^Default_Switches^ ("Ada")
11711              use ("^-gnatP^-gnatP^");
11712        when others =>
11713      end case;
11714    end Compiler;
11715 end MyProj;
11716 @end group
11717 @end smallexample
11718
11719 @noindent
11720 The syntax of a @code{case} construction is based on the Ada case statement
11721 (although there is no @code{null} construction for empty alternatives).
11722
11723 The case expression must a typed string variable.
11724 Each alternative comprises the reserved word @code{when}, either a list of
11725 literal strings separated by the @code{"|"} character or the reserved word
11726 @code{others},  and the @code{"=>"} token.
11727 Each literal string must belong to the string type that is the type of the
11728 case variable.
11729 An @code{others} alternative, if present, must occur last.
11730
11731 After each @code{=>}, there are zero or more constructions.  The only
11732 constructions allowed in a case construction are other case constructions and
11733 attribute declarations. String type declarations, variable declarations and
11734 package declarations are not allowed.
11735
11736 The value of the case variable is often given by an external reference
11737 (see @ref{External References in Project Files}).
11738
11739 @c ****************************************
11740 @c * Objects and Sources in Project Files *
11741 @c ****************************************
11742
11743 @node Objects and Sources in Project Files
11744 @section Objects and Sources in Project Files
11745
11746 @menu
11747 * Object Directory::
11748 * Exec Directory::
11749 * Source Directories::
11750 * Source File Names::
11751 @end menu
11752
11753 @noindent
11754 Each project has exactly one object directory and one or more source
11755 directories. The source directories must contain at least one source file,
11756 unless  the project file explicitly specifies that no source files are present
11757 (see @ref{Source File Names}).
11758
11759 @node Object Directory
11760 @subsection Object Directory
11761
11762 @noindent
11763 The object directory for a project is the directory containing the compiler's
11764 output (such as @file{ALI} files and object files) for the project's immediate
11765 sources.
11766
11767 The object directory is given by the value of the attribute @code{Object_Dir}
11768 in the project file.
11769
11770 @smallexample @c projectfile
11771    for Object_Dir use "objects";
11772 @end smallexample
11773
11774 @noindent
11775 The attribute @var{Object_Dir} has a string value, the path name of the object
11776 directory. The path name may be absolute or relative to the directory of the
11777 project file. This directory must already exist, and be readable and writable.
11778
11779 By default, when the attribute @code{Object_Dir} is not given an explicit value
11780 or when its value is the empty string, the object directory is the same as the
11781 directory containing the project file.
11782
11783 @node Exec Directory
11784 @subsection Exec Directory
11785
11786 @noindent
11787 The exec directory for a project is the directory containing the executables
11788 for the project's main subprograms.
11789
11790 The exec directory is given by the value of the attribute @code{Exec_Dir}
11791 in the project file.
11792
11793 @smallexample @c projectfile
11794    for Exec_Dir use "executables";
11795 @end smallexample
11796
11797 @noindent
11798 The attribute @var{Exec_Dir} has a string value, the path name of the exec
11799 directory. The path name may be absolute or relative to the directory of the
11800 project file. This directory must already exist, and be writable.
11801
11802 By default, when the attribute @code{Exec_Dir} is not given an explicit value
11803 or when its value is the empty string, the exec directory is the same as the
11804 object directory of the project file.
11805
11806 @node Source Directories
11807 @subsection Source Directories
11808
11809 @noindent
11810 The source directories of a project are specified by the project file
11811 attribute @code{Source_Dirs}.
11812
11813 This attribute's value is a string list. If the attribute is not given an
11814 explicit value, then there is only one source directory, the one where the
11815 project file resides.
11816
11817 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
11818 as in
11819
11820 @smallexample @c projectfile
11821     for Source_Dirs use ();
11822 @end smallexample
11823
11824 @noindent
11825 indicates that the project contains no source files.
11826
11827 Otherwise, each string in the string list designates one or more
11828 source directories.
11829
11830 @smallexample @c projectfile
11831    for Source_Dirs use ("sources", "test/drivers");
11832 @end smallexample
11833
11834 @noindent
11835 If a string in the list ends with @code{"/**"},  then the directory whose path
11836 name precedes the two asterisks, as well as all its subdirectories
11837 (recursively), are source directories.
11838
11839 @smallexample @c projectfile
11840    for Source_Dirs use ("/system/sources/**");
11841 @end smallexample
11842
11843 @noindent
11844 Here the directory @code{/system/sources} and all of its subdirectories
11845 (recursively) are source directories.
11846
11847 To specify that the source directories are the directory of the project file
11848 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
11849 @smallexample @c projectfile
11850    for Source_Dirs use ("./**");
11851 @end smallexample
11852
11853 @noindent
11854 Each of the source directories must exist and be readable.
11855
11856 @node Source File Names
11857 @subsection Source File Names
11858
11859 @noindent
11860 In a project that contains source files, their names may be specified by the
11861 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
11862 (a string). Source file names never include any directory information.
11863
11864 If the attribute @code{Source_Files} is given an explicit value, then each
11865 element of the list is a source file name.
11866
11867 @smallexample @c projectfile
11868    for Source_Files use ("main.adb");
11869    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
11870 @end smallexample
11871
11872 @noindent
11873 If the attribute @code{Source_Files} is not given an explicit value,
11874 but the attribute @code{Source_List_File} is given a string value,
11875 then the source file names are contained in the text file whose path name
11876 (absolute or relative to the directory of the project file) is the
11877 value of the attribute @code{Source_List_File}.
11878
11879 Each line in the file that is not empty or is not a comment
11880 contains a source file name.
11881
11882 @smallexample @c projectfile
11883    for Source_List_File use "source_list.txt";
11884 @end smallexample
11885
11886 @noindent
11887 By default, if neither the attribute @code{Source_Files} nor the attribute
11888 @code{Source_List_File} is given an explicit value, then each file in the
11889 source directories that conforms to the project's naming scheme
11890 (see @ref{Naming Schemes}) is an immediate source of the project.
11891
11892 A warning is issued if both attributes @code{Source_Files} and
11893 @code{Source_List_File} are given explicit values. In this case, the attribute
11894 @code{Source_Files} prevails.
11895
11896 Each source file name must be the name of one existing source file
11897 in one of the source directories.
11898
11899 A @code{Source_Files} attribute whose value is an empty list
11900 indicates that there are no source files in the project.
11901
11902 If the order of the source directories is known statically, that is if
11903 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
11904 be several files with the same source file name. In this case, only the file
11905 in the first directory is considered as an immediate source of the project
11906 file. If the order of the source directories is not known statically, it is
11907 an error to have several files with the same source file name.
11908
11909 Projects can be specified to have no Ada source
11910 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
11911 list, or the @code{"Ada"} may be absent from @code{Languages}:
11912
11913 @smallexample @c projectfile
11914    for Source_Dirs use ();
11915    for Source_Files use ();
11916    for Languages use ("C", "C++");
11917 @end smallexample
11918
11919 @noindent
11920 Otherwise, a project must contain at least one immediate source.
11921
11922 Projects with no source files are useful as template packages
11923 (see @ref{Packages in Project Files}) for other projects; in particular to
11924 define a package @code{Naming} (see @ref{Naming Schemes}).
11925
11926 @c ****************************
11927 @c * Importing Projects *
11928 @c ****************************
11929
11930 @node  Importing Projects
11931 @section Importing Projects
11932
11933 @noindent
11934 An immediate source of a project P may depend on source files that
11935 are neither immediate sources of P nor in the predefined library.
11936 To get this effect, P must @emph{import} the projects that contain the needed
11937 source files.
11938
11939 @smallexample @c projectfile
11940 @group
11941   with "project1", "utilities.gpr";
11942   with "/namings/apex.gpr";
11943   project Main is
11944     ...
11945 @end group
11946 @end smallexample
11947
11948 @noindent
11949 As can be seen in this example, the syntax for importing projects is similar
11950 to the syntax for importing compilation units in Ada. However, project files
11951 use literal strings instead of names, and the @code{with} clause identifies
11952 project files rather than packages.
11953
11954 Each literal string is the file name or path name (absolute or relative) of a
11955 project file. If a string is simply a file name, with no path, then its
11956 location is determined by the @emph{project path}:
11957
11958 @itemize @bullet
11959 @item
11960 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} exists,
11961 then the project path includes all the directories in this
11962 ^environment variable^logical name^, plus the directory of the project file.
11963
11964 @item
11965 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} does not
11966 exist, then the project path contains only one directory, namely the one where
11967 the project file is located.
11968 @end itemize
11969
11970 @noindent
11971 If a relative pathname is used, as in
11972
11973 @smallexample @c projectfile
11974   with "tests/proj";
11975 @end smallexample
11976
11977 @noindent
11978 then the path is relative to the directory where the importing project file is
11979 located. Any symbolic link will be fully resolved in the directory
11980 of the importing project file before the imported project file is examined.
11981
11982 If the @code{with}'ed project file name does not have an extension,
11983 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
11984 then the file name as specified in the @code{with} clause (no extension) will
11985 be used. In the above example, if a file @code{project1.gpr} is found, then it
11986 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
11987 then it will be used; if neither file exists, this is an error.
11988
11989 A warning is issued if the name of the project file does not match the
11990 name of the project; this check is case insensitive.
11991
11992 Any source file that is an immediate source of the imported project can be
11993 used by the immediate sources of the importing project, transitively. Thus
11994 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
11995 sources of @code{A} may depend on the immediate sources of @code{C}, even if
11996 @code{A} does not import @code{C} explicitly. However, this is not recommended,
11997 because if and when @code{B} ceases to import @code{C}, some sources in
11998 @code{A} will no longer compile.
11999
12000 A side effect of this capability is that normally cyclic dependencies are not
12001 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
12002 is not allowed to import @code{A}. However, there are cases when cyclic
12003 dependencies would be beneficial. For these cases, another form of import
12004 between projects exists, the @code{limited with}: a project @code{A} that
12005 imports a project @code{B} with a straigh @code{with} may also be imported,
12006 directly or indirectly, by @code{B} on the condition that imports from @code{B}
12007 to @code{A} include at least one @code{limited with}.
12008
12009 @smallexample @c 0projectfile
12010 with "../b/b.gpr";
12011 with "../c/c.gpr";
12012 project A is
12013 end A;
12014
12015 limited with "../a/a.gpr";
12016 project B is
12017 end B;
12018
12019 with "../d/d.gpr";
12020 project C is
12021 end C;
12022
12023 limited with "../a/a.gpr";
12024 project D is
12025 end D;
12026 @end smallexample
12027
12028 @noindent
12029 In the above legal example, there are two project cycles:
12030 @itemize @bullet
12031 @item A-> B-> A
12032 @item A -> C -> D -> A
12033 @end itemize
12034
12035 @noindent
12036 In each of these cycle there is one @code{limited with}: import of @code{A}
12037 from @code{B} and import of @code{A} from @code{D}.
12038
12039 The difference between straight @code{with} and @code{limited with} is that
12040 the name of a project imported with a @code{limited with} cannot be used in the
12041 project that imports it. In particular, its packages cannot be renamed and
12042 its variables cannot be referred to.
12043
12044 An exception to the above rules for @code{limited with} is that for the main
12045 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12046 @code{limited with} is equivalent to a straight @code{with}. For example,
12047 in the example above, projects @code{B} and @code{D} could not be main
12048 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12049 each have a @code{limited with} that is the only one in a cycle of importing
12050 projects.
12051
12052 @c *********************
12053 @c * Project Extension *
12054 @c *********************
12055
12056 @node Project Extension
12057 @section Project Extension
12058
12059 @noindent
12060 During development of a large system, it is sometimes necessary to use
12061 modified versions of some of the source files, without changing the original
12062 sources. This can be achieved through the @emph{project extension} facility.
12063
12064 @smallexample @c projectfile
12065    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12066 @end smallexample
12067
12068 @noindent
12069 A project extension declaration introduces an extending project
12070 (the @emph{child}) and a project being extended (the @emph{parent}).
12071
12072 By default, a child project inherits all the sources of its parent.
12073 However, inherited sources can be overridden: a unit in a parent is hidden
12074 by a unit of the same name in the child.
12075
12076 Inherited sources are considered to be sources (but not immediate sources)
12077 of the child project; see @ref{Project File Syntax}.
12078
12079 An inherited source file retains any switches specified in the parent project.
12080
12081 For example if the project @code{Utilities} contains the specification and the
12082 body of an Ada package @code{Util_IO}, then the project
12083 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12084 The original body of @code{Util_IO} will not be considered in program builds.
12085 However, the package specification will still be found in the project
12086 @code{Utilities}.
12087
12088 A child project can have only one parent but it may import any number of other
12089 projects.
12090
12091 A project is not allowed to import directly or indirectly at the same time a
12092 child project and any of its ancestors.
12093
12094 @c ****************************************
12095 @c * External References in Project Files *
12096 @c ****************************************
12097
12098 @node  External References in Project Files
12099 @section External References in Project Files
12100
12101 @noindent
12102 A project file may contain references to external variables; such references
12103 are called @emph{external references}.
12104
12105 An external variable is either defined as part of the environment (an
12106 environment variable in Unix, for example) or else specified on the command
12107 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12108 If both, then the command line value is used.
12109
12110 The value of an external reference is obtained by means of the built-in
12111 function @code{external}, which returns a string value.
12112 This function has two forms:
12113 @itemize @bullet
12114 @item @code{external (external_variable_name)}
12115 @item @code{external (external_variable_name, default_value)}
12116 @end itemize
12117
12118 @noindent
12119 Each parameter must be a string literal.  For example:
12120
12121 @smallexample @c projectfile
12122    external ("USER")
12123    external ("OS", "GNU/Linux")
12124 @end smallexample
12125
12126 @noindent
12127 In the form with one parameter, the function returns the value of
12128 the external variable given as parameter. If this name is not present in the
12129 environment, the function returns an empty string.
12130
12131 In the form with two string parameters, the second argument is
12132 the value returned when the variable given as the first argument is not
12133 present in the environment. In the example above, if @code{"OS"} is not
12134 the name of ^an environment variable^a logical name^ and is not passed on
12135 the command line, then the returned value is @code{"GNU/Linux"}.
12136
12137 An external reference may be part of a string expression or of a string
12138 list expression, and can therefore appear in a variable declaration or
12139 an attribute declaration.
12140
12141 @smallexample @c projectfile
12142 @group
12143    type Mode_Type is ("Debug", "Release");
12144    Mode : Mode_Type := external ("MODE");
12145    case Mode is
12146      when "Debug" =>
12147         ...
12148 @end group
12149 @end smallexample
12150
12151 @c *****************************
12152 @c * Packages in Project Files *
12153 @c *****************************
12154
12155 @node  Packages in Project Files
12156 @section Packages in Project Files
12157
12158 @noindent
12159 A @emph{package} defines the settings for project-aware tools within a
12160 project.
12161 For each such tool one can declare a package; the names for these
12162 packages are preset (see @ref{Packages}).
12163 A package may contain variable declarations, attribute declarations, and case
12164 constructions.
12165
12166 @smallexample @c projectfile
12167 @group
12168    project Proj is
12169       package Builder is  -- used by gnatmake
12170          for ^Default_Switches^Default_Switches^ ("Ada")
12171              use ("^-v^-v^",
12172                   "^-g^-g^");
12173       end Builder;
12174    end Proj;
12175 @end group
12176 @end smallexample
12177
12178 @noindent
12179 The syntax of package declarations mimics that of package in Ada.
12180
12181 Most of the packages have an attribute
12182 @code{^Default_Switches^Default_Switches^}.
12183 This attribute is an associative array, and its value is a string list.
12184 The index of the associative array is the name of a programming language (case
12185 insensitive). This attribute indicates the ^switch^switch^
12186 or ^switches^switches^ to be used
12187 with the corresponding tool.
12188
12189 Some packages also have another attribute, @code{^Switches^Switches^},
12190 an associative array whose value is a string list.
12191 The index is the name of a source file.
12192 This attribute indicates the ^switch^switch^
12193 or ^switches^switches^ to be used by the corresponding
12194 tool when dealing with this specific file.
12195
12196 Further information on these ^switch^switch^-related attributes is found in
12197 @ref{^Switches^Switches^ and Project Files}.
12198
12199 A package may be declared as a @emph{renaming} of another package; e.g., from
12200 the project file for an imported project.
12201
12202 @smallexample @c projectfile
12203 @group
12204   with "/global/apex.gpr";
12205   project Example is
12206     package Naming renames Apex.Naming;
12207     ...
12208   end Example;
12209 @end group
12210 @end smallexample
12211
12212 @noindent
12213 Packages that are renamed in other project files often come from project files
12214 that have no sources: they are just used as templates. Any modification in the
12215 template will be reflected automatically in all the project files that rename
12216 a package from the template.
12217
12218 In addition to the tool-oriented packages, you can also declare a package
12219 named @code{Naming} to establish specialized source file naming conventions
12220 (see @ref{Naming Schemes}).
12221
12222 @c ************************************
12223 @c * Variables from Imported Projects *
12224 @c ************************************
12225
12226 @node Variables from Imported Projects
12227 @section Variables from Imported Projects
12228
12229 @noindent
12230 An attribute or variable defined in an imported or parent project can
12231 be used in expressions in the importing / extending project.
12232 Such an attribute or variable is denoted by an expanded name whose prefix
12233 is either the name of the project or the expanded name of a package within
12234 a project.
12235
12236 @smallexample @c projectfile
12237 @group
12238   with "imported";
12239   project Main extends "base" is
12240      Var1 := Imported.Var;
12241      Var2 := Base.Var & ".new";
12242 @end group
12243
12244 @group
12245      package Builder is
12246         for ^Default_Switches^Default_Switches^ ("Ada")
12247             use Imported.Builder.Ada_^Switches^Switches^ &
12248                 "^-gnatg^-gnatg^" &
12249                 "^-v^-v^";
12250      end Builder;
12251 @end group
12252
12253 @group
12254      package Compiler is
12255         for ^Default_Switches^Default_Switches^ ("Ada")
12256             use Base.Compiler.Ada_^Switches^Switches^;
12257      end Compiler;
12258   end Main;
12259 @end group
12260 @end smallexample
12261
12262 @noindent
12263 In this example:
12264
12265 @itemize @bullet
12266 @item
12267 The value of @code{Var1} is a copy of the variable @code{Var} defined
12268 in the project file @file{"imported.gpr"}
12269 @item
12270 the value of @code{Var2} is a copy of the value of variable @code{Var}
12271 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12272 @item
12273 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12274 @code{Builder} is a string list that includes in its value a copy of the value
12275 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12276 in project file @file{imported.gpr} plus two new elements:
12277 @option{"^-gnatg^-gnatg^"}
12278 and @option{"^-v^-v^"};
12279 @item
12280 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12281 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12282 defined in the @code{Compiler} package in project file @file{base.gpr},
12283 the project being extended.
12284 @end itemize
12285
12286 @c ******************
12287 @c * Naming Schemes *
12288 @c ******************
12289
12290 @node  Naming Schemes
12291 @section Naming Schemes
12292
12293 @noindent
12294 Sometimes an Ada software system is ported from a foreign compilation
12295 environment to GNAT, and the file names do not use the default GNAT
12296 conventions. Instead of changing all the file names (which for a variety
12297 of reasons might not be possible), you can define the relevant file
12298 naming scheme in the @code{Naming} package in your project file.
12299
12300 @noindent
12301 Note that the use of pragmas described in @ref{Alternative
12302 File Naming Schemes} by mean of a configuration pragmas file is not
12303 supported when using project files. You must use the features described
12304 in this paragraph. You can however use specify other configuration
12305 pragmas (see @ref{Specifying Configuration Pragmas}).
12306
12307 @ifclear vms
12308 For example, the following
12309 package models the Apex file naming rules:
12310
12311 @smallexample @c projectfile
12312 @group
12313   package Naming is
12314     for Casing               use "lowercase";
12315     for Dot_Replacement      use ".";
12316     for Spec_Suffix ("Ada")  use ".1.ada";
12317     for Body_Suffix ("Ada")  use ".2.ada";
12318   end Naming;
12319 @end group
12320 @end smallexample
12321 @end ifclear
12322
12323 @ifset vms
12324 For example, the following package models the DEC Ada file naming rules:
12325
12326 @smallexample @c projectfile
12327 @group
12328   package Naming is
12329     for Casing               use "lowercase";
12330     for Dot_Replacement      use "__";
12331     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12332     for Body_Suffix ("Ada")  use ".^ada^ada^";
12333   end Naming;
12334 @end group
12335 @end smallexample
12336
12337 @noindent
12338 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12339 names in lower case)
12340 @end ifset
12341
12342 @noindent
12343 You can define the following attributes in package @code{Naming}:
12344
12345 @table @code
12346
12347 @item @var{Casing}
12348 This must be a string with one of the three values @code{"lowercase"},
12349 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12350
12351 @noindent
12352 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12353
12354 @item @var{Dot_Replacement}
12355 This must be a string whose value satisfies the following conditions:
12356
12357 @itemize @bullet
12358 @item It must not be empty
12359 @item It cannot start or end with an alphanumeric character
12360 @item It cannot be a single underscore
12361 @item It cannot start with an underscore followed by an alphanumeric
12362 @item It cannot contain a dot @code{'.'} except if the entire string
12363 is @code{"."}
12364 @end itemize
12365
12366 @noindent
12367 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12368
12369 @item @var{Spec_Suffix}
12370 This is an associative array (indexed by the programming language name, case
12371 insensitive) whose value is a string that must satisfy the following
12372 conditions:
12373
12374 @itemize @bullet
12375 @item It must not be empty
12376 @item It must include at least one dot
12377 @end itemize
12378 @noindent
12379 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12380 @code{"^.ads^.ADS^"}.
12381
12382 @item @var{Body_Suffix}
12383 This is an associative array (indexed by the programming language name, case
12384 insensitive) whose value is a string that must satisfy the following
12385 conditions:
12386
12387 @itemize @bullet
12388 @item It must not be empty
12389 @item It must include at least one dot
12390 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12391 @end itemize
12392 @noindent
12393 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12394 @code{"^.adb^.ADB^"}.
12395
12396 @item @var{Separate_Suffix}
12397 This must be a string whose value satisfies the same conditions as
12398 @code{Body_Suffix}.
12399
12400 @noindent
12401 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12402 value as @code{Body_Suffix ("Ada")}.
12403
12404 @item @var{Spec}
12405 @noindent
12406 You can use the associative array attribute @code{Spec}  to define
12407 the source file name for an individual Ada compilation unit's spec. The array
12408 index must be a string literal that identifies the Ada unit (case insensitive).
12409 The value of this attribute must be a string that identifies the file that
12410 contains this unit's spec (case sensitive or insensitive depending on the
12411 operating system).
12412
12413 @smallexample @c projectfile
12414    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12415 @end smallexample
12416
12417 @item @var{Body}
12418
12419 You can use the associative array attribute @code{Body} to
12420 define the source file name for an individual Ada compilation unit's body
12421 (possibly a subunit).  The array index must be a string literal that identifies
12422 the Ada unit (case insensitive).  The value of this attribute must be a string
12423 that identifies the file that contains this unit's body or subunit (case
12424 sensitive or insensitive depending on the operating system).
12425
12426 @smallexample @c projectfile
12427    for Body ("MyPack.MyChild") use "mypack.mychild.body";
12428 @end smallexample
12429 @end table
12430
12431 @c ********************
12432 @c * Library Projects *
12433 @c ********************
12434
12435 @node Library Projects
12436 @section Library Projects
12437
12438 @noindent
12439 @emph{Library projects} are projects whose object code is placed in a library.
12440 (Note that this facility is not yet supported on all platforms)
12441
12442 To create a library project, you need to define in its project file
12443 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12444 Additionally, you may define the library-related attributes
12445 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12446 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12447
12448 The @code{Library_Name} attribute has a string value. There is no restriction
12449 on the name of a library. It is the responsability of the developer to
12450 choose a name that will be accepted by the platform. It is recommanded to
12451 choose names that could be Ada identifiers; such names are almost guaranteed
12452 to be acceptable on all platforms.
12453
12454 The @code{Library_Dir} attribute has a string value that designates the path
12455 (absolute or relative) of the directory where the library will reside.
12456 It must designate an existing directory, and this directory must be
12457 different from the project's object directory. It also needs to be writable.
12458 The directory should only be used for one library; the reason is that all
12459 files contained in this directory may be deleted by the Project Manager.
12460
12461 If both @code{Library_Name} and @code{Library_Dir} are specified and
12462 are legal, then the project file defines a library project.  The optional
12463 library-related attributes are checked only for such project files.
12464
12465 The @code{Library_Kind} attribute has a string value that must be one of the
12466 following (case insensitive): @code{"static"}, @code{"dynamic"} or
12467 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
12468 attribute is not specified, the library is a static library, that is
12469 an archive of object files that can be potentially linked into an
12470 static executable. Otherwise, the library may be dynamic or
12471 relocatable, that is a library that is loaded only at the start of execution.
12472
12473 If you need to build both a static and a dynamic library, you should use two
12474 different object directories, since in some cases some extra code needs to
12475 be generated for the latter. For such cases, it is recommended to either use
12476 two different project files, or a single one which uses external variables
12477 to indicate what kind of library should be build.
12478
12479 The @code{Library_Version} attribute has a string value whose interpretation
12480 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12481 used only for dynamic/relocatable libraries as the internal name of the
12482 library (the @code{"soname"}). If the library file name (built from the
12483 @code{Library_Name}) is different from the @code{Library_Version}, then the
12484 library file will be a symbolic link to the actual file whose name will be
12485 @code{Library_Version}.
12486
12487 Example (on Unix):
12488
12489 @smallexample @c projectfile
12490 @group
12491 project Plib is
12492
12493    Version := "1";
12494
12495    for Library_Dir use "lib_dir";
12496    for Library_Name use "dummy";
12497    for Library_Kind use "relocatable";
12498    for Library_Version use "libdummy.so." & Version;
12499
12500 end Plib;
12501 @end group
12502 @end smallexample
12503
12504 @noindent
12505 Directory @file{lib_dir} will contain the internal library file whose name
12506 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12507 @file{libdummy.so.1}.
12508
12509 When @command{gnatmake} detects that a project file
12510 is a library project file, it will check all immediate sources of the project
12511 and rebuild the library if any of the sources have been recompiled.
12512
12513 Standard project files can import library project files. In such cases,
12514 the libraries will only be rebuild if some of its sources are recompiled
12515 because they are in the closure of some other source in an importing project.
12516 Sources of the library project files that are not in such a closure will
12517 not be checked, unless the full library is checked, because one of its sources
12518 needs to be recompiled.
12519
12520 For instance, assume the project file @code{A} imports the library project file
12521 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
12522 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
12523 @file{l2.ads}, @file{l2.adb}.
12524
12525 If @file{l1.adb} has been modified, then the library associated with @code{L}
12526 will be rebuild when compiling all the immediate sources of @code{A} only
12527 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
12528 @code{"with L1;"}.
12529
12530 To be sure that all the sources in the library associated with @code{L} are
12531 up to date, and that all the sources of parject @code{A} are also up to date,
12532 the following two commands needs to be used:
12533
12534 @smallexample
12535 gnatmake -Pl.gpr
12536 gnatmake -Pa.gpr
12537 @end smallexample
12538
12539 When a library is built or rebuilt, an attempt is made first to delete all
12540 files in the library directory.
12541 All @file{ALI} files will also be copied from the object directory to the
12542 library directory. To build executables, @command{gnatmake} will use the
12543 library rather than the individual object files.
12544
12545
12546 @c **********************************************
12547 @c * Using Third-Party Libraries through Projects
12548 @c **********************************************
12549 @node Using Third-Party Libraries through Projects
12550 @section Using Third-Party Libraries through Projects
12551
12552 Whether you are exporting your own library to make it available to
12553 clients, or you are using a library provided by a third party, it is
12554 convenient to have project files that automatically set the correct
12555 command line switches for the compiler and linker.
12556
12557 Such project files are very similar to the library project files;
12558 @xref{Library Projects}. The only difference is that you set the
12559 @code{Source_Dirs} and @code{Object_Dir} attribute so that they point to the
12560 directories where, respectively, the sources and the read-only ALI files have
12561 been installed.
12562
12563 If you need to interface with a set of libraries, as opposed to a
12564 single one, you need to create one library project for each of the
12565 libraries. In addition, a top-level project that imports all these
12566 library projects should be provided, so that the user of your library
12567 has a single @code{with} clause to add to his own projects.
12568
12569 For instance, let's assume you are providing two static libraries
12570 @file{liba.a} and @file{libb.a}. The user needs to link with
12571 both of these libraries. Each of these is associated with its
12572 own set of header files. Let's assume furthermore that all the
12573 header files for the two libraries have been installed in the same
12574 directory @file{headers}. The @file{ALI} files are found in the same
12575 @file{headers} directory.
12576
12577 In this case, you should provide the following three projects:
12578
12579 @smallexample @c projectfile
12580 @group
12581 with "liba", "libb";
12582 project My_Library is
12583   for Source_Dirs use ("headers");
12584   for Object_Dir  use "headers";
12585 end My_Library;
12586 @end group
12587
12588 @group
12589 project Liba is
12590    for Source_Dirs use ();
12591    for Library_Dir use "lib";
12592    for Library_Name use "a";
12593    for Library_Kind use "static";
12594 end Liba;
12595 @end group
12596
12597 @group
12598 project Libb is
12599    for Source_Dirs use ();
12600    for Library_Dir use "lib";
12601    for Library_Name use "b";
12602    for Library_Kind use "static";
12603 end Libb;
12604 @end group
12605 @end smallexample
12606
12607 @c *******************************
12608 @c * Stand-alone Library Projects *
12609 @c *******************************
12610
12611 @node Stand-alone Library Projects
12612 @section Stand-alone Library Projects
12613
12614 @noindent
12615 A Stand-alone Library is a library that contains the necessary code to
12616 elaborate the Ada units that are included in the library. A Stand-alone
12617 Library is suitable to be used in an executable when the main is not
12618 in Ada. However, Stand-alone Libraries may also be used with an Ada main
12619 subprogram.
12620
12621 A Stand-alone Library Project is a Library Project where the library is
12622 a Stand-alone Library.
12623
12624 To be a Stand-alone Library Project, in addition to the two attributes
12625 that make a project a Library Project (@code{Library_Name} and
12626 @code{Library_Dir}, see @ref{Library Projects}), the attribute
12627 @code{Library_Interface} must be defined.
12628
12629 @smallexample @c projectfile
12630 @group
12631    for Library_Dir use "lib_dir";
12632    for Library_Name use "dummy";
12633    for Library_Interface use ("int1", "int1.child");
12634 @end group
12635 @end smallexample
12636
12637 Attribute @code{Library_Interface} has a non empty string list value,
12638 each string in the list designating a unit contained in an immediate source
12639 of the project file.
12640
12641 When a Stand-alone Library is built, first the binder is invoked to build
12642 a package whose name depends on the library name
12643 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12644 This binder-generated package includes initialization and
12645 finalization procedures whose
12646 names depend on the library name (dummyinit and dummyfinal in the example
12647 above). The object corresponding to this package is included in the library.
12648
12649 A dynamic or relocatable Stand-alone Library is automatically initialized
12650 if automatic initialization of Stand-alone Libraries is supported on the
12651 platform and if attribute @code{Library_Auto_Init} is not specified or
12652 is specified with the value "true". A static Stand-alone Library is never
12653 automatically initialized.
12654
12655 Single string attribute @code{Library_Auto_Init} may be specified with only
12656 two possible values: "false" or "true" (case-insensitive). Specifying
12657 "false" for attribute @code{Library_Auto_Init} will prevent automatic
12658 initialization of dynamic or relocatable libraries.
12659
12660 When a non automatically initialized Stand-alone Library is used
12661 in an executable, its initialization procedure must be called before
12662 any service of the library is used.
12663 When the main subprogram is in Ada, it may mean that the initialization
12664 procedure has to be called during elaboration of another package.
12665
12666 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12667 (those that are listed in attribute @code{Library_Interface}) are copied to
12668 the Library Directory. As a consequence, only the Interface Units may be
12669 imported from Ada units outside of the library. If other units are imported,
12670 the binding phase will fail.
12671
12672 When a Stand-Alone Library is bound, the switches that are specified in
12673 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12674 used in the call to @command{gnatbind}.
12675
12676 The string list attribute @code{Library_Options} may be used to specified
12677 additional switches to the call to @command{gcc} to link the library.
12678
12679 The attribute @code{Library_Src_Dir}, may be specified for a
12680 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12681 single string value. Its value must be the path (absolute or relative to the
12682 project directory) of an existing directory. This directory cannot be the
12683 object directory or one of the source directories, but it can be the same as
12684 the library directory. The sources of the Interface
12685 Units of the library, necessary to an Ada client of the library, will be
12686 copied to the designated directory, called Interface Copy directory.
12687 These sources includes the specs of the Interface Units, but they may also
12688 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12689 are used, or when there is a generic units in the spec. Before the sources
12690 are copied to the Interface Copy directory, an attempt is made to delete all
12691 files in the Interface Copy directory.
12692
12693 @c *************************************
12694 @c * Switches Related to Project Files *
12695 @c *************************************
12696 @node Switches Related to Project Files
12697 @section Switches Related to Project Files
12698
12699 @noindent
12700 The following switches are used by GNAT tools that support project files:
12701
12702 @table @option
12703
12704 @item ^-P^/PROJECT_FILE=^@var{project}
12705 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12706 Indicates the name of a project file. This project file will be parsed with
12707 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12708 if any, and using the external references indicated
12709 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12710 @ifclear vms
12711 There may zero, one or more spaces between @option{-P} and @var{project}.
12712 @end ifclear
12713
12714 @noindent
12715 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12716
12717 @noindent
12718 Since the Project Manager parses the project file only after all the switches
12719 on the command line are checked, the order of the switches
12720 @option{^-P^/PROJECT_FILE^},
12721 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12722 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12723
12724 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12725 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12726 Indicates that external variable @var{name} has the value @var{value}.
12727 The Project Manager will use this value for occurrences of
12728 @code{external(name)} when parsing the project file.
12729
12730 @ifclear vms
12731 @noindent
12732 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12733 put between quotes.
12734 @smallexample
12735   -XOS=NT
12736   -X"user=John Doe"
12737 @end smallexample
12738 @end ifclear
12739
12740 @noindent
12741 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12742 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12743 @var{name}, only the last one is used.
12744
12745 @noindent
12746 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12747 takes precedence over the value of the same name in the environment.
12748
12749 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12750 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
12751 @c Previous line uses code vs option command, to stay less than 80 chars
12752 Indicates the verbosity of the parsing of GNAT project files.
12753
12754 @ifclear vms
12755 @option{-vP0} means Default;
12756 @option{-vP1} means Medium;
12757 @option{-vP2} means High.
12758 @end ifclear
12759
12760 @ifset vms
12761 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12762 HIGH.
12763 @end ifset
12764
12765 @noindent
12766 The default is ^Default^DEFAULT^: no output for syntactically correct
12767 project files.
12768 @noindent
12769 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12770 only the last one is used.
12771
12772 @end table
12773
12774 @c **********************************
12775 @c * Tools Supporting Project Files *
12776 @c **********************************
12777
12778 @node  Tools Supporting Project Files
12779 @section Tools Supporting Project Files
12780
12781 @menu
12782 * gnatmake and Project Files::
12783 * The GNAT Driver and Project Files::
12784 @ifclear vms
12785 * Glide and Project Files::
12786 @end ifclear
12787 @end menu
12788
12789 @node gnatmake and Project Files
12790 @subsection gnatmake and Project Files
12791
12792 @noindent
12793 This section covers several topics related to @command{gnatmake} and
12794 project files: defining ^switches^switches^ for @command{gnatmake}
12795 and for the tools that it invokes; specifying configuration pragmas;
12796 the use of the @code{Main} attribute; building and rebuilding library project
12797 files.
12798
12799 @menu
12800 * ^Switches^Switches^ and Project Files::
12801 * Specifying Configuration Pragmas::
12802 * Project Files and Main Subprograms::
12803 * Library Project Files::
12804 @end menu
12805
12806 @node ^Switches^Switches^ and Project Files
12807 @subsubsection ^Switches^Switches^ and Project Files
12808
12809 @ifset vms
12810 It is not currently possible to specify VMS style qualifiers in the project
12811 files; only Unix style ^switches^switches^ may be specified.
12812 @end ifset
12813
12814 @noindent
12815 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12816 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12817 attribute, a @code{^Switches^Switches^} attribute, or both;
12818 as their names imply, these ^switch^switch^-related
12819 attributes affect the ^switches^switches^ that are used for each of these GNAT
12820 components when
12821 @command{gnatmake} is invoked.  As will be explained below, these
12822 component-specific ^switches^switches^ precede
12823 the ^switches^switches^ provided on the @command{gnatmake} command line.
12824
12825 The @code{^Default_Switches^Default_Switches^} attribute is an associative
12826 array indexed by language name (case insensitive) whose value is a string list.
12827 For example:
12828
12829 @smallexample @c projectfile
12830 @group
12831 package Compiler is
12832   for ^Default_Switches^Default_Switches^ ("Ada")
12833       use ("^-gnaty^-gnaty^",
12834            "^-v^-v^");
12835 end Compiler;
12836 @end group
12837 @end smallexample
12838
12839 @noindent
12840 The @code{^Switches^Switches^} attribute is also an associative array,
12841 indexed by a file name (which may or may not be case sensitive, depending
12842 on the operating system) whose value is a string list.  For example:
12843
12844 @smallexample @c projectfile
12845 @group
12846 package Builder is
12847    for ^Switches^Switches^ ("main1.adb")
12848        use ("^-O2^-O2^");
12849    for ^Switches^Switches^ ("main2.adb")
12850        use ("^-g^-g^");
12851 end Builder;
12852 @end group
12853 @end smallexample
12854
12855 @noindent
12856 For the @code{Builder} package, the file names must designate source files
12857 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12858 file names must designate @file{ALI} or source files for main subprograms.
12859 In each case just the file name without an explicit extension is acceptable.
12860
12861 For each tool used in a program build (@command{gnatmake}, the compiler, the
12862 binder, and the linker), the corresponding package @dfn{contributes} a set of
12863 ^switches^switches^ for each file on which the tool is invoked, based on the
12864 ^switch^switch^-related attributes defined in the package.
12865 In particular, the ^switches^switches^
12866 that each of these packages contributes for a given file @var{f} comprise:
12867
12868 @itemize @bullet
12869 @item
12870 the value of attribute @code{^Switches^Switches^ (@var{f})},
12871 if it is specified in the package for the given file,
12872 @item
12873 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12874 if it is specified in the package.
12875 @end itemize
12876
12877 @noindent
12878 If neither of these attributes is defined in the package, then the package does
12879 not contribute any ^switches^switches^ for the given file.
12880
12881 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12882 two sets, in the following order: those contributed for the file
12883 by the @code{Builder} package;
12884 and the switches passed on the command line.
12885
12886 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12887 the ^switches^switches^ passed to the tool comprise three sets,
12888 in the following order:
12889
12890 @enumerate
12891 @item
12892 the applicable ^switches^switches^ contributed for the file
12893 by the @code{Builder} package in the project file supplied on the command line;
12894
12895 @item
12896 those contributed for the file by the package (in the relevant project file --
12897 see below) corresponding to the tool; and
12898
12899 @item
12900 the applicable switches passed on the command line.
12901 @end enumerate
12902
12903 @noindent
12904 The term @emph{applicable ^switches^switches^} reflects the fact that
12905 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12906 tools, depending on the individual ^switch^switch^.
12907
12908 @command{gnatmake} may invoke the compiler on source files from different
12909 projects. The Project Manager will use the appropriate project file to
12910 determine the @code{Compiler} package for each source file being compiled.
12911 Likewise for the @code{Binder} and @code{Linker} packages.
12912
12913 As an example, consider the following package in a project file:
12914
12915 @smallexample @c projectfile
12916 @group
12917 project Proj1 is
12918    package Compiler is
12919       for ^Default_Switches^Default_Switches^ ("Ada")
12920           use ("^-g^-g^");
12921       for ^Switches^Switches^ ("a.adb")
12922           use ("^-O1^-O1^");
12923       for ^Switches^Switches^ ("b.adb")
12924           use ("^-O2^-O2^",
12925                "^-gnaty^-gnaty^");
12926    end Compiler;
12927 end Proj1;
12928 @end group
12929 @end smallexample
12930
12931 @noindent
12932 If @command{gnatmake} is invoked with this project file, and it needs to
12933 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12934 @file{a.adb} will be compiled with the ^switch^switch^
12935 @option{^-O1^-O1^},
12936 @file{b.adb} with ^switches^switches^
12937 @option{^-O2^-O2^}
12938 and @option{^-gnaty^-gnaty^},
12939 and @file{c.adb} with @option{^-g^-g^}.
12940
12941 The following example illustrates the ordering of the ^switches^switches^
12942 contributed by different packages:
12943
12944 @smallexample @c projectfile
12945 @group
12946 project Proj2 is
12947    package Builder is
12948       for ^Switches^Switches^ ("main.adb")
12949           use ("^-g^-g^",
12950                "^-O1^-)1^",
12951                "^-f^-f^");
12952    end Builder;
12953 @end group
12954
12955 @group
12956    package Compiler is
12957       for ^Switches^Switches^ ("main.adb")
12958           use ("^-O2^-O2^");
12959    end Compiler;
12960 end Proj2;
12961 @end group
12962 @end smallexample
12963
12964 @noindent
12965 If you issue the command:
12966
12967 @smallexample
12968     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12969 @end smallexample
12970
12971 @noindent
12972 then the compiler will be invoked on @file{main.adb} with the following
12973 sequence of ^switches^switches^
12974
12975 @smallexample
12976    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12977 @end smallexample
12978
12979 with the last @option{^-O^-O^}
12980 ^switch^switch^ having precedence over the earlier ones;
12981 several other ^switches^switches^
12982 (such as @option{^-c^-c^}) are added implicitly.
12983
12984 The ^switches^switches^
12985 @option{^-g^-g^}
12986 and @option{^-O1^-O1^} are contributed by package
12987 @code{Builder},  @option{^-O2^-O2^} is contributed
12988 by the package @code{Compiler}
12989 and @option{^-O0^-O0^} comes from the command line.
12990
12991 The @option{^-g^-g^}
12992 ^switch^switch^ will also be passed in the invocation of
12993 @command{Gnatlink.}
12994
12995 A final example illustrates switch contributions from packages in different
12996 project files:
12997
12998 @smallexample @c projectfile
12999 @group
13000 project Proj3 is
13001    for Source_Files use ("pack.ads", "pack.adb");
13002    package Compiler is
13003       for ^Default_Switches^Default_Switches^ ("Ada")
13004           use ("^-gnata^-gnata^");
13005    end Compiler;
13006 end Proj3;
13007 @end group
13008
13009 @group
13010 with "Proj3";
13011 project Proj4 is
13012    for Source_Files use ("foo_main.adb", "bar_main.adb");
13013    package Builder is
13014       for ^Switches^Switches^ ("foo_main.adb")
13015           use ("^-s^-s^",
13016                "^-g^-g^");
13017    end Builder;
13018 end Proj4;
13019 @end group
13020
13021 @group
13022 -- Ada source file:
13023 with Pack;
13024 procedure Foo_Main is
13025    ...
13026 end Foo_Main;
13027 @end group
13028 @end smallexample
13029
13030 If the command is
13031 @smallexample
13032 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13033 @end smallexample
13034
13035 @noindent
13036 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13037 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13038 @option{^-gnato^-gnato^} (passed on the command line).
13039 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13040 are @option{^-g^-g^} from @code{Proj4.Builder},
13041 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13042 and @option{^-gnato^-gnato^} from the command line.
13043
13044 @noindent
13045 When using @command{gnatmake} with project files, some ^switches^switches^ or
13046 arguments may be expressed as relative paths. As the working directory where
13047 compilation occurs may change, these relative paths are converted to absolute
13048 paths. For the ^switches^switches^ found in a project file, the relative paths
13049 are relative to the project file directory, for the switches on the command
13050 line, they are relative to the directory where @command{gnatmake} is invoked.
13051 The ^switches^switches^ for which this occurs are:
13052 ^-I^-I^,
13053 ^-A^-A^,
13054 ^-L^-L^,
13055 ^-aO^-aO^,
13056 ^-aL^-aL^,
13057 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13058 ^switch^switch^
13059 ^-o^-o^, object files specified in package @code{Linker} or after
13060 -largs on the command line). The exception to this rule is the ^switch^switch^
13061 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13062
13063 @node Specifying Configuration Pragmas
13064 @subsubsection Specifying Configuration Pragmas
13065
13066 When using @command{gnatmake} with project files, if there exists a file
13067 @file{gnat.adc} that contains configuration pragmas, this file will be
13068 ignored.
13069
13070 Configuration pragmas can be defined by means of the following attributes in
13071 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13072 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13073
13074 Both these attributes are single string attributes. Their values is the path
13075 name of a file containing configuration pragmas. If a path name is relative,
13076 then it is relative to the project directory of the project file where the
13077 attribute is defined.
13078
13079 When compiling a source, the configuration pragmas used are, in order,
13080 those listed in the file designated by attribute
13081 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13082 project file, if it is specified, and those listed in the file designated by
13083 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13084 the project file of the source, if it exists.
13085
13086 @node Project Files and Main Subprograms
13087 @subsubsection Project Files and Main Subprograms
13088
13089 @noindent
13090 When using a project file, you can invoke @command{gnatmake}
13091 with one or several main subprograms, by specifying their source files on the
13092 command line.
13093
13094 @smallexample
13095     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13096 @end smallexample
13097
13098 @noindent
13099 Each of these needs to be a source file of the same project, except
13100 when the switch ^-u^/UNIQUE^ is used.
13101
13102 @noindent
13103 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13104 same project, one of the project in the tree rooted at the project specified
13105 on the command line. The package @code{Builder} of this common project, the
13106 "main project" is the one that is considered by @command{gnatmake}.
13107
13108 @noindent
13109 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13110 imported directly or indirectly by the project specified on the command line.
13111 Note that if such a source file is not part of the project specified on the
13112 command line, the ^switches^switches^ found in package @code{Builder} of the
13113 project specified on the command line, if any, that are transmitted
13114 to the compiler will still be used, not those found in the project file of
13115 the source file.
13116
13117 @noindent
13118 When using a project file, you can also invoke @command{gnatmake} without
13119 explicitly specifying any main, and the effect depends on whether you have
13120 defined the @code{Main} attribute.  This attribute has a string list value,
13121 where each element in the list is the name of a source file (the file
13122 extension is optional) that contains a unit that can be a main subprogram.
13123
13124 If the @code{Main} attribute is defined in a project file as a non-empty
13125 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13126 line, then invoking @command{gnatmake} with this project file but without any
13127 main on the command line is equivalent to invoking @command{gnatmake} with all
13128 the file names in the @code{Main} attribute on the command line.
13129
13130 Example:
13131 @smallexample @c projectfile
13132 @group
13133    project Prj is
13134       for Main use ("main1", "main2", "main3");
13135    end Prj;
13136 @end group
13137 @end smallexample
13138
13139 @noindent
13140 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13141 is equivalent to
13142 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13143
13144 When the project attribute @code{Main} is not specified, or is specified
13145 as an empty string list, or when the switch @option{-u} is used on the command
13146 line, then invoking @command{gnatmake} with no main on the command line will
13147 result in all immediate sources of the project file being checked, and
13148 potentially recompiled. Depending on the presence of the switch @option{-u},
13149 sources from other project files on which the immediate sources of the main
13150 project file depend are also checked and potentially recompiled. In other
13151 words, the @option{-u} switch is applied to all of the immediate sources of the
13152 main project file.
13153
13154 When no main is specified on the command line and attribute @code{Main} exists
13155 and includes several mains, or when several mains are specified on the
13156 command line, the default ^switches^switches^ in package @code{Builder} will
13157 be used for all mains, even if there are specific ^switches^switches^
13158 specified for one or several mains.
13159
13160 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13161 the specific ^switches^switches^ for each main, if they are specified.
13162
13163 @node Library Project Files
13164 @subsubsection Library Project Files
13165
13166 @noindent
13167 When @command{gnatmake} is invoked with a main project file that is a library
13168 project file, it is not allowed to specify one or more mains on the command
13169 line.
13170
13171 @noindent
13172 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13173 ^-l^/ACTION=LINK^ have special meanings.
13174
13175 @itemize @bullet
13176 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13177 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13178 library.
13179
13180 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13181 to @command{gnatmake} that the binder generated file should be compiled
13182 (in the case of a stand-alone library) and that the library should be built.
13183
13184 @end itemize
13185
13186 @node The GNAT Driver and Project Files
13187 @subsection The GNAT Driver and Project Files
13188
13189 @noindent
13190 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13191 are project-aware:
13192 @command{^gnatbind^gnatbind^},
13193 @command{^gnatfind^gnatfind^},
13194 @command{^gnatlink^gnatlink^},
13195 @command{^gnatls^gnatls^},
13196 @command{^gnatelim^gnatelim^},
13197 @command{^gnatpp^gnatpp^},
13198 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13199 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13200 They must be invoked through the @command{gnat} driver.
13201
13202 The @command{gnat} driver is a front-end that accepts a number of commands and
13203 call the corresponding tool. It has been designed initially for VMS to convert
13204 VMS style qualifiers to Unix style switches, but it is now available to all
13205 the GNAT supported platforms.
13206
13207 On non VMS platforms, the @command{gnat} driver accepts the following commands
13208 (case insensitive):
13209
13210 @itemize @bullet
13211 @item
13212 BIND to invoke @command{^gnatbind^gnatbind^}
13213 @item
13214 CHOP to invoke @command{^gnatchop^gnatchop^}
13215 @item
13216 CLEAN to invoke @command{^gnatclean^gnatclean^}
13217 @item
13218 COMP or COMPILE to invoke the compiler
13219 @item
13220 ELIM to invoke @command{^gnatelim^gnatelim^}
13221 @item
13222 FIND to invoke @command{^gnatfind^gnatfind^}
13223 @item
13224 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13225 @item
13226 LINK to invoke @command{^gnatlink^gnatlink^}
13227 @item
13228 LS or LIST to invoke @command{^gnatls^gnatls^}
13229 @item
13230 MAKE to invoke @command{^gnatmake^gnatmake^}
13231 @item
13232 NAME to invoke @command{^gnatname^gnatname^}
13233 @item
13234 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13235 @item
13236 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13237 @item
13238 STUB to invoke @command{^gnatstub^gnatstub^}
13239 @item
13240 XREF to invoke @command{^gnatxref^gnatxref^}
13241 @end itemize
13242
13243 @noindent
13244 (note that the compiler is invoked using the command
13245 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13246
13247 @noindent
13248 On non VMS platforms, between @command{gnat} and the command, two
13249 special switches may be used:
13250
13251 @itemize @bullet
13252 @item
13253 @command{-v} to display the invocation of the tool.
13254 @item
13255 @command{-dn} to prevent the @command{gnat} driver from removing
13256 the temporary files it has created. These temporary files are
13257 configuration files and temporary file list files.
13258 @end itemize
13259
13260 @noindent
13261 The command may be followed by switches and arguments for the invoked
13262 tool.
13263
13264 @smallexample
13265   gnat bind -C main.ali
13266   gnat ls -a main
13267   gnat chop foo.txt
13268 @end smallexample
13269
13270 @noindent
13271 Switches may also be put in text files, one switch per line, and the text
13272 files may be specified with their path name preceded by '@@'.
13273
13274 @smallexample
13275    gnat bind @@args.txt main.ali
13276 @end smallexample
13277
13278 @noindent
13279 In addition, for command BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13280 PP or PRETTY and XREF, the project file related switches
13281 (@option{^-P^/PROJECT_FILE^},
13282 @option{^-X^/EXTERNAL_REFERENCE^} and
13283 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13284 the switches of the invoking tool.
13285
13286 @noindent
13287 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13288 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13289 the immediate sources of the specified project file.
13290
13291 @noindent
13292 For each of these commands, there is optionally a corresponding  package
13293 in the main project.
13294
13295 @itemize @bullet
13296 @item
13297 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13298
13299 @item
13300 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13301
13302 @item
13303 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13304
13305 @item
13306 package @code{Eliminate} for command ELIM (invoking
13307 @code{^gnatelim^gnatelim^})
13308
13309 @item
13310 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13311
13312 @item
13313 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13314
13315 @item
13316 package @code{Pretty_Printer} for command PP or PRETTY
13317 (invoking @code{^gnatpp^gnatpp^})
13318
13319 @item
13320 package @code{Cross_Reference} for command XREF (invoking
13321 @code{^gnatxref^gnatxref^})
13322
13323 @end itemize
13324
13325 @noindent
13326 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13327 a simple variable with a string list value. It contains ^switches^switches^
13328 for the invocation of @code{^gnatls^gnatls^}.
13329
13330 @smallexample @c projectfile
13331 @group
13332 project Proj1 is
13333    package gnatls is
13334       for ^Switches^Switches^
13335           use ("^-a^-a^",
13336                "^-v^-v^");
13337    end gnatls;
13338 end Proj1;
13339 @end group
13340 @end smallexample
13341
13342 @noindent
13343 All other packages have two attribute @code{^Switches^Switches^} and
13344 @code{^Default_Switches^Default_Switches^}.
13345
13346 @noindent
13347 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13348 source file name, that has a string list value: the ^switches^switches^ to be
13349 used when the tool corresponding to the package is invoked for the specific
13350 source file.
13351
13352 @noindent
13353 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13354 indexed by  the programming language that has a string list value.
13355 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13356 ^switches^switches^ for the invocation of the tool corresponding
13357 to the package, except if a specific @code{^Switches^Switches^} attribute
13358 is specified for the source file.
13359
13360 @smallexample @c projectfile
13361 @group
13362 project Proj is
13363
13364    for Source_Dirs use ("./**");
13365
13366    package gnatls is
13367       for ^Switches^Switches^ use
13368           ("^-a^-a^",
13369            "^-v^-v^");
13370    end gnatls;
13371 @end group
13372 @group
13373
13374    package Compiler is
13375       for ^Default_Switches^Default_Switches^ ("Ada")
13376           use ("^-gnatv^-gnatv^",
13377                "^-gnatwa^-gnatwa^");
13378    end Binder;
13379 @end group
13380 @group
13381
13382    package Binder is
13383       for ^Default_Switches^Default_Switches^ ("Ada")
13384           use ("^-C^-C^",
13385                "^-e^-e^");
13386    end Binder;
13387 @end group
13388 @group
13389
13390    package Linker is
13391       for ^Default_Switches^Default_Switches^ ("Ada")
13392           use ("^-C^-C^");
13393       for ^Switches^Switches^ ("main.adb")
13394           use ("^-C^-C^",
13395                "^-v^-v^",
13396                "^-v^-v^");
13397    end Linker;
13398 @end group
13399 @group
13400
13401    package Finder is
13402       for ^Default_Switches^Default_Switches^ ("Ada")
13403            use ("^-a^-a^",
13404                 "^-f^-f^");
13405    end Finder;
13406 @end group
13407 @group
13408
13409    package Cross_Reference is
13410       for ^Default_Switches^Default_Switches^ ("Ada")
13411           use ("^-a^-a^",
13412                "^-f^-f^",
13413                "^-d^-d^",
13414                "^-u^-u^");
13415    end Cross_Reference;
13416 end Proj;
13417 @end group
13418 @end smallexample
13419
13420 @noindent
13421 With the above project file, commands such as
13422
13423 @smallexample
13424    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13425    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13426    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13427    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13428    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13429 @end smallexample
13430
13431 @noindent
13432 will set up the environment properly and invoke the tool with the switches
13433 found in the package corresponding to the tool:
13434 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13435 except @code{^Switches^Switches^ ("main.adb")}
13436 for @code{^gnatlink^gnatlink^}.
13437
13438 @ifclear vms
13439 @node Glide and Project Files
13440 @subsection Glide and Project Files
13441
13442 @noindent
13443 Glide will automatically recognize the @file{.gpr} extension for
13444 project files, and will
13445 convert them to its own internal format automatically. However, it
13446 doesn't provide a syntax-oriented editor for modifying these
13447 files.
13448 The project file will be loaded as text when you select the menu item
13449 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13450 You can edit this text and save the @file{gpr} file;
13451 when you next select this project file in Glide it
13452 will be automatically reloaded.
13453 @end ifclear
13454
13455 @c **********************
13456 @node An Extended Example
13457 @section An Extended Example
13458
13459 @noindent
13460 Suppose that we have two programs, @var{prog1} and @var{prog2},
13461 whose sources are in corresponding directories. We would like
13462 to build them with a single @command{gnatmake} command, and we want to place
13463 their object files into @file{build} subdirectories of the source directories.
13464 Furthermore, we want to have to have two separate subdirectories
13465 in @file{build}  -- @file{release} and @file{debug} -- which will contain
13466 the object files compiled with different set of compilation flags.
13467
13468 In other words, we have the following structure:
13469
13470 @smallexample
13471 @group
13472    main
13473      |- prog1
13474      |    |- build
13475      |         | debug
13476      |         | release
13477      |- prog2
13478           |- build
13479                | debug
13480                | release
13481 @end group
13482 @end smallexample
13483
13484 @noindent
13485 Here are the project files that we must place in a directory @file{main}
13486 to maintain this structure:
13487
13488 @enumerate
13489
13490 @item We create a @code{Common} project with a package @code{Compiler} that
13491 specifies the compilation ^switches^switches^:
13492
13493 @smallexample
13494 File "common.gpr":
13495 @group
13496 @b{project} Common @b{is}
13497
13498    @b{for} Source_Dirs @b{use} (); -- No source files
13499 @end group
13500
13501 @group
13502    @b{type} Build_Type @b{is} ("release", "debug");
13503    Build : Build_Type := External ("BUILD", "debug");
13504 @end group
13505 @group
13506    @b{package} Compiler @b{is}
13507       @b{case} Build @b{is}
13508          @b{when} "release" =>
13509            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13510                    @b{use} ("^-O2^-O2^");
13511          @b{when} "debug"   =>
13512            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13513                    @b{use} ("^-g^-g^");
13514       @b{end case};
13515    @b{end} Compiler;
13516
13517 @b{end} Common;
13518 @end group
13519 @end smallexample
13520
13521 @item We create separate projects for the two programs:
13522
13523 @smallexample
13524 @group
13525 File "prog1.gpr":
13526
13527 @b{with} "common";
13528 @b{project} Prog1 @b{is}
13529
13530     @b{for} Source_Dirs @b{use} ("prog1");
13531     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
13532
13533     @b{package} Compiler @b{renames} Common.Compiler;
13534
13535 @b{end} Prog1;
13536 @end group
13537 @end smallexample
13538
13539 @smallexample
13540 @group
13541 File "prog2.gpr":
13542
13543 @b{with} "common";
13544 @b{project} Prog2 @b{is}
13545
13546     @b{for} Source_Dirs @b{use} ("prog2");
13547     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
13548
13549     @b{package} Compiler @b{renames} Common.Compiler;
13550
13551 @end group
13552 @b{end} Prog2;
13553 @end smallexample
13554
13555 @item We create a wrapping project @code{Main}:
13556
13557 @smallexample
13558 @group
13559 File "main.gpr":
13560
13561 @b{with} "common";
13562 @b{with} "prog1";
13563 @b{with} "prog2";
13564 @b{project} Main @b{is}
13565
13566    @b{package} Compiler @b{renames} Common.Compiler;
13567
13568 @b{end} Main;
13569 @end group
13570 @end smallexample
13571
13572 @item Finally we need to create a dummy procedure that @code{with}s (either
13573 explicitly or implicitly) all the sources of our two programs.
13574
13575 @end enumerate
13576
13577 @noindent
13578 Now we can build the programs using the command
13579
13580 @smallexample
13581    gnatmake ^-P^/PROJECT_FILE=^main dummy
13582 @end smallexample
13583
13584 @noindent
13585 for the Debug mode, or
13586
13587 @ifclear vms
13588 @smallexample
13589    gnatmake -Pmain -XBUILD=release
13590 @end smallexample
13591 @end ifclear
13592
13593 @ifset vms
13594 @smallexample
13595    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13596 @end smallexample
13597 @end ifset
13598
13599 @noindent
13600 for the Release mode.
13601
13602 @c ********************************
13603 @c * Project File Complete Syntax *
13604 @c ********************************
13605
13606 @node Project File Complete Syntax
13607 @section Project File Complete Syntax
13608
13609 @smallexample
13610 project ::=
13611   context_clause project_declaration
13612
13613 context_clause ::=
13614   @{with_clause@}
13615
13616 with_clause ::=
13617   @b{with} path_name @{ , path_name @} ;
13618
13619 path_name ::=
13620    string_literal
13621
13622 project_declaration ::=
13623   simple_project_declaration | project_extension
13624
13625 simple_project_declaration ::=
13626   @b{project} <project_>simple_name @b{is}
13627     @{declarative_item@}
13628   @b{end} <project_>simple_name;
13629
13630 project_extension ::=
13631   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
13632     @{declarative_item@}
13633   @b{end} <project_>simple_name;
13634
13635 declarative_item ::=
13636   package_declaration |
13637   typed_string_declaration |
13638   other_declarative_item
13639
13640 package_declaration ::=
13641   package_specification | package_renaming
13642
13643 package_specification ::=
13644   @b{package} package_identifier @b{is}
13645     @{simple_declarative_item@}
13646   @b{end} package_identifier ;
13647
13648 package_identifier ::=
13649   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13650   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
13651   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
13652
13653 package_renaming ::==
13654   @b{package} package_identifier @b{renames}
13655        <project_>simple_name.package_identifier ;
13656
13657 typed_string_declaration ::=
13658   @b{type} <typed_string_>_simple_name @b{is}
13659    ( string_literal @{, string_literal@} );
13660
13661 other_declarative_item ::=
13662   attribute_declaration |
13663   typed_variable_declaration |
13664   variable_declaration |
13665   case_construction
13666
13667 attribute_declaration ::=
13668   full_associative_array_declaration |
13669   @b{for} attribute_designator @b{use} expression ;
13670
13671 full_associative_array_declaration ::=
13672   @b{for} <associative_array_attribute_>simple_name @b{use}
13673   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13674
13675 attribute_designator ::=
13676   <simple_attribute_>simple_name |
13677   <associative_array_attribute_>simple_name ( string_literal )
13678
13679 typed_variable_declaration ::=
13680   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
13681
13682 variable_declaration ::=
13683   <variable_>simple_name := expression;
13684
13685 expression ::=
13686   term @{& term@}
13687
13688 term ::=
13689   literal_string |
13690   string_list |
13691   <variable_>name |
13692   external_value |
13693   attribute_reference
13694
13695 string_literal ::=
13696   (same as Ada)
13697
13698 string_list ::=
13699   ( <string_>expression @{ , <string_>expression @} )
13700
13701 external_value ::=
13702   @b{external} ( string_literal [, string_literal] )
13703
13704 attribute_reference ::=
13705   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
13706
13707 attribute_prefix ::=
13708   @b{project} |
13709   <project_>simple_name | package_identifier |
13710   <project_>simple_name . package_identifier
13711
13712 case_construction ::=
13713   @b{case} <typed_variable_>name @b{is}
13714     @{case_item@}
13715   @b{end case} ;
13716
13717 case_item ::=
13718   @b{when} discrete_choice_list =>
13719       @{case_construction | attribute_declaration@}
13720
13721 discrete_choice_list ::=
13722   string_literal @{| string_literal@} |
13723   @b{others}
13724
13725 name ::=
13726   simple_name @{. simple_name@}
13727
13728 simple_name ::=
13729   identifier (same as Ada)
13730
13731 @end smallexample
13732
13733
13734 @node The Cross-Referencing Tools gnatxref and gnatfind
13735 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13736 @findex gnatxref
13737 @findex gnatfind
13738
13739 @noindent
13740 The compiler generates cross-referencing information (unless
13741 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13742 This information indicates where in the source each entity is declared and
13743 referenced. Note that entities in package Standard are not included, but
13744 entities in all other predefined units are included in the output.
13745
13746 Before using any of these two tools, you need to compile successfully your
13747 application, so that GNAT gets a chance to generate the cross-referencing
13748 information.
13749
13750 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13751 information to provide the user with the capability to easily locate the
13752 declaration and references to an entity. These tools are quite similar,
13753 the difference being that @code{gnatfind} is intended for locating
13754 definitions and/or references to a specified entity or entities, whereas
13755 @code{gnatxref} is oriented to generating a full report of all
13756 cross-references.
13757
13758 To use these tools, you must not compile your application using the
13759 @option{-gnatx} switch on the @file{gnatmake} command line
13760 (see @ref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13761 information will not be generated.
13762
13763 @menu
13764 * gnatxref Switches::
13765 * gnatfind Switches::
13766 * Project Files for gnatxref and gnatfind::
13767 * Regular Expressions in gnatfind and gnatxref::
13768 * Examples of gnatxref Usage::
13769 * Examples of gnatfind Usage::
13770 @end menu
13771
13772 @node gnatxref Switches
13773 @section @code{gnatxref} Switches
13774
13775 @noindent
13776 The command invocation for @code{gnatxref} is:
13777 @smallexample
13778 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13779 @end smallexample
13780
13781 @noindent
13782 where
13783
13784 @table @code
13785 @item sourcefile1, sourcefile2
13786 identifies the source files for which a report is to be generated. The
13787 ``with''ed units will be processed too. You must provide at least one file.
13788
13789 These file names are considered to be regular expressions, so for instance
13790 specifying @file{source*.adb} is the same as giving every file in the current
13791 directory whose name starts with @file{source} and whose extension is
13792 @file{adb}.
13793
13794 You shouldn't specify any directory name, just base names. @command{gnatxref}
13795 and @command{gnatfind} will be able to locate these files by themselves using
13796 the source path. If you specify directories, no result is produced.
13797
13798 @end table
13799
13800 @noindent
13801 The switches can be :
13802 @table @option
13803 @c !sort!
13804 @item ^-a^/ALL_FILES^
13805 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13806 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13807 the read-only files found in the library search path. Otherwise, these files
13808 will be ignored. This option can be used to protect Gnat sources or your own
13809 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13810 much faster, and their output much smaller. Read-only here refers to access
13811 or permissions status in the file system for the current user.
13812
13813 @item -aIDIR
13814 @cindex @option{-aIDIR} (@command{gnatxref})
13815 When looking for source files also look in directory DIR. The order in which
13816 source file search is undertaken is the same as for @file{gnatmake}.
13817
13818 @item -aODIR
13819 @cindex @option{-aODIR} (@command{gnatxref})
13820 When searching for library and object files, look in directory
13821 DIR. The order in which library files are searched is the same as for
13822 @file{gnatmake}.
13823
13824 @item -nostdinc
13825 @cindex @option{-nostdinc} (@command{gnatxref})
13826 Do not look for sources in the system default directory.
13827
13828 @item -nostdlib
13829 @cindex @option{-nostdlib} (@command{gnatxref})
13830 Do not look for library files in the system default directory.
13831
13832 @item --RTS=@var{rts-path}
13833 @cindex @option{--RTS} (@command{gnatxref})
13834 Specifies the default location of the runtime library. Same meaning as the
13835 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13836
13837 @item ^-d^/DERIVED_TYPES^
13838 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13839 If this switch is set @code{gnatxref} will output the parent type
13840 reference for each matching derived types.
13841
13842 @item ^-f^/FULL_PATHNAME^
13843 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13844 If this switch is set, the output file names will be preceded by their
13845 directory (if the file was found in the search path). If this switch is
13846 not set, the directory will not be printed.
13847
13848 @item ^-g^/IGNORE_LOCALS^
13849 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13850 If this switch is set, information is output only for library-level
13851 entities, ignoring local entities. The use of this switch may accelerate
13852 @code{gnatfind} and @code{gnatxref}.
13853
13854 @item -IDIR
13855 @cindex @option{-IDIR} (@command{gnatxref})
13856 Equivalent to @samp{-aODIR -aIDIR}.
13857
13858 @item -pFILE
13859 @cindex @option{-pFILE} (@command{gnatxref})
13860 Specify a project file to use @xref{Project Files}. These project files are
13861 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
13862 project files, you should use gnatxref through the GNAT driver
13863 (@command{gnat xref -Pproject}).
13864
13865 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13866 project file in the current directory.
13867
13868 If a project file is either specified or found by the tools, then the content
13869 of the source directory and object directory lines are added as if they
13870 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13871 and @samp{^-aO^OBJECT_SEARCH^}.
13872 @item ^-u^/UNUSED^
13873 Output only unused symbols. This may be really useful if you give your
13874 main compilation unit on the command line, as @code{gnatxref} will then
13875 display every unused entity and 'with'ed package.
13876
13877 @ifclear vms
13878 @item -v
13879 Instead of producing the default output, @code{gnatxref} will generate a
13880 @file{tags} file that can be used by vi. For examples how to use this
13881 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
13882 to the standard output, thus you will have to redirect it to a file.
13883 @end ifclear
13884
13885 @end table
13886
13887 @noindent
13888 All these switches may be in any order on the command line, and may even
13889 appear after the file names. They need not be separated by spaces, thus
13890 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13891 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13892
13893 @node gnatfind Switches
13894 @section @code{gnatfind} Switches
13895
13896 @noindent
13897 The command line for @code{gnatfind} is:
13898
13899 @smallexample
13900 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
13901       [file1 file2 ...]
13902 @end smallexample
13903
13904 @noindent
13905 where
13906
13907 @table @code
13908 @item pattern
13909 An entity will be output only if it matches the regular expression found
13910 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
13911
13912 Omitting the pattern is equivalent to specifying @samp{*}, which
13913 will match any entity. Note that if you do not provide a pattern, you
13914 have to provide both a sourcefile and a line.
13915
13916 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13917 for matching purposes. At the current time there is no support for
13918 8-bit codes other than Latin-1, or for wide characters in identifiers.
13919
13920 @item sourcefile
13921 @code{gnatfind} will look for references, bodies or declarations
13922 of symbols referenced in @file{sourcefile}, at line @samp{line}
13923 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
13924 for syntax examples.
13925
13926 @item line
13927 is a decimal integer identifying the line number containing
13928 the reference to the entity (or entities) to be located.
13929
13930 @item column
13931 is a decimal integer identifying the exact location on the
13932 line of the first character of the identifier for the
13933 entity reference. Columns are numbered from 1.
13934
13935 @item file1 file2 ...
13936 The search will be restricted to these source files. If none are given, then
13937 the search will be done for every library file in the search path.
13938 These file must appear only after the pattern or sourcefile.
13939
13940 These file names are considered to be regular expressions, so for instance
13941 specifying 'source*.adb' is the same as giving every file in the current
13942 directory whose name starts with 'source' and whose extension is 'adb'.
13943
13944 The location of the spec of the entity will always be displayed, even if it
13945 isn't in one of file1, file2,... The occurrences of the entity in the
13946 separate units of the ones given on the command line will also be displayed.
13947
13948 Note that if you specify at least one file in this part, @code{gnatfind} may
13949 sometimes not be able to find the body of the subprograms...
13950
13951 @end table
13952
13953 @noindent
13954 At least one of 'sourcefile' or 'pattern' has to be present on
13955 the command line.
13956
13957 The following switches are available:
13958 @table @option
13959 @c !sort!
13960
13961 @item ^-a^/ALL_FILES^
13962 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13963 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13964 the read-only files found in the library search path. Otherwise, these files
13965 will be ignored. This option can be used to protect Gnat sources or your own
13966 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13967 much faster, and their output much smaller. Read-only here refers to access
13968 or permission status in the file system for the current user.
13969
13970 @item -aIDIR
13971 @cindex @option{-aIDIR} (@command{gnatfind})
13972 When looking for source files also look in directory DIR. The order in which
13973 source file search is undertaken is the same as for @file{gnatmake}.
13974
13975 @item -aODIR
13976 @cindex @option{-aODIR} (@command{gnatfind})
13977 When searching for library and object files, look in directory
13978 DIR. The order in which library files are searched is the same as for
13979 @file{gnatmake}.
13980
13981 @item -nostdinc
13982 @cindex @option{-nostdinc} (@command{gnatfind})
13983 Do not look for sources in the system default directory.
13984
13985 @item -nostdlib
13986 @cindex @option{-nostdlib} (@command{gnatfind})
13987 Do not look for library files in the system default directory.
13988
13989 @item --RTS=@var{rts-path}
13990 @cindex @option{--RTS} (@command{gnatfind})
13991 Specifies the default location of the runtime library. Same meaning as the
13992 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13993
13994 @item ^-d^/DERIVED_TYPE_INFORMATION^
13995 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13996 If this switch is set, then @code{gnatfind} will output the parent type
13997 reference for each matching derived types.
13998
13999 @item ^-e^/EXPRESSIONS^
14000 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14001 By default, @code{gnatfind} accept the simple regular expression set for
14002 @samp{pattern}. If this switch is set, then the pattern will be
14003 considered as full Unix-style regular expression.
14004
14005 @item ^-f^/FULL_PATHNAME^
14006 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14007 If this switch is set, the output file names will be preceded by their
14008 directory (if the file was found in the search path). If this switch is
14009 not set, the directory will not be printed.
14010
14011 @item ^-g^/IGNORE_LOCALS^
14012 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14013 If this switch is set, information is output only for library-level
14014 entities, ignoring local entities. The use of this switch may accelerate
14015 @code{gnatfind} and @code{gnatxref}.
14016
14017 @item -IDIR
14018 @cindex @option{-IDIR} (@command{gnatfind})
14019 Equivalent to @samp{-aODIR -aIDIR}.
14020
14021 @item -pFILE
14022 @cindex @option{-pFILE} (@command{gnatfind})
14023 Specify a project file (@pxref{Project Files}) to use.
14024 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14025 project file in the current directory.
14026
14027 If a project file is either specified or found by the tools, then the content
14028 of the source directory and object directory lines are added as if they
14029 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14030 @samp{^-aO^/OBJECT_SEARCH^}.
14031
14032 @item ^-r^/REFERENCES^
14033 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14034 By default, @code{gnatfind} will output only the information about the
14035 declaration, body or type completion of the entities. If this switch is
14036 set, the @code{gnatfind} will locate every reference to the entities in
14037 the files specified on the command line (or in every file in the search
14038 path if no file is given on the command line).
14039
14040 @item ^-s^/PRINT_LINES^
14041 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14042 If this switch is set, then @code{gnatfind} will output the content
14043 of the Ada source file lines were the entity was found.
14044
14045 @item ^-t^/TYPE_HIERARCHY^
14046 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14047 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14048 the specified type. It act like -d option but recursively from parent
14049 type to parent type. When this switch is set it is not possible to
14050 specify more than one file.
14051
14052 @end table
14053
14054 @noindent
14055 All these switches may be in any order on the command line, and may even
14056 appear after the file names. They need not be separated by spaces, thus
14057 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14058 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14059
14060 As stated previously, gnatfind will search in every directory in the
14061 search path. You can force it to look only in the current directory if
14062 you specify @code{*} at the end of the command line.
14063
14064 @node Project Files for gnatxref and gnatfind
14065 @section Project Files for @command{gnatxref} and @command{gnatfind}
14066
14067 @noindent
14068 Project files allow a programmer to specify how to compile its
14069 application, where to find sources, etc.  These files are used
14070 @ifclear vms
14071 primarily by the Glide Ada mode, but they can also be used
14072 @end ifclear
14073 by the two tools
14074 @code{gnatxref} and @code{gnatfind}.
14075
14076 A project file name must end with @file{.gpr}. If a single one is
14077 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14078 extract the information from it. If multiple project files are found, none of
14079 them is read, and you have to use the @samp{-p} switch to specify the one
14080 you want to use.
14081
14082 The following lines can be included, even though most of them have default
14083 values which can be used in most cases.
14084 The lines can be entered in any order in the file.
14085 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14086 each line. If you have multiple instances, only the last one is taken into
14087 account.
14088
14089 @table @code
14090 @item src_dir=DIR
14091 [default: @code{"^./^[]^"}]
14092 specifies a directory where to look for source files. Multiple @code{src_dir}
14093 lines can be specified and they will be searched in the order they
14094 are specified.
14095
14096 @item obj_dir=DIR
14097 [default: @code{"^./^[]^"}]
14098 specifies a directory where to look for object and library files. Multiple
14099 @code{obj_dir} lines can be specified, and they will be searched in the order
14100 they are specified
14101
14102 @item comp_opt=SWITCHES
14103 [default: @code{""}]
14104 creates a variable which can be referred to subsequently by using
14105 the @code{$@{comp_opt@}} notation. This is intended to store the default
14106 switches given to @command{gnatmake} and @command{gcc}.
14107
14108 @item bind_opt=SWITCHES
14109 [default: @code{""}]
14110 creates a variable which can be referred to subsequently by using
14111 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14112 switches given to @command{gnatbind}.
14113
14114 @item link_opt=SWITCHES
14115 [default: @code{""}]
14116 creates a variable which can be referred to subsequently by using
14117 the @samp{$@{link_opt@}} notation. This is intended to store the default
14118 switches given to @command{gnatlink}.
14119
14120 @item main=EXECUTABLE
14121 [default: @code{""}]
14122 specifies the name of the executable for the application. This variable can
14123 be referred to in the following lines by using the @samp{$@{main@}} notation.
14124
14125 @ifset vms
14126 @item comp_cmd=COMMAND
14127 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14128 @end ifset
14129 @ifclear vms
14130 @item comp_cmd=COMMAND
14131 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14132 @end ifclear
14133 specifies the command used to compile a single file in the application.
14134
14135 @ifset vms
14136 @item make_cmd=COMMAND
14137 [default: @code{"GNAT MAKE $@{main@}
14138 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14139 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14140 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14141 @end ifset
14142 @ifclear vms
14143 @item make_cmd=COMMAND
14144 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14145  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14146  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14147 @end ifclear
14148 specifies the command used to recompile the whole application.
14149
14150 @item run_cmd=COMMAND
14151 [default: @code{"$@{main@}"}]
14152 specifies the command used to run the application.
14153
14154 @item debug_cmd=COMMAND
14155 [default: @code{"gdb $@{main@}"}]
14156 specifies the command used to debug the application
14157
14158 @end table
14159
14160 @noindent
14161 @command{gnatxref} and @command{gnatfind} only take into account the
14162 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14163
14164 @node Regular Expressions in gnatfind and gnatxref
14165 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
14166
14167 @noindent
14168 As specified in the section about @command{gnatfind}, the pattern can be a
14169 regular expression. Actually, there are to set of regular expressions
14170 which are recognized by the program :
14171
14172 @table @code
14173 @item globbing patterns
14174 These are the most usual regular expression. They are the same that you
14175 generally used in a Unix shell command line, or in a DOS session.
14176
14177 Here is a more formal grammar :
14178 @smallexample
14179 @group
14180 @iftex
14181 @leftskip=.5cm
14182 @end iftex
14183 regexp ::= term
14184 term   ::= elmt            -- matches elmt
14185 term   ::= elmt elmt       -- concatenation (elmt then elmt)
14186 term   ::= *               -- any string of 0 or more characters
14187 term   ::= ?               -- matches any character
14188 term   ::= [char @{char@}] -- matches any character listed
14189 term   ::= [char - char]   -- matches any character in range
14190 @end group
14191 @end smallexample
14192
14193 @item full regular expression
14194 The second set of regular expressions is much more powerful. This is the
14195 type of regular expressions recognized by utilities such a @file{grep}.
14196
14197 The following is the form of a regular expression, expressed in Ada
14198 reference manual style BNF is as follows
14199
14200 @smallexample
14201 @iftex
14202 @leftskip=.5cm
14203 @end iftex
14204 @group
14205 regexp ::= term @{| term@} -- alternation (term or term ...)
14206
14207 term ::= item @{item@}     -- concatenation (item then item)
14208
14209 item ::= elmt              -- match elmt
14210 item ::= elmt *            -- zero or more elmt's
14211 item ::= elmt +            -- one or more elmt's
14212 item ::= elmt ?            -- matches elmt or nothing
14213 @end group
14214 @group
14215 elmt ::= nschar            -- matches given character
14216 elmt ::= [nschar @{nschar@}]   -- matches any character listed
14217 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14218 elmt ::= [char - char]     -- matches chars in given range
14219 elmt ::= \ char            -- matches given character
14220 elmt ::= .                 -- matches any single character
14221 elmt ::= ( regexp )        -- parens used for grouping
14222
14223 char ::= any character, including special characters
14224 nschar ::= any character except ()[].*+?^^^
14225 @end group
14226 @end smallexample
14227
14228 Following are a few examples :
14229
14230 @table @samp
14231 @item abcde|fghi
14232 will match any of the two strings 'abcde' and 'fghi'.
14233
14234 @item abc*d
14235 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14236
14237 @item [a-z]+
14238 will match any string which has only lowercase characters in it (and at
14239 least one character
14240
14241 @end table
14242 @end table
14243
14244 @node Examples of gnatxref Usage
14245 @section Examples of @code{gnatxref} Usage
14246
14247 @subsection General Usage
14248
14249 @noindent
14250 For the following examples, we will consider the following units :
14251
14252 @smallexample @c ada
14253 @group
14254 @cartouche
14255 main.ads:
14256 1: with Bar;
14257 2: package Main is
14258 3:     procedure Foo (B : in Integer);
14259 4:     C : Integer;
14260 5: private
14261 6:     D : Integer;
14262 7: end Main;
14263
14264 main.adb:
14265 1: package body Main is
14266 2:     procedure Foo (B : in Integer) is
14267 3:     begin
14268 4:        C := B;
14269 5:        D := B;
14270 6:        Bar.Print (B);
14271 7:        Bar.Print (C);
14272 8:     end Foo;
14273 9: end Main;
14274
14275 bar.ads:
14276 1: package Bar is
14277 2:     procedure Print (B : Integer);
14278 3: end bar;
14279 @end cartouche
14280 @end group
14281 @end smallexample
14282
14283 @table @code
14284
14285 @noindent
14286 The first thing to do is to recompile your application (for instance, in
14287 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14288 the cross-referencing information.
14289 You can then issue any of the following commands:
14290
14291 @item gnatxref main.adb
14292 @code{gnatxref} generates cross-reference information for main.adb
14293 and every unit 'with'ed by main.adb.
14294
14295 The output would be:
14296 @smallexample
14297 @iftex
14298 @leftskip=0cm
14299 @end iftex
14300 B                                                      Type: Integer
14301   Decl: bar.ads           2:22
14302 B                                                      Type: Integer
14303   Decl: main.ads          3:20
14304   Body: main.adb          2:20
14305   Ref:  main.adb          4:13     5:13     6:19
14306 Bar                                                    Type: Unit
14307   Decl: bar.ads           1:9
14308   Ref:  main.adb          6:8      7:8
14309        main.ads           1:6
14310 C                                                      Type: Integer
14311   Decl: main.ads          4:5
14312   Modi: main.adb          4:8
14313   Ref:  main.adb          7:19
14314 D                                                      Type: Integer
14315   Decl: main.ads          6:5
14316   Modi: main.adb          5:8
14317 Foo                                                    Type: Unit
14318   Decl: main.ads          3:15
14319   Body: main.adb          2:15
14320 Main                                                    Type: Unit
14321   Decl: main.ads          2:9
14322   Body: main.adb          1:14
14323 Print                                                   Type: Unit
14324   Decl: bar.ads           2:15
14325   Ref:  main.adb          6:12     7:12
14326 @end smallexample
14327
14328 @noindent
14329 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14330 its body is in main.adb, line 1, column 14 and is not referenced any where.
14331
14332 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14333 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14334
14335 @item gnatxref package1.adb package2.ads
14336 @code{gnatxref} will generates cross-reference information for
14337 package1.adb, package2.ads and any other package 'with'ed by any
14338 of these.
14339
14340 @end table
14341
14342 @ifclear vms
14343 @subsection Using gnatxref with vi
14344
14345 @code{gnatxref} can generate a tags file output, which can be used
14346 directly from @file{vi}. Note that the standard version of @file{vi}
14347 will not work properly with overloaded symbols. Consider using another
14348 free implementation of @file{vi}, such as @file{vim}.
14349
14350 @smallexample
14351 $ gnatxref -v gnatfind.adb > tags
14352 @end smallexample
14353
14354 @noindent
14355 will generate the tags file for @code{gnatfind} itself (if the sources
14356 are in the search path!).
14357
14358 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14359 (replacing @i{entity} by whatever you are looking for), and vi will
14360 display a new file with the corresponding declaration of entity.
14361 @end ifclear
14362
14363 @node Examples of gnatfind Usage
14364 @section Examples of @code{gnatfind} Usage
14365
14366 @table @code
14367
14368 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14369 Find declarations for all entities xyz referenced at least once in
14370 main.adb. The references are search in every library file in the search
14371 path.
14372
14373 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14374 switch is set)
14375
14376 The output will look like:
14377 @smallexample
14378 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14379 ^directory/^[directory]^main.adb:24:10: xyz <= body
14380 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14381 @end smallexample
14382
14383 @noindent
14384 that is to say, one of the entities xyz found in main.adb is declared at
14385 line 12 of main.ads (and its body is in main.adb), and another one is
14386 declared at line 45 of foo.ads
14387
14388 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14389 This is the same command as the previous one, instead @code{gnatfind} will
14390 display the content of the Ada source file lines.
14391
14392 The output will look like:
14393
14394 @smallexample
14395 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14396    procedure xyz;
14397 ^directory/^[directory]^main.adb:24:10: xyz <= body
14398    procedure xyz is
14399 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14400    xyz : Integer;
14401 @end smallexample
14402
14403 @noindent
14404 This can make it easier to find exactly the location your are looking
14405 for.
14406
14407 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14408 Find references to all entities containing an x that are
14409 referenced on line 123 of main.ads.
14410 The references will be searched only in main.ads and foo.adb.
14411
14412 @item gnatfind main.ads:123
14413 Find declarations and bodies for all entities that are referenced on
14414 line 123 of main.ads.
14415
14416 This is the same as @code{gnatfind "*":main.adb:123}.
14417
14418 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14419 Find the declaration for the entity referenced at column 45 in
14420 line 123 of file main.adb in directory mydir. Note that it
14421 is usual to omit the identifier name when the column is given,
14422 since the column position identifies a unique reference.
14423
14424 The column has to be the beginning of the identifier, and should not
14425 point to any character in the middle of the identifier.
14426
14427 @end table
14428
14429
14430 @c *********************************
14431 @node The GNAT Pretty-Printer gnatpp
14432 @chapter The GNAT Pretty-Printer @command{gnatpp}
14433 @findex gnatpp
14434 @cindex Pretty-Printer
14435
14436 @noindent
14437 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14438 for source reformatting / pretty-printing.
14439 It takes an Ada source file as input and generates a reformatted
14440 version as output.
14441 You can specify various style directives via switches; e.g.,
14442 identifier case conventions, rules of indentation, and comment layout.
14443
14444 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14445 tree for the input source and thus requires the input to be syntactically and
14446 semantically legal.
14447 If this condition is not met, @command{gnatpp} will terminate with an
14448 error message; no output file will be generated.
14449
14450 If the compilation unit
14451 contained in the input source depends semantically upon units located
14452 outside the current directory, you have to provide the source search path
14453 when invoking @command{gnatpp}, if these units are contained in files with
14454 names that do not follow the GNAT file naming rules, you have to provide
14455 the configuration file describing the corresponding naming scheme;
14456 see the description of the @command{gnatpp}
14457 switches below. Another possibility is to use a project file and to
14458 call @command{gnatpp} through the @command{gnat} driver
14459
14460 The @command{gnatpp} command has the form
14461
14462 @smallexample
14463 $ gnatpp [@var{switches}] @var{filename}
14464 @end smallexample
14465
14466 @noindent
14467 where
14468 @itemize @bullet
14469 @item
14470 @var{switches} is an optional sequence of switches defining such properties as
14471 the formatting rules, the source search path, and the destination for the
14472 output source file
14473
14474 @item
14475 @var{filename} is the name (including the extension) of the source file to
14476 reformat; ``wildcards'' or several file names on the same gnatpp command are
14477 allowed.  The file name may contain path information; it does not have to
14478 follow the GNAT file naming rules
14479 @end itemize
14480
14481
14482 @menu
14483 * Switches for gnatpp::
14484 * Formatting Rules::
14485 @end menu
14486
14487 @node Switches for gnatpp
14488 @section Switches for @command{gnatpp}
14489
14490 @noindent
14491 The following subsections describe the various switches accepted by
14492 @command{gnatpp}, organized by category.
14493
14494 @ifclear vms
14495 You specify a switch by supplying a name and generally also a value.
14496 In many cases the values for a switch with a given name are incompatible with
14497 each other
14498 (for example the switch that controls the casing of a reserved word may have
14499 exactly one value: upper case, lower case, or
14500 mixed case) and thus exactly one such switch can be in effect for an
14501 invocation of @command{gnatpp}.
14502 If more than one is supplied, the last one is used.
14503 However, some values for the same switch are mutually compatible.
14504 You may supply several such switches to @command{gnatpp}, but then
14505 each must be specified in full, with both the name and the value.
14506 Abbreviated forms (the name appearing once, followed by each value) are
14507 not permitted.
14508 For example, to set
14509 the alignment of the assignment delimiter both in declarations and in
14510 assignment statements, you must write @option{-A2A3}
14511 (or @option{-A2 -A3}), but not @option{-A23}.
14512 @end ifclear
14513
14514 @ifset vms
14515 In many cases the set of options for a given qualifier are incompatible with
14516 each other (for example the qualifier that controls the casing of a reserved
14517 word may have exactly one option, which specifies either upper case, lower
14518 case, or mixed case), and thus exactly one such option can be in effect for
14519 an invocation of @command{gnatpp}.
14520 If more than one is supplied, the last one is used.
14521 However, some qualifiers have options that are mutually compatible,
14522 and then you may then supply several such options when invoking
14523 @command{gnatpp}.
14524 @end ifset
14525
14526 In most cases, it is obvious whether or not the
14527 ^values for a switch with a given name^options for a given qualifier^
14528 are compatible with each other.
14529 When the semantics might not be evident, the summaries below explicitly
14530 indicate the effect.
14531
14532 @menu
14533 * Alignment Control::
14534 * Casing Control::
14535 * Construct Layout Control::
14536 * General Text Layout Control::
14537 * Other Formatting Options::
14538 * Setting the Source Search Path::
14539 * Output File Control::
14540 * Other gnatpp Switches::
14541 @end menu
14542
14543
14544 @node Alignment Control
14545 @subsection Alignment Control
14546 @cindex Alignment control in @command{gnatpp}
14547
14548 @noindent
14549 Programs can be easier to read if certain constructs are vertically aligned.
14550 By default all alignments are set ON.
14551 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14552 OFF, and then use one or more of the other
14553 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14554 to activate alignment for specific constructs.
14555
14556 @table @option
14557 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14558
14559 @ifset vms
14560 @item /ALIGN=ON
14561 Set all alignments to ON
14562 @end ifset
14563
14564 @item ^-A0^/ALIGN=OFF^
14565 Set all alignments to OFF
14566
14567 @item ^-A1^/ALIGN=COLONS^
14568 Align @code{:} in declarations
14569
14570 @item ^-A2^/ALIGN=DECLARATIONS^
14571 Align @code{:=} in initializations in declarations
14572
14573 @item ^-A3^/ALIGN=STATEMENTS^
14574 Align @code{:=} in assignment statements
14575
14576 @item ^-A4^/ALIGN=ARROWS^
14577 Align @code{=>} in associations
14578 @end table
14579
14580 @noindent
14581 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14582 is allowed.
14583
14584
14585 @node Casing Control
14586 @subsection Casing Control
14587 @cindex Casing control in @command{gnatpp}
14588
14589 @noindent
14590 @command{gnatpp} allows you to specify the casing for reserved words,
14591 pragma names, attribute designators and identifiers.
14592 For identifiers you may define a
14593 general rule for name casing but also override this rule
14594 via a set of dictionary files.
14595
14596 Three types of casing are supported: lower case, upper case, and mixed case.
14597 Lower and upper case are self-explanatory (but since some letters in
14598 Latin1 and other GNAT-supported character sets
14599 exist only in lower-case form, an upper case conversion will have no
14600 effect on them.)
14601 ``Mixed case'' means that the first letter, and also each letter immediately
14602 following an underscore, are converted to their uppercase forms;
14603 all the other letters are converted to their lowercase forms.
14604
14605 @table @option
14606 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14607 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14608 Attribute designators are lower case
14609
14610 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14611 Attribute designators are upper case
14612
14613 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14614 Attribute designators are mixed case (this is the default)
14615
14616 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14617 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14618 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14619 lower case (this is the default)
14620
14621 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14622 Keywords are upper case
14623
14624 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14625 @item ^-nD^/NAME_CASING=AS_DECLARED^
14626 Name casing for defining occurrences are as they appear in the source file
14627 (this is the default)
14628
14629 @item ^-nU^/NAME_CASING=UPPER_CASE^
14630 Names are in upper case
14631
14632 @item ^-nL^/NAME_CASING=LOWER_CASE^
14633 Names are in lower case
14634
14635 @item ^-nM^/NAME_CASING=MIXED_CASE^
14636 Names are in mixed case
14637
14638 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14639 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14640 Pragma names are lower case
14641
14642 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14643 Pragma names are upper case
14644
14645 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14646 Pragma names are mixed case (this is the default)
14647
14648 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14649 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14650 Use @var{file} as a @emph{dictionary file} that defines
14651 the casing for a set of specified names,
14652 thereby overriding the effect on these names by
14653 any explicit or implicit
14654 ^-n^/NAME_CASING^ switch.
14655 To supply more than one dictionary file,
14656 use ^several @option{-D} switches^a list of files as options^.
14657
14658 @noindent
14659 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14660 to define the casing for the Ada predefined names and
14661 the names declared in the GNAT libraries.
14662
14663 @item ^-D-^/SPECIFIC_CASING^
14664 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14665 Do not use the default dictionary file;
14666 instead, use the casing
14667 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14668 dictionary file(s)
14669 @end table
14670
14671 @noindent
14672 The structure of a dictionary file, and details on the conventions
14673 used in the default dictionary file, are defined in @ref{Name Casing}.
14674
14675 The @option{^-D-^/SPECIFIC_CASING^} and
14676 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14677 compatible.
14678
14679
14680 @node Construct Layout Control
14681 @subsection Construct Layout Control
14682 @cindex Layout control in @command{gnatpp}
14683
14684 @noindent
14685 This group of @command{gnatpp} switches controls the layout of comments and
14686 complex syntactic constructs.  See @ref{Formatting Comments}, for details
14687 on their effect.
14688
14689 @table @option
14690 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14691 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14692 All the comments remain unchanged
14693
14694 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14695 GNAT-style comment line indentation (this is the default).
14696
14697 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14698 Reference-manual comment line indentation.
14699
14700 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14701 GNAT-style comment beginning
14702
14703 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14704 Reformat comment blocks
14705
14706 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14707 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14708 GNAT-style layout (this is the default)
14709
14710 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14711 Compact layout
14712
14713 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14714 Uncompact layout
14715
14716 @item ^-notab^/NOTABS^
14717 All the VT characters are removed from the comment text. All the HT characters
14718 are expanded with the sequences of space characters to get to the next tab
14719 stops.
14720
14721 @end table
14722
14723 @ifclear vms
14724 @noindent
14725 The @option{-c1} and @option{-c2} switches are incompatible.
14726 The @option{-c3} and @option{-c4} switches are compatible with each other and
14727 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14728 the other comment formatting switches.
14729
14730 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14731 @end ifclear
14732
14733 @ifset vms
14734 @noindent
14735 For the @option{/COMMENTS_LAYOUT} qualifier:
14736 @itemize @bullet
14737 @item
14738 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14739 @item
14740 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14741 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14742 @end itemize
14743
14744 @noindent
14745 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14746 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14747 @end ifset
14748
14749 @node General Text Layout Control
14750 @subsection General Text Layout Control
14751
14752 @noindent
14753 These switches allow control over line length and indentation.
14754
14755 @table @option
14756 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
14757 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14758 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
14759
14760 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
14761 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14762 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
14763
14764 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
14765 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14766 Indentation level for continuation lines (relative to the line being
14767 continued), @i{nnn} from 1 .. 9.
14768 The default
14769 value is one less then the (normal) indentation level, unless the
14770 indentation is set to 1 (in which case the default value for continuation
14771 line indentation is also 1)
14772 @end table
14773
14774
14775 @node Other Formatting Options
14776 @subsection Other Formatting Options
14777
14778 @noindent
14779 These switches control the inclusion of missing end/exit labels, and
14780 the indentation level in @b{case} statements.
14781
14782 @table @option
14783 @item ^-e^/NO_MISSED_LABELS^
14784 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14785 Do not insert missing end/exit labels. An end label is the name of
14786 a construct that may optionally be repeated at the end of the
14787 construct's declaration;
14788 e.g., the names of packages, subprograms, and tasks.
14789 An exit label is the name of a loop that may appear as target
14790 of an exit statement within the loop.
14791 By default, @command{gnatpp} inserts these end/exit labels when
14792 they are absent from the original source. This option suppresses such
14793 insertion, so that the formatted source reflects the original.
14794
14795 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14796 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14797 Insert a Form Feed character after a pragma Page.
14798
14799 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
14800 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14801 Do not use an additional indentation level for @b{case} alternatives
14802 and variants if there are @i{nnn} or more (the default
14803 value is 10).
14804 If @i{nnn} is 0, an additional indentation level is
14805 used for @b{case} alternatives and variants regardless of their number.
14806 @end table
14807
14808 @node Setting the Source Search Path
14809 @subsection Setting the Source Search Path
14810
14811 @noindent
14812 To define the search path for the input source file, @command{gnatpp}
14813 uses the same switches as the GNAT compiler, with the same effects.
14814
14815 @table @option
14816 @item ^-I^/SEARCH=^@var{dir}
14817 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14818 The same as the corresponding gcc switch
14819
14820 @item ^-I-^/NOCURRENT_DIRECTORY^
14821 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14822 The same as the corresponding gcc switch
14823
14824 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14825 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14826 The same as the corresponding gcc switch
14827
14828 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14829 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14830 The same as the corresponding gcc switch
14831
14832 @end table
14833
14834
14835 @node Output File Control
14836 @subsection Output File Control
14837
14838 @noindent
14839 By default the output is sent to the file whose name is obtained by appending
14840 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14841 (if the file with this name already exists, it is unconditionally overwritten).
14842 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14843 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14844 as output file.
14845 The output may be redirected by the following switches:
14846
14847 @table @option
14848 @item ^-pipe^/STANDARD_OUTPUT^
14849 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14850 Send the output to @code{Standard_Output}
14851
14852 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14853 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14854 Write the output into @var{output_file}.
14855 If @var{output_file} already exists, @command{gnatpp} terminates without
14856 reading or processing the input file.
14857
14858 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14859 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14860 Write the output into @var{output_file}, overwriting the existing file
14861 (if one is present).
14862
14863 @item ^-r^/REPLACE^
14864 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14865 Replace the input source file with the reformatted output, and copy the
14866 original input source into the file whose name is obtained by appending the
14867 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14868 If a file with this name already exists, @command{gnatpp} terminates without
14869 reading or processing the input file.
14870
14871 @item ^-rf^/OVERRIDING_REPLACE^
14872 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14873 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14874 already exists, it is overwritten.
14875
14876 @item ^-rnb^/NO_BACKUP^
14877 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
14878 Replace the input source file with the reformatted output without
14879 creating any backup copy of the input source.
14880 @end table
14881
14882 @noindent
14883 Options @option{^-pipe^/STANDARD_OUTPUT^},
14884 @option{^-o^/OUTPUT^} and
14885 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14886 contains only one file to reformat
14887
14888 @node Other gnatpp Switches
14889 @subsection Other @code{gnatpp} Switches
14890
14891 @noindent
14892 The additional @command{gnatpp} switches are defined in this subsection.
14893
14894 @table @option
14895 @item ^-files @var{filename}^/FILES=@var{output_file}^
14896 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14897 Take the argument source files from the specified file. This file should be an
14898 ordinary textual file containing file names separated by spaces or
14899 line breaks. You can use this switch more then once in the same call to
14900 @command{gnatpp}. You also can combine this switch with explicit list of
14901 files.
14902
14903 @item ^-v^/VERBOSE^
14904 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14905 Verbose mode;
14906 @command{gnatpp} generates version information and then
14907 a trace of the actions it takes to produce or obtain the ASIS tree.
14908
14909 @item ^-w^/WARNINGS^
14910 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14911 Warning mode;
14912 @command{gnatpp} generates a warning whenever it can not provide
14913 a required layout in the result source.
14914 @end table
14915
14916
14917 @node Formatting Rules
14918 @section Formatting Rules
14919
14920 @noindent
14921 The following subsections show how @command{gnatpp} treats ``white space'',
14922 comments, program layout, and name casing.
14923 They provide the detailed descriptions of the switches shown above.
14924
14925 @menu
14926 * White Space and Empty Lines::
14927 * Formatting Comments::
14928 * Construct Layout::
14929 * Name Casing::
14930 @end menu
14931
14932
14933 @node White Space and Empty Lines
14934 @subsection White Space and Empty Lines
14935
14936 @noindent
14937 @command{gnatpp} does not have an option to control space characters.
14938 It will add or remove spaces according to the style illustrated by the
14939 examples in the @cite{Ada Reference Manual}.
14940
14941 The only format effectors
14942 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
14943 that will appear in the output file are platform-specific line breaks,
14944 and also format effectors within (but not at the end of) comments.
14945 In particular, each horizontal tab character that is not inside
14946 a comment will be treated as a space and thus will appear in the
14947 output file as zero or more spaces depending on
14948 the reformatting of the line in which it appears.
14949 The only exception is a Form Feed character, which is inserted after a
14950 pragma @code{Page} when @option{-ff} is set.
14951
14952 The output file will contain no lines with trailing ``white space'' (spaces,
14953 format effectors).
14954
14955 Empty lines in the original source are preserved
14956 only if they separate declarations or statements.
14957 In such contexts, a
14958 sequence of two or more empty lines is replaced by exactly one empty line.
14959 Note that a blank line will be removed if it separates two ``comment blocks''
14960 (a comment block is a sequence of whole-line comments).
14961 In order to preserve a visual separation between comment blocks, use an
14962 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
14963 Likewise, if for some reason you wish to have a sequence of empty lines,
14964 use a sequence of empty comments instead.
14965
14966
14967 @node Formatting Comments
14968 @subsection Formatting Comments
14969
14970 @noindent
14971 Comments in Ada code are of two kinds:
14972 @itemize @bullet
14973 @item
14974 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14975 ``white space'') on a line
14976
14977 @item
14978 an @emph{end-of-line comment}, which follows some other Ada lexical element
14979 on the same line.
14980 @end itemize
14981
14982 @noindent
14983 The indentation of a whole-line comment is that of either
14984 the preceding or following line in
14985 the formatted source, depending on switch settings as will be described below.
14986
14987 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
14988 between the end of the preceding Ada lexical element and the beginning
14989 of the comment as appear in the original source,
14990 unless either the comment has to be split to
14991 satisfy the line length limitation, or else the next line contains a
14992 whole line comment that is considered a continuation of this end-of-line
14993 comment (because it starts at the same position).
14994 In the latter two
14995 cases, the start of the end-of-line comment is moved right to the nearest
14996 multiple of the indentation level.
14997 This may result in a ``line overflow'' (the right-shifted comment extending
14998 beyond the maximum line length), in which case the comment is split as
14999 described below.
15000
15001 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15002 (GNAT-style comment line indentation)
15003 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15004 (reference-manual comment line indentation).
15005 With reference-manual style, a whole-line comment is indented as if it
15006 were a declaration or statement at the same place
15007 (i.e., according to the indentation of the preceding line(s)).
15008 With GNAT style, a whole-line comment that is immediately followed by an
15009 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15010 word @b{begin}, is indented based on the construct that follows it.
15011
15012 For example:
15013 @smallexample @c ada
15014 @cartouche
15015 if A then
15016     null;
15017        -- some comment
15018 else
15019    null;
15020 end if;
15021 @end cartouche
15022 @end smallexample
15023
15024 @noindent
15025 Reference-manual indentation produces:
15026
15027 @smallexample @c ada
15028 @cartouche
15029 if A then
15030    null;
15031    --  some comment
15032 else
15033    null;
15034 end if;
15035 @end cartouche
15036 @end smallexample
15037
15038 @noindent
15039 while GNAT-style indentation produces:
15040
15041 @smallexample @c ada
15042 @cartouche
15043 if A then
15044    null;
15045 --  some comment
15046 else
15047    null;
15048 end if;
15049 @end cartouche
15050 @end smallexample
15051
15052 @noindent
15053 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15054 (GNAT style comment beginning) has the following
15055 effect:
15056
15057 @itemize @bullet
15058 @item
15059 For each whole-line comment that does not end with two hyphens,
15060 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15061 to ensure that there are at least two spaces between these hyphens and the
15062 first non-blank character of the comment.
15063 @end itemize
15064
15065 @noindent
15066 For an end-of-line comment, if in the original source the next line is a
15067 whole-line comment that starts at the same position
15068 as the end-of-line comment,
15069 then the whole-line comment (and all whole-line comments
15070 that follow it and that start at the same position)
15071 will start at this position in the output file.
15072
15073 @noindent
15074 That is, if in the original source we have:
15075
15076 @smallexample @c ada
15077 @cartouche
15078 begin
15079 A := B + C;            --  B must be in the range Low1..High1
15080                        --  C must be in the range Low2..High2
15081              --B+C will be in the range Low1+Low2..High1+High2
15082 X := X + 1;
15083 @end cartouche
15084 @end smallexample
15085
15086 @noindent
15087 Then in the formatted source we get
15088
15089 @smallexample @c ada
15090 @cartouche
15091 begin
15092    A := B + C;            --  B must be in the range Low1..High1
15093                           --  C must be in the range Low2..High2
15094    --  B+C will be in the range Low1+Low2..High1+High2
15095    X := X + 1;
15096 @end cartouche
15097 @end smallexample
15098
15099 @noindent
15100 A comment that exceeds the line length limit will be split.
15101 Unless switch
15102 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15103 the line belongs to a reformattable block, splitting the line generates a
15104 @command{gnatpp} warning.
15105 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15106 comments may be reformatted in typical
15107 word processor style (that is, moving words between lines and putting as
15108 many words in a line as possible).
15109
15110
15111 @node Construct Layout
15112 @subsection Construct Layout
15113
15114 @noindent
15115 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15116 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15117 layout on the one hand, and uncompact layout
15118 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15119 can be illustrated by the following examples:
15120
15121 @iftex
15122 @cartouche
15123 @multitable @columnfractions .5 .5
15124 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15125
15126 @item
15127 @smallexample @c ada
15128 type q is record
15129    a : integer;
15130    b : integer;
15131 end record;
15132 @end smallexample
15133 @tab
15134 @smallexample @c ada
15135 type q is
15136    record
15137       a : integer;
15138       b : integer;
15139    end record;
15140 @end smallexample
15141
15142 @item
15143 @smallexample @c ada
15144 Block : declare
15145    A : Integer := 3;
15146 begin
15147    Proc (A, A);
15148 end Block;
15149 @end smallexample
15150 @tab
15151 @smallexample @c ada
15152 Block :
15153    declare
15154       A : Integer := 3;
15155    begin
15156       Proc (A, A);
15157    end Block;
15158 @end smallexample
15159
15160 @item
15161 @smallexample @c ada
15162 Clear : for J in 1 .. 10 loop
15163    A (J) := 0;
15164 end loop Clear;
15165 @end smallexample
15166 @tab
15167 @smallexample @c ada
15168 Clear :
15169    for J in 1 .. 10 loop
15170       A (J) := 0;
15171    end loop Clear;
15172 @end smallexample
15173 @end multitable
15174 @end cartouche
15175 @end iftex
15176
15177 @ifnottex
15178 @smallexample
15179 @cartouche
15180 GNAT style, compact layout              Uncompact layout
15181
15182 type q is record                        type q is
15183    a : integer;                            record
15184    b : integer;                               a : integer;
15185 end record;                                   b : integer;
15186                                            end record;
15187
15188
15189 Block : declare                         Block :
15190    A : Integer := 3;                       declare
15191 begin                                         A : Integer := 3;
15192    Proc (A, A);                            begin
15193 end Block;                                    Proc (A, A);
15194                                            end Block;
15195
15196 Clear : for J in 1 .. 10 loop           Clear :
15197    A (J) := 0;                             for J in 1 .. 10 loop
15198 end loop Clear;                               A (J) := 0;
15199                                            end loop Clear;
15200 @end cartouche
15201 @end smallexample
15202 @end ifnottex
15203
15204 @noindent
15205 A further difference between GNAT style layout and compact layout is that
15206 GNAT style layout inserts empty lines as separation for
15207 compound statements, return statements and bodies.
15208
15209
15210 @node Name Casing
15211 @subsection Name Casing
15212
15213 @noindent
15214 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15215 the same casing as the corresponding defining identifier.
15216
15217 You control the casing for defining occurrences via the
15218 @option{^-n^/NAME_CASING^} switch.
15219 @ifclear vms
15220 With @option{-nD} (``as declared'', which is the default),
15221 @end ifclear
15222 @ifset vms
15223 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15224 @end ifset
15225 defining occurrences appear exactly as in the source file
15226 where they are declared.
15227 The other ^values for this switch^options for this qualifier^ ---
15228 @option{^-nU^UPPER_CASE^},
15229 @option{^-nL^LOWER_CASE^},
15230 @option{^-nM^MIXED_CASE^} ---
15231 result in
15232 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15233 If @command{gnatpp} changes the casing of a defining
15234 occurrence, it analogously changes the casing of all the
15235 usage occurrences of this name.
15236
15237 If the defining occurrence of a name is not in the source compilation unit
15238 currently being processed by @command{gnatpp}, the casing of each reference to
15239 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15240 switch (subject to the dictionary file mechanism described below).
15241 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15242 had affected the
15243 casing for the defining occurrence of the name.
15244
15245 Some names may need to be spelled with casing conventions that are not
15246 covered by the upper-, lower-, and mixed-case transformations.
15247 You can arrange correct casing by placing such names in a
15248 @emph{dictionary file},
15249 and then supplying a @option{^-D^/DICTIONARY^} switch.
15250 The casing of names from dictionary files overrides
15251 any @option{^-n^/NAME_CASING^} switch.
15252
15253 To handle the casing of Ada predefined names and the names from GNAT libraries,
15254 @command{gnatpp} assumes a default dictionary file.
15255 The name of each predefined entity is spelled with the same casing as is used
15256 for the entity in the @cite{Ada Reference Manual}.
15257 The name of each entity in the GNAT libraries is spelled with the same casing
15258 as is used in the declaration of that entity.
15259
15260 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15261 default dictionary file.
15262 Instead, the casing for predefined and GNAT-defined names will be established
15263 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15264 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15265 will appear as just shown,
15266 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15267 To ensure that even such names are rendered in uppercase,
15268 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15269 (or else, less conveniently, place these names in upper case in a dictionary
15270 file).
15271
15272 A dictionary file is
15273 a plain text file; each line in this file can be either a blank line
15274 (containing only space characters and ASCII.HT characters), an Ada comment
15275 line, or the specification of exactly one @emph{casing schema}.
15276
15277 A casing schema is a string that has the following syntax:
15278
15279 @smallexample
15280 @cartouche
15281   @var{casing_schema} ::= @var{identifier} | [*]@var{simple_identifier}[*]
15282
15283   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15284 @end cartouche
15285 @end smallexample
15286
15287 @noindent
15288 (The @code{[]} metanotation stands for an optional part;
15289 see @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15290 @var{identifier} lexical element and the @var{letter_or_digit} category).
15291
15292 The casing schema string can be followed by white space and/or an Ada-style
15293 comment; any amount of white space is allowed before the string.
15294
15295 If a dictionary file is passed as
15296 @ifclear vms
15297 the value of a @option{-D@var{file}} switch
15298 @end ifclear
15299 @ifset vms
15300 an option to the @option{/DICTIONARY} qualifier
15301 @end ifset
15302 then for every
15303 simple name and every identifier, @command{gnatpp} checks if the dictionary
15304 defines the casing for the name or for some of its parts (the term ``subword''
15305 is used below to denote the part of a name which is delimited by ``_'' or by
15306 the beginning or end of the word and which does not contain any ``_'' inside):
15307
15308 @itemize @bullet
15309 @item
15310 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15311 the casing defined by the dictionary; no subwords are checked for this word
15312
15313 @item
15314 for the first subword (that is, for the subword preceding the leftmost
15315 ``_''), @command{gnatpp} checks if the dictionary contains the corresponding
15316 string of the form @code{@var{simple_identifier}*}, and if it does, the
15317 casing of this @var{simple_identifier} is used for this subword
15318
15319 @item
15320 for the last subword (following the rightmost ``_'') @command{gnatpp}
15321 checks if the dictionary contains the corresponding string of the form
15322 @code{*@var{simple_identifier}}, and if it does, the casing of this
15323 @var{simple_identifier} is used for this subword
15324
15325 @item
15326 for every intermediate subword (surrounded by two'_') @command{gnatpp} checks
15327 if the dictionary contains the corresponding string of the form
15328 @code{*@var{simple_identifier}*}, and if it does, the casing of this
15329 simple_identifier is used for this subword
15330
15331 @item
15332 if more than one dictionary file is passed as @command{gnatpp} switches, each
15333 dictionary adds new casing exceptions and overrides all the existing casing
15334 exceptions set by the previous dictionaries
15335
15336 @item
15337 when @command{gnatpp} checks if the word or subword is in the dictionary,
15338 this check is not case sensitive
15339 @end itemize
15340
15341 @noindent
15342 For example, suppose we have the following source to reformat:
15343
15344 @smallexample @c ada
15345 @cartouche
15346 procedure test is
15347    name1 : integer := 1;
15348    name4_name3_name2 : integer := 2;
15349    name2_name3_name4 : Boolean;
15350    name1_var : Float;
15351 begin
15352    name2_name3_name4 := name4_name3_name2 > name1;
15353 end;
15354 @end cartouche
15355 @end smallexample
15356
15357 @noindent
15358 And suppose we have two dictionaries:
15359
15360 @smallexample
15361 @cartouche
15362 @i{dict1:}
15363    NAME1
15364    *NaMe3*
15365    *NAME2
15366 @end cartouche
15367
15368 @cartouche
15369 @i{dict2:}
15370   *NAME3*
15371 @end cartouche
15372 @end smallexample
15373
15374 @noindent
15375 If @command{gnatpp} is called with the following switches:
15376
15377 @smallexample
15378 @ifclear vms
15379 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15380 @end ifclear
15381 @ifset vms
15382 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15383 @end ifset
15384 @end smallexample
15385
15386 @noindent
15387 then we will get the following name casing in the @command{gnatpp} output:
15388
15389 @smallexample @c ada
15390 @cartouche
15391 procedure Test is
15392    NAME1             : Integer := 1;
15393    Name4_NAME3_NAME2 : integer := 2;
15394    Name2_NAME3_Name4 : Boolean;
15395    Name1_Var         : Float;
15396 begin
15397    Name2_NAME3_Name4 := Name4_NAME3_NAME2 > NAME1;
15398 end Test;
15399 @end cartouche
15400 @end smallexample
15401
15402
15403
15404 @c ***********************************
15405 @node File Name Krunching Using gnatkr
15406 @chapter File Name Krunching Using @code{gnatkr}
15407 @findex gnatkr
15408
15409 @noindent
15410 This chapter discusses the method used by the compiler to shorten
15411 the default file names chosen for Ada units so that they do not
15412 exceed the maximum length permitted. It also describes the
15413 @code{gnatkr} utility that can be used to determine the result of
15414 applying this shortening.
15415 @menu
15416 * About gnatkr::
15417 * Using gnatkr::
15418 * Krunching Method::
15419 * Examples of gnatkr Usage::
15420 @end menu
15421
15422 @node About gnatkr
15423 @section About @code{gnatkr}
15424
15425 @noindent
15426 The default file naming rule in GNAT
15427 is that the file name must be derived from
15428 the unit name. The exact default rule is as follows:
15429 @itemize @bullet
15430 @item
15431 Take the unit name and replace all dots by hyphens.
15432 @item
15433 If such a replacement occurs in the
15434 second character position of a name, and the first character is
15435 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
15436 ^~ (tilde)^$ (dollar sign)^
15437 instead of a minus.
15438 @end itemize
15439 The reason for this exception is to avoid clashes
15440 with the standard names for children of System, Ada, Interfaces,
15441 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
15442 respectively.
15443
15444 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15445 switch of the compiler activates a ``krunching''
15446 circuit that limits file names to nn characters (where nn is a decimal
15447 integer). For example, using OpenVMS,
15448 where the maximum file name length is
15449 39, the value of nn is usually set to 39, but if you want to generate
15450 a set of files that would be usable if ported to a system with some
15451 different maximum file length, then a different value can be specified.
15452 The default value of 39 for OpenVMS need not be specified.
15453
15454 The @code{gnatkr} utility can be used to determine the krunched name for
15455 a given file, when krunched to a specified maximum length.
15456
15457 @node Using gnatkr
15458 @section Using @code{gnatkr}
15459
15460 @noindent
15461 The @code{gnatkr} command has the form
15462
15463 @ifclear vms
15464 @smallexample
15465 $ gnatkr @var{name} [@var{length}]
15466 @end smallexample
15467 @end ifclear
15468
15469 @ifset vms
15470 @smallexample
15471 $ gnatkr @var{name} /COUNT=nn
15472 @end smallexample
15473 @end ifset
15474
15475 @noindent
15476 @var{name} is the uncrunched file name, derived from the name of the unit
15477 in the standard manner described in the previous section (i.e. in particular
15478 all dots are replaced by hyphens). The file name may or may not have an
15479 extension (defined as a suffix of the form period followed by arbitrary
15480 characters other than period). If an extension is present then it will
15481 be preserved in the output. For example, when krunching @file{hellofile.ads}
15482 to eight characters, the result will be hellofil.ads.
15483
15484 Note: for compatibility with previous versions of @code{gnatkr} dots may
15485 appear in the name instead of hyphens, but the last dot will always be
15486 taken as the start of an extension. So if @code{gnatkr} is given an argument
15487 such as @file{Hello.World.adb} it will be treated exactly as if the first
15488 period had been a hyphen, and for example krunching to eight characters
15489 gives the result @file{hellworl.adb}.
15490
15491 Note that the result is always all lower case (except on OpenVMS where it is
15492 all upper case). Characters of the other case are folded as required.
15493
15494 @var{length} represents the length of the krunched name. The default
15495 when no argument is given is ^8^39^ characters. A length of zero stands for
15496 unlimited, in other words do not chop except for system files where the
15497 impled crunching length is always eight characters.
15498
15499 @noindent
15500 The output is the krunched name. The output has an extension only if the
15501 original argument was a file name with an extension.
15502
15503 @node Krunching Method
15504 @section Krunching Method
15505
15506 @noindent
15507 The initial file name is determined by the name of the unit that the file
15508 contains. The name is formed by taking the full expanded name of the
15509 unit and replacing the separating dots with hyphens and
15510 using ^lowercase^uppercase^
15511 for all letters, except that a hyphen in the second character position is
15512 replaced by a ^tilde^dollar sign^ if the first character is
15513 ^a, i, g, or s^A, I, G, or S^.
15514 The extension is @code{.ads} for a
15515 specification and @code{.adb} for a body.
15516 Krunching does not affect the extension, but the file name is shortened to
15517 the specified length by following these rules:
15518
15519 @itemize @bullet
15520 @item
15521 The name is divided into segments separated by hyphens, tildes or
15522 underscores and all hyphens, tildes, and underscores are
15523 eliminated. If this leaves the name short enough, we are done.
15524
15525 @item
15526 If the name is too long, the longest segment is located (left-most
15527 if there are two of equal length), and shortened by dropping
15528 its last character. This is repeated until the name is short enough.
15529
15530 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15531 to fit the name into 8 characters as required by some operating systems.
15532
15533 @smallexample
15534 our-strings-wide_fixed 22
15535 our strings wide fixed 19
15536 our string  wide fixed 18
15537 our strin   wide fixed 17
15538 our stri    wide fixed 16
15539 our stri    wide fixe  15
15540 our str     wide fixe  14
15541 our str     wid  fixe  13
15542 our str     wid  fix   12
15543 ou  str     wid  fix   11
15544 ou  st      wid  fix   10
15545 ou  st      wi   fix   9
15546 ou  st      wi   fi    8
15547 Final file name: oustwifi.adb
15548 @end smallexample
15549
15550 @item
15551 The file names for all predefined units are always krunched to eight
15552 characters. The krunching of these predefined units uses the following
15553 special prefix replacements:
15554
15555 @table @file
15556 @item ada-
15557 replaced by @file{^a^A^-}
15558
15559 @item gnat-
15560 replaced by @file{^g^G^-}
15561
15562 @item interfaces-
15563 replaced by @file{^i^I^-}
15564
15565 @item system-
15566 replaced by @file{^s^S^-}
15567 @end table
15568
15569 These system files have a hyphen in the second character position. That
15570 is why normal user files replace such a character with a
15571 ^tilde^dollar sign^, to
15572 avoid confusion with system file names.
15573
15574 As an example of this special rule, consider
15575 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15576
15577 @smallexample
15578 ada-strings-wide_fixed 22
15579 a-  strings wide fixed 18
15580 a-  string  wide fixed 17
15581 a-  strin   wide fixed 16
15582 a-  stri    wide fixed 15
15583 a-  stri    wide fixe  14
15584 a-  str     wide fixe  13
15585 a-  str     wid  fixe  12
15586 a-  str     wid  fix   11
15587 a-  st      wid  fix   10
15588 a-  st      wi   fix   9
15589 a-  st      wi   fi    8
15590 Final file name: a-stwifi.adb
15591 @end smallexample
15592 @end itemize
15593
15594 Of course no file shortening algorithm can guarantee uniqueness over all
15595 possible unit names, and if file name krunching is used then it is your
15596 responsibility to ensure that no name clashes occur. The utility
15597 program @code{gnatkr} is supplied for conveniently determining the
15598 krunched name of a file.
15599
15600 @node Examples of gnatkr Usage
15601 @section Examples of @code{gnatkr} Usage
15602
15603 @smallexample
15604 @iftex
15605 @leftskip=0cm
15606 @end iftex
15607 @ifclear vms
15608 $ gnatkr very_long_unit_name.ads      --> velounna.ads
15609 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15610 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15611 $ gnatkr grandparent-parent-child     --> grparchi
15612 @end ifclear
15613 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15614 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15615 @end smallexample
15616
15617 @node Preprocessing Using gnatprep
15618 @chapter Preprocessing Using @code{gnatprep}
15619 @findex gnatprep
15620
15621 @noindent
15622 The @code{gnatprep} utility provides
15623 a simple preprocessing capability for Ada programs.
15624 It is designed for use with GNAT, but is not dependent on any special
15625 features of GNAT.
15626
15627 @menu
15628 * Using gnatprep::
15629 * Switches for gnatprep::
15630 * Form of Definitions File::
15631 * Form of Input Text for gnatprep::
15632 @end menu
15633
15634 @node Using gnatprep
15635 @section Using @code{gnatprep}
15636
15637 @noindent
15638 To call @code{gnatprep} use
15639
15640 @smallexample
15641 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
15642 @end smallexample
15643
15644 @noindent
15645 where
15646 @table @code
15647 @item infile
15648 is the full name of the input file, which is an Ada source
15649 file containing preprocessor directives.
15650
15651 @item outfile
15652 is the full name of the output file, which is an Ada source
15653 in standard Ada form. When used with GNAT, this file name will
15654 normally have an ads or adb suffix.
15655
15656 @item deffile
15657 is the full name of a text file containing definitions of
15658 symbols to be referenced by the preprocessor. This argument is
15659 optional, and can be replaced by the use of the @option{-D} switch.
15660
15661 @item switches
15662 is an optional sequence of switches as described in the next section.
15663 @end table
15664
15665 @node Switches for gnatprep
15666 @section Switches for @code{gnatprep}
15667
15668 @table @option
15669 @c !sort!
15670
15671 @item ^-b^/BLANK_LINES^
15672 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15673 Causes both preprocessor lines and the lines deleted by
15674 preprocessing to be replaced by blank lines in the output source file,
15675 preserving line numbers in the output file.
15676
15677 @item ^-c^/COMMENTS^
15678 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15679 Causes both preprocessor lines and the lines deleted
15680 by preprocessing to be retained in the output source as comments marked
15681 with the special string @code{"--! "}. This option will result in line numbers
15682 being preserved in the output file.
15683
15684 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15685 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15686 Defines a new symbol, associated with value. If no value is given on the
15687 command line, then symbol is considered to be @code{True}. This switch
15688 can be used in place of a definition file.
15689
15690 @ifset vms
15691 @item /REMOVE
15692 @cindex @option{/REMOVE} (@command{gnatprep})
15693 This is the default setting which causes lines deleted by preprocessing
15694 to be entirely removed from the output file.
15695 @end ifset
15696
15697 @item ^-r^/REFERENCE^
15698 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15699 Causes a @code{Source_Reference} pragma to be generated that
15700 references the original input file, so that error messages will use
15701 the file name of this original file. The use of this switch implies
15702 that preprocessor lines are not to be removed from the file, so its
15703 use will force @option{^-b^/BLANK_LINES^} mode if
15704 @option{^-c^/COMMENTS^}
15705 has not been specified explicitly.
15706
15707 Note that if the file to be preprocessed contains multiple units, then
15708 it will be necessary to @code{gnatchop} the output file from
15709 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15710 in the preprocessed file, it will be respected by
15711 @code{gnatchop ^-r^/REFERENCE^}
15712 so that the final chopped files will correctly refer to the original
15713 input source file for @code{gnatprep}.
15714
15715 @item ^-s^/SYMBOLS^
15716 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15717 Causes a sorted list of symbol names and values to be
15718 listed on the standard output file.
15719
15720 @item ^-u^/UNDEFINED^
15721 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15722 Causes undefined symbols to be treated as having the value FALSE in the context
15723 of a preprocessor test. In the absence of this option, an undefined symbol in
15724 a @code{#if} or @code{#elsif} test will be treated as an error.
15725
15726 @end table
15727
15728 @ifclear vms
15729 @noindent
15730 Note: if neither @option{-b} nor @option{-c} is present,
15731 then preprocessor lines and
15732 deleted lines are completely removed from the output, unless -r is
15733 specified, in which case -b is assumed.
15734 @end ifclear
15735
15736 @node Form of Definitions File
15737 @section Form of Definitions File
15738
15739 @noindent
15740 The definitions file contains lines of the form
15741
15742 @smallexample
15743 symbol := value
15744 @end smallexample
15745
15746 @noindent
15747 where symbol is an identifier, following normal Ada (case-insensitive)
15748 rules for its syntax, and value is one of the following:
15749
15750 @itemize @bullet
15751 @item
15752 Empty, corresponding to a null substitution
15753 @item
15754 A string literal using normal Ada syntax
15755 @item
15756 Any sequence of characters from the set
15757 (letters, digits, period, underline).
15758 @end itemize
15759
15760 @noindent
15761 Comment lines may also appear in the definitions file, starting with
15762 the usual @code{--},
15763 and comments may be added to the definitions lines.
15764
15765 @node Form of Input Text for gnatprep
15766 @section Form of Input Text for @code{gnatprep}
15767
15768 @noindent
15769 The input text may contain preprocessor conditional inclusion lines,
15770 as well as general symbol substitution sequences.
15771
15772 The preprocessor conditional inclusion commands have the form
15773
15774 @smallexample
15775 @group
15776 @cartouche
15777 #if @i{expression} [then]
15778    lines
15779 #elsif @i{expression} [then]
15780    lines
15781 #elsif @i{expression} [then]
15782    lines
15783 ...
15784 #else
15785    lines
15786 #end if;
15787 @end cartouche
15788 @end group
15789 @end smallexample
15790
15791 @noindent
15792 In this example, @i{expression} is defined by the following grammar:
15793 @smallexample
15794 @i{expression} ::=  <symbol>
15795 @i{expression} ::=  <symbol> = "<value>"
15796 @i{expression} ::=  <symbol> = <symbol>
15797 @i{expression} ::=  <symbol> 'Defined
15798 @i{expression} ::=  not @i{expression}
15799 @i{expression} ::=  @i{expression} and @i{expression}
15800 @i{expression} ::=  @i{expression} or @i{expression}
15801 @i{expression} ::=  @i{expression} and then @i{expression}
15802 @i{expression} ::=  @i{expression} or else @i{expression}
15803 @i{expression} ::=  ( @i{expression} )
15804 @end smallexample
15805
15806 @noindent
15807 For the first test (@i{expression} ::= <symbol>) the symbol must have
15808 either the value true or false, that is to say the right-hand of the
15809 symbol definition must be one of the (case-insensitive) literals
15810 @code{True} or @code{False}. If the value is true, then the
15811 corresponding lines are included, and if the value is false, they are
15812 excluded.
15813
15814 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15815 the symbol has been defined in the definition file or by a @option{-D}
15816 switch on the command line. Otherwise, the test is false.
15817
15818 The equality tests are case insensitive, as are all the preprocessor lines.
15819
15820 If the symbol referenced is not defined in the symbol definitions file,
15821 then the effect depends on whether or not switch @option{-u}
15822 is specified. If so, then the symbol is treated as if it had the value
15823 false and the test fails. If this switch is not specified, then
15824 it is an error to reference an undefined symbol. It is also an error to
15825 reference a symbol that is defined with a value other than @code{True}
15826 or @code{False}.
15827
15828 The use of the @code{not} operator inverts the sense of this logical test, so
15829 that the lines are included only if the symbol is not defined.
15830 The @code{then} keyword is optional as shown
15831
15832 The @code{#} must be the first non-blank character on a line, but
15833 otherwise the format is free form. Spaces or tabs may appear between
15834 the @code{#} and the keyword. The keywords and the symbols are case
15835 insensitive as in normal Ada code. Comments may be used on a
15836 preprocessor line, but other than that, no other tokens may appear on a
15837 preprocessor line. Any number of @code{elsif} clauses can be present,
15838 including none at all. The @code{else} is optional, as in Ada.
15839
15840 The @code{#} marking the start of a preprocessor line must be the first
15841 non-blank character on the line, i.e. it must be preceded only by
15842 spaces or horizontal tabs.
15843
15844 Symbol substitution outside of preprocessor lines is obtained by using
15845 the sequence
15846
15847 @smallexample
15848 $symbol
15849 @end smallexample
15850
15851 @noindent
15852 anywhere within a source line, except in a comment or within a
15853 string literal. The identifier
15854 following the @code{$} must match one of the symbols defined in the symbol
15855 definition file, and the result is to substitute the value of the
15856 symbol in place of @code{$symbol} in the output file.
15857
15858 Note that although the substitution of strings within a string literal
15859 is not possible, it is possible to have a symbol whose defined value is
15860 a string literal. So instead of setting XYZ to @code{hello} and writing:
15861
15862 @smallexample
15863 Header : String := "$XYZ";
15864 @end smallexample
15865
15866 @noindent
15867 you should set XYZ to @code{"hello"} and write:
15868
15869 @smallexample
15870 Header : String := $XYZ;
15871 @end smallexample
15872
15873 @noindent
15874 and then the substitution will occur as desired.
15875
15876 @ifset vms
15877 @node The GNAT Run-Time Library Builder gnatlbr
15878 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
15879 @findex gnatlbr
15880 @cindex Library builder
15881
15882 @noindent
15883 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
15884 supplied configuration pragmas.
15885
15886 @menu
15887 * Running gnatlbr::
15888 * Switches for gnatlbr::
15889 * Examples of gnatlbr Usage::
15890 @end menu
15891
15892 @node Running gnatlbr
15893 @section Running @code{gnatlbr}
15894
15895 @noindent
15896 The @code{gnatlbr} command has the form
15897
15898 @smallexample
15899 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
15900 @end smallexample
15901
15902 @node Switches for gnatlbr
15903 @section Switches for @code{gnatlbr}
15904
15905 @noindent
15906 @code{gnatlbr} recognizes the following switches:
15907
15908 @table @option
15909 @c !sort!
15910 @item /CREATE=directory
15911 @cindex @code{/CREATE} (@code{gnatlbr})
15912      Create the new run-time library in the specified directory.
15913
15914 @item /SET=directory
15915 @cindex @code{/SET} (@code{gnatlbr})
15916      Make the library in the specified directory the current run-time
15917      library.
15918
15919 @item /DELETE=directory
15920 @cindex @code{/DELETE} (@code{gnatlbr})
15921      Delete the run-time library in the specified directory.
15922
15923 @item /CONFIG=file
15924 @cindex @code{/CONFIG} (@code{gnatlbr})
15925      With /CREATE:
15926      Use the configuration pragmas in the specified file when building
15927      the library.
15928
15929      With /SET:
15930      Use the configuration pragmas in the specified file when compiling.
15931
15932 @end table
15933
15934 @node Examples of gnatlbr Usage
15935 @section Example of @code{gnatlbr} Usage
15936
15937 @smallexample
15938 Contents of VAXFLOAT.ADC:
15939 pragma Float_Representation (VAX_Float);
15940
15941 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
15942
15943 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
15944
15945 @end smallexample
15946 @end ifset
15947
15948 @node The GNAT Library Browser gnatls
15949 @chapter The GNAT Library Browser @code{gnatls}
15950 @findex gnatls
15951 @cindex Library browser
15952
15953 @noindent
15954 @code{gnatls} is a tool that outputs information about compiled
15955 units. It gives the relationship between objects, unit names and source
15956 files. It can also be used to check the source dependencies of a unit
15957 as well as various characteristics.
15958
15959 @menu
15960 * Running gnatls::
15961 * Switches for gnatls::
15962 * Examples of gnatls Usage::
15963 @end menu
15964
15965 @node Running gnatls
15966 @section Running @code{gnatls}
15967
15968 @noindent
15969 The @code{gnatls} command has the form
15970
15971 @smallexample
15972 $ gnatls switches @var{object_or_ali_file}
15973 @end smallexample
15974
15975 @noindent
15976 The main argument is the list of object or @file{ali} files
15977 (@pxref{The Ada Library Information Files})
15978 for which information is requested.
15979
15980 In normal mode, without additional option, @code{gnatls} produces a
15981 four-column listing. Each line represents information for a specific
15982 object. The first column gives the full path of the object, the second
15983 column gives the name of the principal unit in this object, the third
15984 column gives the status of the source and the fourth column gives the
15985 full path of the source representing this unit.
15986 Here is a simple example of use:
15987
15988 @smallexample
15989 $ gnatls *.o
15990 ^./^[]^demo1.o            demo1            DIF demo1.adb
15991 ^./^[]^demo2.o            demo2             OK demo2.adb
15992 ^./^[]^hello.o            h1                OK hello.adb
15993 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15994 ^./^[]^instr.o            instr             OK instr.adb
15995 ^./^[]^tef.o              tef              DIF tef.adb
15996 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15997 ^./^[]^tgef.o             tgef             DIF tgef.adb
15998 @end smallexample
15999
16000 @noindent
16001 The first line can be interpreted as follows: the main unit which is
16002 contained in
16003 object file @file{demo1.o} is demo1, whose main source is in
16004 @file{demo1.adb}. Furthermore, the version of the source used for the
16005 compilation of demo1 has been modified (DIF). Each source file has a status
16006 qualifier which can be:
16007
16008 @table @code
16009 @item OK (unchanged)
16010 The version of the source file used for the compilation of the
16011 specified unit corresponds exactly to the actual source file.
16012
16013 @item MOK (slightly modified)
16014 The version of the source file used for the compilation of the
16015 specified unit differs from the actual source file but not enough to
16016 require recompilation. If you use gnatmake with the qualifier
16017 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16018 MOK will not be recompiled.
16019
16020 @item DIF (modified)
16021 No version of the source found on the path corresponds to the source
16022 used to build this object.
16023
16024 @item ??? (file not found)
16025 No source file was found for this unit.
16026
16027 @item HID (hidden,  unchanged version not first on PATH)
16028 The version of the source that corresponds exactly to the source used
16029 for compilation has been found on the path but it is hidden by another
16030 version of the same source that has been modified.
16031
16032 @end table
16033
16034 @node Switches for gnatls
16035 @section Switches for @code{gnatls}
16036
16037 @noindent
16038 @code{gnatls} recognizes the following switches:
16039
16040 @table @option
16041 @c !sort!
16042 @item ^-a^/ALL_UNITS^
16043 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
16044 Consider all units, including those of the predefined Ada library.
16045 Especially useful with @option{^-d^/DEPENDENCIES^}.
16046
16047 @item ^-d^/DEPENDENCIES^
16048 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16049 List sources from which specified units depend on.
16050
16051 @item ^-h^/OUTPUT=OPTIONS^
16052 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16053 Output the list of options.
16054
16055 @item ^-o^/OUTPUT=OBJECTS^
16056 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16057 Only output information about object files.
16058
16059 @item ^-s^/OUTPUT=SOURCES^
16060 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16061 Only output information about source files.
16062
16063 @item ^-u^/OUTPUT=UNITS^
16064 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16065 Only output information about compilation units.
16066
16067 @item ^-files^/FILES^=@var{file}
16068 @cindex @option{^-files^/FILES^} (@code{gnatls})
16069 Take as arguments the files listed in text file @var{file}.
16070 Text file @var{file} may contain empty lines that are ignored.
16071 Each non empty line should contain the name of an existing file.
16072 Several such switches may be specified simultaneously.
16073
16074 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16075 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16076 @itemx ^-I^/SEARCH=^@var{dir}
16077 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
16078 @itemx -nostdinc
16079 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16080 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16081 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16082 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16083 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
16084 (see @ref{Switches for gnatmake}).
16085
16086 @item --RTS=@var{rts-path}
16087 @cindex @option{--RTS} (@code{gnatls})
16088 Specifies the default location of the runtime library. Same meaning as the
16089 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
16090
16091 @item ^-v^/OUTPUT=VERBOSE^
16092 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16093 Verbose mode. Output the complete source and object paths. Do not use
16094 the default column layout but instead use long format giving as much as
16095 information possible on each requested units, including special
16096 characteristics such as:
16097
16098 @table @code
16099 @item  Preelaborable
16100 The unit is preelaborable in the Ada 95 sense.
16101
16102 @item No_Elab_Code
16103 No elaboration code has been produced by the compiler for this unit.
16104
16105 @item Pure
16106 The unit is pure in the Ada 95 sense.
16107
16108 @item Elaborate_Body
16109 The unit contains a pragma Elaborate_Body.
16110
16111 @item Remote_Types
16112 The unit contains a pragma Remote_Types.
16113
16114 @item Shared_Passive
16115 The unit contains a pragma Shared_Passive.
16116
16117 @item Predefined
16118 This unit is part of the predefined environment and cannot be modified
16119 by the user.
16120
16121 @item Remote_Call_Interface
16122 The unit contains a pragma Remote_Call_Interface.
16123
16124 @end table
16125
16126 @end table
16127
16128 @node Examples of gnatls Usage
16129 @section Example of @code{gnatls} Usage
16130 @ifclear vms
16131
16132 @noindent
16133 Example of using the verbose switch. Note how the source and
16134 object paths are affected by the -I switch.
16135
16136 @smallexample
16137 $ gnatls -v -I.. demo1.o
16138
16139 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
16140
16141 Source Search Path:
16142    <Current_Directory>
16143    ../
16144    /home/comar/local/adainclude/
16145
16146 Object Search Path:
16147    <Current_Directory>
16148    ../
16149    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
16150
16151 ./demo1.o
16152    Unit =>
16153      Name   => demo1
16154      Kind   => subprogram body
16155      Flags  => No_Elab_Code
16156      Source => demo1.adb    modified
16157 @end smallexample
16158
16159 @noindent
16160 The following is an example of use of the dependency list.
16161 Note the use of the -s switch
16162 which gives a straight list of source files. This can be useful for
16163 building specialized scripts.
16164
16165 @smallexample
16166 $ gnatls -d demo2.o
16167 ./demo2.o   demo2        OK demo2.adb
16168                          OK gen_list.ads
16169                          OK gen_list.adb
16170                          OK instr.ads
16171                          OK instr-child.ads
16172
16173 $ gnatls -d -s -a demo1.o
16174 demo1.adb
16175 /home/comar/local/adainclude/ada.ads
16176 /home/comar/local/adainclude/a-finali.ads
16177 /home/comar/local/adainclude/a-filico.ads
16178 /home/comar/local/adainclude/a-stream.ads
16179 /home/comar/local/adainclude/a-tags.ads
16180 gen_list.ads
16181 gen_list.adb
16182 /home/comar/local/adainclude/gnat.ads
16183 /home/comar/local/adainclude/g-io.ads
16184 instr.ads
16185 /home/comar/local/adainclude/system.ads
16186 /home/comar/local/adainclude/s-exctab.ads
16187 /home/comar/local/adainclude/s-finimp.ads
16188 /home/comar/local/adainclude/s-finroo.ads
16189 /home/comar/local/adainclude/s-secsta.ads
16190 /home/comar/local/adainclude/s-stalib.ads
16191 /home/comar/local/adainclude/s-stoele.ads
16192 /home/comar/local/adainclude/s-stratt.ads
16193 /home/comar/local/adainclude/s-tasoli.ads
16194 /home/comar/local/adainclude/s-unstyp.ads
16195 /home/comar/local/adainclude/unchconv.ads
16196 @end smallexample
16197 @end ifclear
16198
16199 @ifset vms
16200 @smallexample
16201 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16202
16203 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16204 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16205 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16206 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16207 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16208 demo1.adb
16209 gen_list.ads
16210 gen_list.adb
16211 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16212 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16213 instr.ads
16214 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16215 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16216 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16217 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16218 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16219 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16220 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16221 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16222 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16223 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16224 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16225 @end smallexample
16226 @end ifset
16227
16228 @node Cleaning Up Using gnatclean
16229 @chapter Cleaning Up Using @code{gnatclean}
16230 @findex gnatclean
16231 @cindex Cleaning tool
16232
16233 @noindent
16234 @code{gnatclean} is a tool that allows the deletion of files produced by the
16235 compiler, binder and linker, including ALI files, object files, tree files,
16236 expanded source files, library files, interface copy source files, binder
16237 generated files and executable files.
16238
16239 @menu
16240 * Running gnatclean::
16241 * Switches for gnatclean::
16242 * Examples of gnatclean Usage::
16243 @end menu
16244
16245 @node Running gnatclean
16246 @section Running @code{gnatclean}
16247
16248 @noindent
16249 The @code{gnatclean} command has the form:
16250
16251 @smallexample
16252 $ gnatclean switches @var{names}
16253 @end smallexample
16254
16255 @noindent
16256 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16257 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16258 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16259
16260 @noindent
16261 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16262 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16263 the linker. In informative-only mode, specified by switch
16264 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16265 normal mode is listed, but no file is actually deleted.
16266
16267 @node Switches for gnatclean
16268 @section Switches for @code{gnatclean}
16269
16270 @noindent
16271 @code{gnatclean} recognizes the following switches:
16272
16273 @table @option
16274 @c !sort!
16275 @item ^-c^/COMPILER_FILES_ONLY^
16276 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16277 Only attempt to delete the files produced by the compiler, not those produced
16278 by the binder or the linker. The files that are not to be deleted are library
16279 files, interface copy files, binder generated files and executable files.
16280
16281 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16282 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16283 Indicate that ALI and object files should normally be found in directory
16284 @var{dir}.
16285
16286 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16287 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16288 When using project files, if some errors or warnings are detected during
16289 parsing and verbose mode is not in effect (no use of switch
16290 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16291 file, rather than its simple file name.
16292
16293 @item ^-h^/HELP^
16294 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16295 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16296
16297 @item ^-n^/NODELETE^
16298 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16299 Informative-only mode. Do not delete any files. Output the list of the files
16300 that would have been deleted if this switch was not specified.
16301
16302 @item ^-P^/PROJECT_FILE=^@var{project}
16303 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16304 Use project file @var{project}. Only one such switch can be used.
16305 When cleaning a project file, the files produced by the compilation of the
16306 immediate sources or inherited sources of the project files are to be
16307 deleted. This is not depending on the presence or not of executable names
16308 on the command line.
16309
16310 @item ^-q^/QUIET^
16311 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16312 Quiet output. If there are no error, do not ouuput anything, except in
16313 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16314 (switch ^-n^/NODELETE^).
16315
16316 @item ^-r^/RECURSIVE^
16317 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16318 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16319 clean all imported and extended project files, recursively. If this switch
16320 is not specified, only the files related to the main project file are to be
16321 deleted. This switch has no effect if no project file is specified.
16322
16323 @item ^-v^/VERBOSE^
16324 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16325 Verbose mode.
16326
16327 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16328 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16329 Indicates the verbosity of the parsing of GNAT project files.
16330 See @ref{Switches Related to Project Files}.
16331
16332 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16333 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16334 Indicates that external variable @var{name} has the value @var{value}.
16335 The Project Manager will use this value for occurrences of
16336 @code{external(name)} when parsing the project file.
16337 See @ref{Switches Related to Project Files}.
16338
16339 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16340 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16341 When searching for ALI and object files, look in directory
16342 @var{dir}.
16343
16344 @item ^-I^/SEARCH=^@var{dir}
16345 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16346 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16347
16348 @item ^-I-^/NOCURRENT_DIRECTORY^
16349 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16350 @cindex Source files, suppressing search
16351 Do not look for ALI or object files in the directory
16352 where @code{gnatclean} was invoked.
16353
16354 @end table
16355
16356 @node Examples of gnatclean Usage
16357 @section Examples of @code{gnatclean} Usage
16358
16359 @ifclear vms
16360 @node GNAT and Libraries
16361 @chapter GNAT and Libraries
16362 @cindex Library, building, installing, using
16363
16364 @noindent
16365 This chapter describes how to build and use
16366 libraries with GNAT, and also shows how to recompile the GNAT run-time library.
16367 You should be familiar with the
16368 Project Manager facility (see @ref{GNAT Project Manager}) before reading this
16369 chapter.
16370
16371 @menu
16372 * Introduction to Libraries in GNAT::
16373 * General Ada Libraries::
16374 * Stand-alone Ada Libraries::
16375 * Rebuilding the GNAT Run-Time Library::
16376 @end menu
16377
16378 @node Introduction to Libraries in GNAT
16379 @section Introduction to Libraries in GNAT
16380
16381 @noindent
16382 A library is, conceptually, a collection of objects which does not have its
16383 own main thread of execution, but rather provides certain services to the
16384 applications that use it. A library can be either statically linked with the
16385 application, in which case its code is directly included in the application,
16386 or, on platforms that support it, be dynamically linked, in which case
16387 its code is shared by all applications making use of this library.
16388
16389 GNAT supports both types of libraries.
16390 In the static case, the compiled code can be provided in different ways.
16391 The simplest approach is to provide directly the
16392 set of objects resulting from compilation of the library source files.
16393 Alternatively, you can group the objects into an archive using whatever
16394 commands are provided by the operating system. For the latter case,
16395 the objects are grouped into a shared library.
16396
16397 In the GNAT environment, a library has two types of components:
16398 @itemize @bullet
16399 @item
16400 Source files.
16401 @item
16402 Compiled code and @file{ALI} files.
16403 See @ref{The Ada Library Information Files}.
16404 @end itemize
16405
16406 @noindent
16407 A GNAT library may either completely expose its source files to the
16408 compilation context of the user's application.
16409 Alternatively, it may expose
16410 a limited subset of its source files, called @emph{interface units},
16411 in which case the library is referred to as a @emph{stand-alone library}
16412 (see @ref{Stand-alone Ada Libraries}). In addition, GNAT fully supports
16413 foreign libraries, which are only available in the object format.
16414
16415 All compilation units comprising
16416 an application are elaborated, in an order partially defined by Ada language
16417 semantics.
16418 Where possible, GNAT provides facilities
16419 to ensure that compilation units of a library are automatically elaborated;
16420 however, there are cases where this must be responsibility of a user. This will
16421 be addressed in greater detail below.
16422
16423 @node General Ada Libraries
16424 @section General Ada Libraries
16425
16426 @menu
16427 * Building the library::
16428 * Installing the library::
16429 * Using the library::
16430 @end menu
16431
16432 @node Building the library
16433 @subsection Building the library
16434
16435 @noindent
16436 The easiest way to build a library is to use the Project Manager,
16437 which supports a special type of projects called Library Projects
16438 (see @ref{Library Projects}).
16439
16440 A project is considered a library project, when two project-level attributes
16441 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
16442 control different aspects of library configuration, additional optional
16443 project-level attributes can be specified:
16444 @table @code
16445 @item Library_Kind
16446 This attribute controls whether the library is to be static or shared
16447
16448 @item Library_Version
16449 This attribute specifies what is the library version; this value is used
16450 during dynamic linking of shared libraries to determine if the currently
16451 installed versions of the binaries are compatible.
16452
16453 @item Library_Options
16454 @item Library_GCC
16455 These attributes specify additional low-level options to be used during
16456 library generation, and redefine the actual application used to generate
16457 library.
16458 @end table
16459
16460 @noindent
16461 The GNAT Project Manager takes full care of the library maintenance task,
16462 including recompilation of the source files for which objects do not exist
16463 or are not up to date, assembly of the library archive, and installation of
16464 the library, i.e. copying associated source, object and @file{ALI} files
16465 to the specified location.
16466
16467 It is not entirely trivial to correctly perform all the steps required to
16468 produce a library. We recommend that you use the GNAT Project Manager
16469 for this task. In special cases where this is not desired, the necessary
16470 steps are discussed below.
16471
16472 There are various possibilities for compiling the units that make up the
16473 library: for example with a Makefile (see @ref{Using the GNU make Utility})
16474 or with a conventional script.
16475 For simple libraries, it is also possible to create a
16476 dummy main program which depends upon all the packages that comprise the
16477 interface of the library. This dummy main program can then be given to
16478 @command{gnatmake}, which will ensure that all necessary objects are built.
16479
16480 After this task is accomplished, you should follow the standard procedure
16481 of the underlying operating system to produce the static or shared library.
16482
16483 Here is an example of such a dummy program:
16484 @smallexample @c ada
16485 @group
16486 with My_Lib.Service1;
16487 with My_Lib.Service2;
16488 with My_Lib.Service3;
16489 procedure My_Lib_Dummy is
16490 begin
16491    null;
16492 end;
16493 @end group
16494 @end smallexample
16495
16496 @noindent
16497 Here are the generic commands that will build an archive or a shared library.
16498
16499 @smallexample
16500 # compiling the library
16501 $ gnatmake -c my_lib_dummy.adb
16502
16503 # we don't need the dummy object itself
16504 $ rm my_lib_dummy.o my_lib_dummy.ali
16505
16506 # create an archive with the remaining objects
16507 $ ar rc libmy_lib.a *.o
16508 # some systems may require "ranlib" to be run as well
16509
16510 # or create a shared library
16511 $ gcc -shared -o libmy_lib.so *.o
16512 # some systems may require the code to have been compiled with -fPIC
16513
16514 # remove the object files that are now in the library
16515 $ rm *.o
16516
16517 # Make the ALI files read-only so that gnatmake will not try to
16518 # regenerate the objects that are in the library
16519 $ chmod -w *.ali
16520 @end smallexample
16521
16522 @noindent
16523 Please note that the library must have a name of the form @file{libxxx.a} or
16524 @file{libxxx.so} in order to be accessed by the directive @option{-lxxx}
16525 at link time.
16526
16527 @node Installing the library
16528 @subsection Installing the library
16529
16530 @noindent
16531 In the GNAT model, installing a library consists in copying into a specific
16532 location the files that make up this library. When the library is built using
16533 projects, it is automatically installed in the location specified in the
16534 project by means of the attribute @code{Library_Dir},
16535 otherwise the user must specify the destination.
16536 GNAT also supports installing the sources in a
16537 different directory from the other files (@file{ALI}, objects, archives)
16538 since the source path and the object path can be specified separately.
16539
16540 The system administrator can place general purpose libraries in the default
16541 compiler paths, by specifying the libraries' location in the configuration
16542 files @file{ada_source_path} and @file{ada_object_path}.
16543 These configuration files must be located in the GNAT
16544 installation tree at the same place as the gcc spec file. The location of
16545 the gcc spec file can be determined as follows:
16546 @smallexample
16547 $ gcc -v
16548 @end smallexample
16549
16550 @noindent
16551 The configuration files mentioned above have a simple format: each line
16552 must contain one unique directory name.
16553 Those names are added to the corresponding path
16554 in their order of appearance in the file. The names can be either absolute
16555 or relative; in the latter case, they are relative to where theses files
16556 are located.
16557
16558 The files @file{ada_source_path} and @file{ada_object_path} might not be
16559 present in a
16560 GNAT installation, in which case, GNAT will look for its run-time library in
16561 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
16562 objects and @file{ALI} files). When the files exist, the compiler does not
16563 look in @file{adainclude} and @file{adalib}, and thus the
16564 @file{ada_source_path} file
16565 must contain the location for the GNAT run-time sources (which can simply
16566 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16567 contain the location for the GNAT run-time objects (which can simply
16568 be @file{adalib}).
16569
16570 You can also specify a new default path to the run-time library at compilation
16571 time with the switch @option{--RTS=rts-path}. You can thus choose / change
16572 the run-time library you want your program to be compiled with. This switch is
16573 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
16574 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
16575
16576 It is possible to install a library before or after the standard GNAT
16577 library, by reordering the lines in the configuration files. In general, a
16578 library must be installed before the GNAT library if it redefines
16579 any part of it.
16580
16581
16582 @node Using the library
16583 @subsection Using the library
16584
16585 @noindent
16586 Once again, the project facility greatly simplifies the addition of libraries
16587 to the compilation. If the project file for an application lists a library
16588 project in its @code{with} clause, the Project Manager will ensure that the
16589 library files are consistent, and that they are considered during the
16590 compilation and linking of the application.
16591
16592 Even if you have a third-party, non-Ada library, you can still use GNAT's
16593 Project Manager facility to provide a wrapper for it. The following project for
16594 example, when @code{with}ed in your main project, will link with the
16595 third-party library @file{liba.a}:
16596
16597 @smallexample @c projectfile
16598 @group
16599 project Liba is
16600    for Source_Dirs use ();
16601    for Library_Dir use "lib";
16602    for Library_Name use "a";
16603    for Library_Kind use "static";
16604 end Liba;
16605 @end group
16606 @end smallexample
16607
16608 @noindent
16609 In order to use an Ada library manually, you need to make sure that this
16610 library is on both your source and object path
16611 (see @ref{Search Paths and the Run-Time Library (RTL)},
16612 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
16613 in an archive or a shared library, you need to specify the desired
16614 library at link time.
16615
16616 For example, you can use the library @file{mylib} installed in
16617 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16618
16619 @smallexample
16620 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16621   -largs -lmy_lib
16622 @end smallexample
16623
16624 @noindent
16625 This can be expressed more simply:
16626 @smallexample
16627 $ gnatmake my_appl
16628 @end smallexample
16629 @noindent
16630 when the following conditions are met:
16631 @itemize @bullet
16632 @item
16633 @file{/dir/my_lib_src} has been added by the user to the environment
16634 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
16635 @file{ada_source_path}
16636 @item
16637 @file{/dir/my_lib_obj} has been added by the user to the environment
16638 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
16639 @file{ada_object_path}
16640 @item
16641 a pragma @code{Linker_Options} has been added to one of the sources.
16642 For example:
16643
16644 @smallexample @c ada
16645 pragma Linker_Options ("-lmy_lib");
16646 @end smallexample
16647 @end itemize
16648
16649
16650 @node Stand-alone Ada Libraries
16651 @section Stand-alone Ada Libraries
16652 @cindex Stand-alone library, building, using
16653
16654 @menu
16655 * Introduction to Stand-alone Libraries::
16656 * Building a Stand-alone Library::
16657 * Creating a Stand-alone Library to be used in a non-Ada context::
16658 * Restrictions in Stand-alone Libraries::
16659 @end menu
16660
16661 @node Introduction to Stand-alone Libraries
16662 @subsection Introduction to Stand-alone Libraries
16663
16664 @noindent
16665 A Stand-alone Library (SAL) is a library that contains the necessary code to
16666 elaborate the Ada units that are included in the library. In contrast with
16667 an ordinary library, which consists of all sources, objects and @file{ALI}
16668 files of the
16669 library, a SAL may specify a restricted subset of compilation units
16670 to serve as a library interface. In this case, the fully
16671 self-sufficient set of files will normally consist of an objects
16672 archive, the sources of interface units' specs, and the @file{ALI}
16673 files of interface units.
16674 If an interface spec contains a generic unit or an inlined subprogram,
16675 the body's
16676 source must also be provided; if the units that must be provided in the source
16677 form depend on other units, the source and @file{ALI} files of those must
16678 also be provided.
16679
16680 The main purpose of a SAL is to minimize the recompilation overhead of client
16681 applications when a new version of the library is installed. Specifically,
16682 if the interface sources have not changed, client applications do not need to
16683 be recompiled. If, furthermore, a SAL is provided in the shared form and its
16684 version, controlled by @code{Library_Version} attribute, is not changed,
16685 then the clients do not need to be relinked.
16686
16687 SALs also allow the library providers to minimize the amount of library source
16688 text exposed to the clients.  Such ``information hiding'' might be useful or
16689 necessary for various reasons.
16690
16691 Stand-alone libraries are also well suited to be used in an executable whose
16692 main routine is not written in Ada.
16693
16694 @node Building a Stand-alone Library
16695 @subsection Building a Stand-alone Library
16696
16697 @noindent
16698 GNAT's Project facility provides a simple way of building and installing
16699 stand-alone libraries; see @ref{Stand-alone Library Projects}.
16700 To be a Stand-alone Library Project, in addition to the two attributes
16701 that make a project a Library Project (@code{Library_Name} and
16702 @code{Library_Dir}; see @ref{Library Projects}), the attribute
16703 @code{Library_Interface} must be defined.  For example:
16704
16705 @smallexample @c projectfile
16706 @group
16707    for Library_Dir use "lib_dir";
16708    for Library_Name use "dummy";
16709    for Library_Interface use ("int1", "int1.child");
16710 @end group
16711 @end smallexample
16712
16713 @noindent
16714 Attribute @code{Library_Interface} has a non empty string list value,
16715 each string in the list designating a unit contained in an immediate source
16716 of the project file.
16717
16718 When a Stand-alone Library is built, first the binder is invoked to build
16719 a package whose name depends on the library name
16720 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16721 This binder-generated package includes initialization and
16722 finalization procedures whose
16723 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16724 in the example
16725 above). The object corresponding to this package is included in the library.
16726
16727 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16728 calling of these procedures if a static SAL is built, or if a shared SAL
16729 is built
16730 with the project-level attribute @code{Library_Auto_Init} set to
16731 @code{"false"}.
16732
16733 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16734 (those that are listed in attribute @code{Library_Interface}) are copied to
16735 the Library Directory. As a consequence, only the Interface Units may be
16736 imported from Ada units outside of the library. If other units are imported,
16737 the binding phase will fail.
16738
16739 The attribute @code{Library_Src_Dir} may be specified for a
16740 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16741 single string value. Its value must be the path (absolute or relative to the
16742 project directory) of an existing directory. This directory cannot be the
16743 object directory or one of the source directories, but it can be the same as
16744 the library directory. The sources of the Interface
16745 Units of the library that are needed by an Ada client of the library will be
16746 copied to the designated directory, called the Interface Copy directory.
16747 These sources includes the specs of the Interface Units, but they may also
16748 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16749 are used, or when there is a generic unit in the spec. Before the sources
16750 are copied to the Interface Copy directory, an attempt is made to delete all
16751 files in the Interface Copy directory.
16752
16753 Building stand-alone libraries by hand is somewhat tedious, but for those
16754 occasions when it is necessary here are the steps that you need to perform:
16755 @itemize @bullet
16756 @item
16757 Compile all library sources.
16758
16759 @item
16760 Invoke the binder with the switch @option{-n} (No Ada main program),
16761 with all the @file{ALI} files of the interfaces, and
16762 with the switch @option{-L} to give specific names to the @code{init}
16763 and @code{final} procedures.  For example:
16764 @smallexample
16765   gnatbind -n int1.ali int2.ali -Lsal1
16766 @end smallexample
16767
16768 @item
16769 Compile the binder generated file:
16770 @smallexample
16771   gcc -c b~int2.adb
16772 @end smallexample
16773
16774 @item
16775 Link the dynamic library with all the necessary object files,
16776 indicating to the linker the names of the @code{init} (and possibly
16777 @code{final}) procedures for automatic initialization (and finalization).
16778 The built library should be placed in a directory different from
16779 the object directory.
16780
16781 @item
16782 Copy the @code{ALI} files of the interface to the library directory,
16783 add in this copy an indication that it is an interface to a SAL
16784 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
16785 with letter ``P'') and make the modified copy of the @file{ALI} file
16786 read-only.
16787 @end itemize
16788
16789 @noindent
16790 Using SALs is not different from using other libraries
16791 (see @ref{Using the library}).
16792
16793 @node Creating a Stand-alone Library to be used in a non-Ada context
16794 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16795
16796 @noindent
16797 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16798 a non-Ada context.
16799
16800 The only extra step required is to ensure that library interface subprograms
16801 are compatible with the main program, by means of @code{pragma Export}
16802 or @code{pragma Convention}.
16803
16804 Here is an example of simple library interface for use with C main program:
16805
16806 @smallexample @c ada
16807 package Interface is
16808
16809    procedure Do_Something;
16810    pragma Export (C, Do_Something, "do_something");
16811
16812    procedure Do_Something_Else;
16813    pragma Export (C, Do_Something_Else, "do_something_else");
16814
16815 end Interface;
16816 @end smallexample
16817
16818 @noindent
16819 On the foreign language side, you must provide a ``foreign'' view of the
16820 library interface; remember that it should contain elaboration routines in
16821 addition to interface subprograms.
16822
16823 The example below shows the content of @code{mylib_interface.h} (note
16824 that there is no rule for the naming of this file, any name can be used)
16825 @smallexample
16826 /* the library elaboration procedure */
16827 extern void mylibinit (void);
16828
16829 /* the library finalization procedure */
16830 extern void mylibfinal (void);
16831
16832 /* the interface exported by the library */
16833 extern void do_something (void);
16834 extern void do_something_else (void);
16835 @end smallexample
16836
16837 @noindent
16838 Libraries built as explained above can be used from any program, provided
16839 that the elaboration procedures (named @code{mylibinit} in the previous
16840 example) are called before the library services are used. Any number of
16841 libraries can be used simultaneously, as long as the elaboration
16842 procedure of each library is called.
16843
16844 Below is an example of C program that uses the @code{mylib} library.
16845
16846 @smallexample
16847 #include "mylib_interface.h"
16848
16849 int
16850 main (void)
16851 @{
16852    /* First, elaborate the library before using it */
16853    mylibinit ();
16854
16855    /* Main program, using the library exported entities */
16856    do_something ();
16857    do_something_else ();
16858
16859    /* Library finalization at the end of the program */
16860    mylibfinal ();
16861    return 0;
16862 @}
16863 @end smallexample
16864
16865 @noindent
16866 Note that invoking any library finalization procedure generated by
16867 @code{gnatbind} shuts down the Ada run-time environment.
16868 Consequently, the
16869 finalization of all Ada libraries must be performed at the end of the program.
16870 No call to these libraries nor to the Ada run-time library should be made
16871 after the finalization phase.
16872
16873 @node Restrictions in Stand-alone Libraries
16874 @subsection Restrictions in Stand-alone Libraries
16875
16876 @noindent
16877 The pragmas listed below should be used with caution inside libraries,
16878 as they can create incompatibilities with other Ada libraries:
16879 @itemize @bullet
16880 @item pragma @code{Locking_Policy}
16881 @item pragma @code{Queuing_Policy}
16882 @item pragma @code{Task_Dispatching_Policy}
16883 @item pragma @code{Unreserve_All_Interrupts}
16884 @end itemize
16885
16886 @noindent
16887 When using a library that contains such pragmas, the user must make sure
16888 that all libraries use the same pragmas with the same values. Otherwise,
16889 @code{Program_Error} will
16890 be raised during the elaboration of the conflicting
16891 libraries. The usage of these pragmas and its consequences for the user
16892 should therefore be well documented.
16893
16894 Similarly, the traceback in the exception occurrence mechanism should be
16895 enabled or disabled in a consistent manner across all libraries.
16896 Otherwise, Program_Error will be raised during the elaboration of the
16897 conflicting libraries.
16898
16899 If the @code{Version} or @code{Body_Version}
16900 attributes are used inside a library, then you need to
16901 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16902 libraries, so that version identifiers can be properly computed.
16903 In practice these attributes are rarely used, so this is unlikely
16904 to be a consideration.
16905
16906 @node  Rebuilding the GNAT Run-Time Library
16907 @section Rebuilding the GNAT Run-Time Library
16908 @cindex GNAT Run-Time Library, rebuilding
16909
16910 @noindent
16911 It may be useful to recompile the GNAT library in various contexts, the
16912 most important one being the use of partition-wide configuration pragmas
16913 such as @code{Normalize_Scalars}. A special Makefile called
16914 @code{Makefile.adalib} is provided to that effect and can be found in
16915 the directory containing the GNAT library. The location of this
16916 directory depends on the way the GNAT environment has been installed and can
16917 be determined by means of the command:
16918
16919 @smallexample
16920 $ gnatls -v
16921 @end smallexample
16922
16923 @noindent
16924 The last entry in the object search path usually contains the
16925 gnat library. This Makefile contains its own documentation and in
16926 particular the set of instructions needed to rebuild a new library and
16927 to use it.
16928
16929
16930 @node Using the GNU make Utility
16931 @chapter Using the GNU @code{make} Utility
16932 @findex make
16933
16934 @noindent
16935 This chapter offers some examples of makefiles that solve specific
16936 problems. It does not explain how to write a makefile (see the GNU make
16937 documentation), nor does it try to replace the @code{gnatmake} utility
16938 (@pxref{The GNAT Make Program gnatmake}).
16939
16940 All the examples in this section are specific to the GNU version of
16941 make. Although @code{make} is a standard utility, and the basic language
16942 is the same, these examples use some advanced features found only in
16943 @code{GNU make}.
16944
16945 @menu
16946 * Using gnatmake in a Makefile::
16947 * Automatically Creating a List of Directories::
16948 * Generating the Command Line Switches::
16949 * Overcoming Command Line Length Limits::
16950 @end menu
16951
16952 @node Using gnatmake in a Makefile
16953 @section Using gnatmake in a Makefile
16954 @findex makefile
16955 @cindex GNU make
16956
16957 @noindent
16958 Complex project organizations can be handled in a very powerful way by
16959 using GNU make combined with gnatmake. For instance, here is a Makefile
16960 which allows you to build each subsystem of a big project into a separate
16961 shared library. Such a makefile allows you to significantly reduce the link
16962 time of very big applications while maintaining full coherence at
16963 each step of the build process.
16964
16965 The list of dependencies are handled automatically by
16966 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
16967 the appropriate directories.
16968
16969 Note that you should also read the example on how to automatically
16970 create the list of directories
16971 (@pxref{Automatically Creating a List of Directories})
16972 which might help you in case your project has a lot of subdirectories.
16973
16974 @smallexample
16975 @iftex
16976 @leftskip=0cm
16977 @font@heightrm=cmr8
16978 @heightrm
16979 @end iftex
16980 ## This Makefile is intended to be used with the following directory
16981 ## configuration:
16982 ##  - The sources are split into a series of csc (computer software components)
16983 ##    Each of these csc is put in its own directory.
16984 ##    Their name are referenced by the directory names.
16985 ##    They will be compiled into shared library (although this would also work
16986 ##    with static libraries
16987 ##  - The main program (and possibly other packages that do not belong to any
16988 ##    csc is put in the top level directory (where the Makefile is).
16989 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16990 ##                    \_ second_csc (sources) __ lib (will contain the library)
16991 ##                    \_ ...
16992 ## Although this Makefile is build for shared library, it is easy to modify
16993 ## to build partial link objects instead (modify the lines with -shared and
16994 ## gnatlink below)
16995 ##
16996 ## With this makefile, you can change any file in the system or add any new
16997 ## file, and everything will be recompiled correctly (only the relevant shared
16998 ## objects will be recompiled, and the main program will be re-linked).
16999
17000 # The list of computer software component for your project. This might be
17001 # generated automatically.
17002 CSC_LIST=aa bb cc
17003
17004 # Name of the main program (no extension)
17005 MAIN=main
17006
17007 # If we need to build objects with -fPIC, uncomment the following line
17008 #NEED_FPIC=-fPIC
17009
17010 # The following variable should give the directory containing libgnat.so
17011 # You can get this directory through 'gnatls -v'. This is usually the last
17012 # directory in the Object_Path.
17013 GLIB=...
17014
17015 # The directories for the libraries
17016 # (This macro expands the list of CSC to the list of shared libraries, you
17017 # could simply use the expanded form :
17018 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17019 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17020
17021 $@{MAIN@}: objects $@{LIB_DIR@}
17022     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17023     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17024
17025 objects::
17026     # recompile the sources
17027     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17028
17029 # Note: In a future version of GNAT, the following commands will be simplified
17030 # by a new tool, gnatmlib
17031 $@{LIB_DIR@}:
17032     mkdir -p $@{dir $@@ @}
17033     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17034     cd $@{dir $@@ @}; cp -f ../*.ali .
17035
17036 # The dependencies for the modules
17037 # Note that we have to force the expansion of *.o, since in some cases
17038 # make won't be able to do it itself.
17039 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17040 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17041 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17042
17043 # Make sure all of the shared libraries are in the path before starting the
17044 # program
17045 run::
17046     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17047
17048 clean::
17049     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17050     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17051     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17052     $@{RM@} *.o *.ali $@{MAIN@}
17053 @end smallexample
17054
17055 @node Automatically Creating a List of Directories
17056 @section Automatically Creating a List of Directories
17057
17058 @noindent
17059 In most makefiles, you will have to specify a list of directories, and
17060 store it in a variable. For small projects, it is often easier to
17061 specify each of them by hand, since you then have full control over what
17062 is the proper order for these directories, which ones should be
17063 included...
17064
17065 However, in larger projects, which might involve hundreds of
17066 subdirectories, it might be more convenient to generate this list
17067 automatically.
17068
17069 The example below presents two methods. The first one, although less
17070 general, gives you more control over the list. It involves wildcard
17071 characters, that are automatically expanded by @code{make}. Its
17072 shortcoming is that you need to explicitly specify some of the
17073 organization of your project, such as for instance the directory tree
17074 depth, whether some directories are found in a separate tree,...
17075
17076 The second method is the most general one. It requires an external
17077 program, called @code{find}, which is standard on all Unix systems. All
17078 the directories found under a given root directory will be added to the
17079 list.
17080
17081 @smallexample
17082 @iftex
17083 @leftskip=0cm
17084 @font@heightrm=cmr8
17085 @heightrm
17086 @end iftex
17087 # The examples below are based on the following directory hierarchy:
17088 # All the directories can contain any number of files
17089 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17090 #                       ->  ab
17091 #                       ->  ac
17092 #                ->  b  ->  ba  ->  baa
17093 #                       ->  bb
17094 #                       ->  bc
17095 # This Makefile creates a variable called DIRS, that can be reused any time
17096 # you need this list (see the other examples in this section)
17097
17098 # The root of your project's directory hierarchy
17099 ROOT_DIRECTORY=.
17100
17101 ####
17102 # First method: specify explicitly the list of directories
17103 # This allows you to specify any subset of all the directories you need.
17104 ####
17105
17106 DIRS := a/aa/ a/ab/ b/ba/
17107
17108 ####
17109 # Second method: use wildcards
17110 # Note that the argument(s) to wildcard below should end with a '/'.
17111 # Since wildcards also return file names, we have to filter them out
17112 # to avoid duplicate directory names.
17113 # We thus use make's @code{dir} and @code{sort} functions.
17114 # It sets DIRs to the following value (note that the directories aaa and baa
17115 # are not given, unless you change the arguments to wildcard).
17116 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17117 ####
17118
17119 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17120                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17121
17122 ####
17123 # Third method: use an external program
17124 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17125 # This is the most complete command: it sets DIRs to the following value:
17126 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17127 ####
17128
17129 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17130
17131 @end smallexample
17132
17133 @node Generating the Command Line Switches
17134 @section Generating the Command Line Switches
17135
17136 @noindent
17137 Once you have created the list of directories as explained in the
17138 previous section (@pxref{Automatically Creating a List of Directories}),
17139 you can easily generate the command line arguments to pass to gnatmake.
17140
17141 For the sake of completeness, this example assumes that the source path
17142 is not the same as the object path, and that you have two separate lists
17143 of directories.
17144
17145 @smallexample
17146 # see "Automatically creating a list of directories" to create
17147 # these variables
17148 SOURCE_DIRS=
17149 OBJECT_DIRS=
17150
17151 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17152 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17153
17154 all:
17155         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17156 @end smallexample
17157
17158 @node Overcoming Command Line Length Limits
17159 @section Overcoming Command Line Length Limits
17160
17161 @noindent
17162 One problem that might be encountered on big projects is that many
17163 operating systems limit the length of the command line. It is thus hard to give
17164 gnatmake the list of source and object directories.
17165
17166 This example shows how you can set up environment variables, which will
17167 make @code{gnatmake} behave exactly as if the directories had been
17168 specified on the command line, but have a much higher length limit (or
17169 even none on most systems).
17170
17171 It assumes that you have created a list of directories in your Makefile,
17172 using one of the methods presented in
17173 @ref{Automatically Creating a List of Directories}.
17174 For the sake of completeness, we assume that the object
17175 path (where the ALI files are found) is different from the sources patch.
17176
17177 Note a small trick in the Makefile below: for efficiency reasons, we
17178 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17179 expanded immediately by @code{make}. This way we overcome the standard
17180 make behavior which is to expand the variables only when they are
17181 actually used.
17182
17183 On Windows, if you are using the standard Windows command shell, you must
17184 replace colons with semicolons in the assignments to these variables.
17185
17186 @smallexample
17187 @iftex
17188 @leftskip=0cm
17189 @font@heightrm=cmr8
17190 @heightrm
17191 @end iftex
17192 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
17193 # This is the same thing as putting the -I arguments on the command line.
17194 # (the equivalent of using -aI on the command line would be to define
17195 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
17196 # You can of course have different values for these variables.
17197 #
17198 # Note also that we need to keep the previous values of these variables, since
17199 # they might have been set before running 'make' to specify where the GNAT
17200 # library is installed.
17201
17202 # see "Automatically creating a list of directories" to create these
17203 # variables
17204 SOURCE_DIRS=
17205 OBJECT_DIRS=
17206
17207 empty:=
17208 space:=$@{empty@} $@{empty@}
17209 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17210 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17211 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17212 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
17213 export ADA_INCLUDE_PATH
17214 export ADA_OBJECT_PATH
17215
17216 all:
17217         gnatmake main_unit
17218 @end smallexample
17219 @end ifclear
17220
17221
17222 @node Finding Memory Problems
17223 @chapter Finding Memory Problems
17224
17225 @noindent
17226 This chapter describes
17227 @ifclear vms
17228 the @command{gnatmem} tool, which can be used to track down
17229 ``memory leaks'', and
17230 @end ifclear
17231 the GNAT Debug Pool facility, which can be used to detect incorrect uses of
17232 access values (including ``dangling references'').
17233
17234 @menu
17235 @ifclear vms
17236 * The gnatmem Tool::
17237 @end ifclear
17238 * The GNAT Debug Pool Facility::
17239 @end menu
17240
17241
17242 @ifclear vms
17243 @node The gnatmem Tool
17244 @section The @command{gnatmem} Tool
17245 @findex gnatmem
17246
17247 @noindent
17248 The @code{gnatmem} utility monitors dynamic allocation and
17249 deallocation activity in a program, and displays information about
17250 incorrect deallocations and possible sources of memory leaks.
17251 It provides three type of information:
17252 @itemize @bullet
17253 @item
17254 General information concerning memory management, such as the total
17255 number of allocations and deallocations, the amount of allocated
17256 memory and the high water mark, i.e. the largest amount of allocated
17257 memory in the course of program execution.
17258
17259 @item
17260 Backtraces for all incorrect deallocations, that is to say deallocations
17261 which do not correspond to a valid allocation.
17262
17263 @item
17264 Information on each allocation that is potentially the origin of a memory
17265 leak.
17266 @end itemize
17267
17268 @menu
17269 * Running gnatmem::
17270 * Switches for gnatmem::
17271 * Example of gnatmem Usage::
17272 @end menu
17273
17274 @node Running gnatmem
17275 @subsection Running @code{gnatmem}
17276
17277 @noindent
17278 @code{gnatmem} makes use of the output created by the special version of
17279 allocation and deallocation routines that record call information. This
17280 allows to obtain accurate dynamic memory usage history at a minimal cost to
17281 the execution speed. Note however, that @code{gnatmem} is not supported on
17282 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
17283 Solaris (sparc and x86) and Windows NT/2000/XP (x86).
17284
17285 @noindent
17286 The @code{gnatmem} command has the form
17287
17288 @smallexample
17289    $ gnatmem [switches] user_program
17290 @end smallexample
17291
17292 @noindent
17293 The program must have been linked with the instrumented version of the
17294 allocation and deallocation routines. This is done by linking with the
17295 @file{libgmem.a} library. For correct symbolic backtrace information,
17296 the user program should be compiled with debugging options
17297 @ref{Switches for gcc}. For example to build @file{my_program}:
17298
17299 @smallexample
17300 $ gnatmake -g my_program -largs -lgmem
17301 @end smallexample
17302
17303 @noindent
17304 When running @file{my_program} the file @file{gmem.out} is produced. This file
17305 contains information about all allocations and deallocations done by the
17306 program. It is produced by the instrumented allocations and
17307 deallocations routines and will be used by @code{gnatmem}.
17308
17309 @noindent
17310 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17311 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17312 @code{-i} switch, gnatmem will assume that this file can be found in the
17313 current directory. For example, after you have executed @file{my_program},
17314 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17315
17316 @smallexample
17317 $ gnatmem my_program
17318 @end smallexample
17319
17320 @noindent
17321 This will produce the output with the following format:
17322
17323 *************** debut cc
17324 @smallexample
17325 $ gnatmem my_program
17326
17327 Global information
17328 ------------------
17329    Total number of allocations        :  45
17330    Total number of deallocations      :   6
17331    Final Water Mark (non freed mem)   :  11.29 Kilobytes
17332    High Water Mark                    :  11.40 Kilobytes
17333
17334 .
17335 .
17336 .
17337 Allocation Root # 2
17338 -------------------
17339  Number of non freed allocations    :  11
17340  Final Water Mark (non freed mem)   :   1.16 Kilobytes
17341  High Water Mark                    :   1.27 Kilobytes
17342  Backtrace                          :
17343    my_program.adb:23 my_program.alloc
17344 .
17345 .
17346 .
17347 @end smallexample
17348
17349 The first block of output gives general information. In this case, the
17350 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17351 Unchecked_Deallocation routine occurred.
17352
17353 @noindent
17354 Subsequent paragraphs display  information on all allocation roots.
17355 An allocation root is a specific point in the execution of the program
17356 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17357 construct. This root is represented by an execution backtrace (or subprogram
17358 call stack). By default the backtrace depth for allocations roots is 1, so
17359 that a root corresponds exactly to a source location. The backtrace can
17360 be made deeper, to make the root more specific.
17361
17362 @node Switches for gnatmem
17363 @subsection Switches for @code{gnatmem}
17364
17365 @noindent
17366 @code{gnatmem} recognizes the following switches:
17367
17368 @table @option
17369
17370 @item -q
17371 @cindex @option{-q} (@code{gnatmem})
17372 Quiet. Gives the minimum output needed to identify the origin of the
17373 memory leaks. Omits statistical information.
17374
17375 @item @var{N}
17376 @cindex @var{N} (@code{gnatmem})
17377 N is an integer literal (usually between 1 and 10) which controls the
17378 depth of the backtraces defining allocation root. The default value for
17379 N is 1. The deeper the backtrace, the more precise the localization of
17380 the root. Note that the total number of roots can depend on this
17381 parameter. This parameter must be specified @emph{before} the name of the
17382 executable to be analyzed, to avoid ambiguity.
17383
17384 @item -b n
17385 @cindex @option{-b} (@code{gnatmem})
17386 This switch has the same effect as just depth parameter.
17387
17388 @item -i @var{file}
17389 @cindex @option{-i} (@code{gnatmem})
17390 Do the @code{gnatmem} processing starting from @file{file}, rather than
17391 @file{gmem.out} in the current directory.
17392
17393 @item -m n
17394 @cindex @option{-m} (@code{gnatmem})
17395 This switch causes @code{gnatmem} to mask the allocation roots that have less
17396 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17397 examine even the roots that didn't result in leaks.
17398
17399 @item -s order
17400 @cindex @option{-s} (@code{gnatmem})
17401 This switch causes @code{gnatmem} to sort the allocation roots according to the
17402 specified order of sort criteria, each identified by a single letter. The
17403 currently supported criteria are @code{n, h, w} standing respectively for
17404 number of unfreed allocations, high watermark, and final watermark
17405 corresponding to a specific root. The default order is @code{nwh}.
17406
17407 @end table
17408
17409 @node Example of gnatmem Usage
17410 @subsection Example of @code{gnatmem} Usage
17411
17412 @noindent
17413 The following example shows the use of @code{gnatmem}
17414 on a simple memory-leaking program.
17415 Suppose that we have the following Ada program:
17416
17417 @smallexample @c ada
17418 @group
17419 @cartouche
17420 with Unchecked_Deallocation;
17421 procedure Test_Gm is
17422
17423    type T is array (1..1000) of Integer;
17424    type Ptr is access T;
17425    procedure Free is new Unchecked_Deallocation (T, Ptr);
17426    A : Ptr;
17427
17428    procedure My_Alloc is
17429    begin
17430       A := new T;
17431    end My_Alloc;
17432
17433    procedure My_DeAlloc is
17434       B : Ptr := A;
17435    begin
17436       Free (B);
17437    end My_DeAlloc;
17438
17439 begin
17440    My_Alloc;
17441    for I in 1 .. 5 loop
17442       for J in I .. 5 loop
17443          My_Alloc;
17444       end loop;
17445       My_Dealloc;
17446    end loop;
17447 end;
17448 @end cartouche
17449 @end group
17450 @end smallexample
17451
17452 @noindent
17453 The program needs to be compiled with debugging option and linked with
17454 @code{gmem} library:
17455
17456 @smallexample
17457 $ gnatmake -g test_gm -largs -lgmem
17458 @end smallexample
17459
17460 @noindent
17461 Then we execute the program as usual:
17462
17463 @smallexample
17464 $ test_gm
17465 @end smallexample
17466
17467 @noindent
17468 Then @code{gnatmem} is invoked simply with
17469 @smallexample
17470 $ gnatmem test_gm
17471 @end smallexample
17472
17473 @noindent
17474 which produces the following output (result may vary on different platforms):
17475
17476 @smallexample
17477 Global information
17478 ------------------
17479    Total number of allocations        :  18
17480    Total number of deallocations      :   5
17481    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17482    High Water Mark                    :  56.90 Kilobytes
17483
17484 Allocation Root # 1
17485 -------------------
17486  Number of non freed allocations    :  11
17487  Final Water Mark (non freed mem)   :  42.97 Kilobytes
17488  High Water Mark                    :  46.88 Kilobytes
17489  Backtrace                          :
17490    test_gm.adb:11 test_gm.my_alloc
17491
17492 Allocation Root # 2
17493 -------------------
17494  Number of non freed allocations    :   1
17495  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17496  High Water Mark                    :  10.02 Kilobytes
17497  Backtrace                          :
17498    s-secsta.adb:81 system.secondary_stack.ss_init
17499
17500 Allocation Root # 3
17501 -------------------
17502  Number of non freed allocations    :   1
17503  Final Water Mark (non freed mem)   :  12 Bytes
17504  High Water Mark                    :  12 Bytes
17505  Backtrace                          :
17506    s-secsta.adb:181 system.secondary_stack.ss_init
17507 @end smallexample
17508
17509 @noindent
17510 Note that the GNAT run time contains itself a certain number of
17511 allocations that have no  corresponding deallocation,
17512 as shown here for root #2 and root
17513 #3. This is a normal behavior when the number of non freed allocations
17514 is one, it allocates dynamic data structures that the run time needs for
17515 the complete lifetime of the program. Note also that there is only one
17516 allocation root in the user program with a single line back trace:
17517 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17518 program shows that 'My_Alloc' is called at 2 different points in the
17519 source (line 21 and line 24). If those two allocation roots need to be
17520 distinguished, the backtrace depth parameter can be used:
17521
17522 @smallexample
17523 $ gnatmem 3 test_gm
17524 @end smallexample
17525
17526 @noindent
17527 which will give the following output:
17528
17529 @smallexample
17530 Global information
17531 ------------------
17532    Total number of allocations        :  18
17533    Total number of deallocations      :   5
17534    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17535    High Water Mark                    :  56.90 Kilobytes
17536
17537 Allocation Root # 1
17538 -------------------
17539  Number of non freed allocations    :  10
17540  Final Water Mark (non freed mem)   :  39.06 Kilobytes
17541  High Water Mark                    :  42.97 Kilobytes
17542  Backtrace                          :
17543    test_gm.adb:11 test_gm.my_alloc
17544    test_gm.adb:24 test_gm
17545    b_test_gm.c:52 main
17546
17547 Allocation Root # 2
17548 -------------------
17549  Number of non freed allocations    :   1
17550  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17551  High Water Mark                    :  10.02 Kilobytes
17552  Backtrace                          :
17553    s-secsta.adb:81  system.secondary_stack.ss_init
17554    s-secsta.adb:283 <system__secondary_stack___elabb>
17555    b_test_gm.c:33   adainit
17556
17557 Allocation Root # 3
17558 -------------------
17559  Number of non freed allocations    :   1
17560  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17561  High Water Mark                    :   3.91 Kilobytes
17562  Backtrace                          :
17563    test_gm.adb:11 test_gm.my_alloc
17564    test_gm.adb:21 test_gm
17565    b_test_gm.c:52 main
17566
17567 Allocation Root # 4
17568 -------------------
17569  Number of non freed allocations    :   1
17570  Final Water Mark (non freed mem)   :  12 Bytes
17571  High Water Mark                    :  12 Bytes
17572  Backtrace                          :
17573    s-secsta.adb:181 system.secondary_stack.ss_init
17574    s-secsta.adb:283 <system__secondary_stack___elabb>
17575    b_test_gm.c:33   adainit
17576 @end smallexample
17577
17578 @noindent
17579 The allocation root #1 of the first example has been split in 2 roots #1
17580 and #3 thanks to the more precise associated backtrace.
17581
17582 @end ifclear
17583
17584
17585 @node The GNAT Debug Pool Facility
17586 @section The GNAT Debug Pool Facility
17587 @findex Debug Pool
17588 @cindex storage, pool, memory corruption
17589
17590 @noindent
17591 The use of unchecked deallocation and unchecked conversion can easily
17592 lead to incorrect memory references. The problems generated by such
17593 references are usually difficult to tackle because the symptoms can be
17594 very remote from the origin of the problem. In such cases, it is
17595 very helpful to detect the problem as early as possible. This is the
17596 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17597
17598 In order to use the GNAT specific debugging pool, the user must
17599 associate a debug pool object with each of the access types that may be
17600 related to suspected memory problems. See Ada Reference Manual 13.11.
17601 @smallexample @c ada
17602 type Ptr is access Some_Type;
17603 Pool : GNAT.Debug_Pools.Debug_Pool;
17604 for Ptr'Storage_Pool use Pool;
17605 @end smallexample
17606
17607 @noindent
17608 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17609 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17610 allow the user to redefine allocation and deallocation strategies. They
17611 also provide a checkpoint for each dereference, through the use of
17612 the primitive operation @code{Dereference} which is implicitly called at
17613 each dereference of an access value.
17614
17615 Once an access type has been associated with a debug pool, operations on
17616 values of the type may raise four distinct exceptions,
17617 which correspond to four potential kinds of memory corruption:
17618 @itemize @bullet
17619 @item
17620 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17621 @item
17622 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17623 @item
17624 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17625 @item
17626 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17627 @end itemize
17628
17629 @noindent
17630 For types associated with a Debug_Pool, dynamic allocation is performed using
17631 the standard
17632 GNAT allocation routine. References to all allocated chunks of memory
17633 are kept in an internal dictionary.
17634 Several deallocation strategies are provided, whereupon the user can choose
17635 to release the memory to the system, keep it allocated for further invalid
17636 access checks, or fill it with an easily recognizable pattern for debug
17637 sessions.
17638 The memory pattern is the old IBM hexadecimal convention: @code{16#DEADBEEF#}.
17639
17640 See the documentation in the file g-debpoo.ads for more information on the
17641 various strategies.
17642
17643 Upon each dereference, a check is made that the access value denotes a
17644 properly allocated memory location. Here is a complete example of use of
17645 @code{Debug_Pools}, that includes typical instances of  memory corruption:
17646 @smallexample @c ada
17647 @iftex
17648 @leftskip=0cm
17649 @end iftex
17650 with Gnat.Io; use Gnat.Io;
17651 with Unchecked_Deallocation;
17652 with Unchecked_Conversion;
17653 with GNAT.Debug_Pools;
17654 with System.Storage_Elements;
17655 with Ada.Exceptions; use Ada.Exceptions;
17656 procedure Debug_Pool_Test is
17657
17658    type T is access Integer;
17659    type U is access all T;
17660
17661    P : GNAT.Debug_Pools.Debug_Pool;
17662    for T'Storage_Pool use P;
17663
17664    procedure Free is new Unchecked_Deallocation (Integer, T);
17665    function UC is new Unchecked_Conversion (U, T);
17666    A, B : aliased T;
17667
17668    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17669
17670 begin
17671    Info (P);
17672    A := new Integer;
17673    B := new Integer;
17674    B := A;
17675    Info (P);
17676    Free (A);
17677    begin
17678       Put_Line (Integer'Image(B.all));
17679    exception
17680       when E : others => Put_Line ("raised: " & Exception_Name (E));
17681    end;
17682    begin
17683       Free (B);
17684    exception
17685       when E : others => Put_Line ("raised: " & Exception_Name (E));
17686    end;
17687    B := UC(A'Access);
17688    begin
17689       Put_Line (Integer'Image(B.all));
17690    exception
17691       when E : others => Put_Line ("raised: " & Exception_Name (E));
17692    end;
17693    begin
17694       Free (B);
17695    exception
17696       when E : others => Put_Line ("raised: " & Exception_Name (E));
17697    end;
17698    Info (P);
17699 end Debug_Pool_Test;
17700 @end smallexample
17701
17702 @noindent
17703 The debug pool mechanism provides the following precise diagnostics on the
17704 execution of this erroneous program:
17705 @smallexample
17706 Debug Pool info:
17707   Total allocated bytes :  0
17708   Total deallocated bytes :  0
17709   Current Water Mark:  0
17710   High Water Mark:  0
17711
17712 Debug Pool info:
17713   Total allocated bytes :  8
17714   Total deallocated bytes :  0
17715   Current Water Mark:  8
17716   High Water Mark:  8
17717
17718 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17719 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17720 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17721 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17722 Debug Pool info:
17723   Total allocated bytes :  8
17724   Total deallocated bytes :  4
17725   Current Water Mark:  4
17726   High Water Mark:  8
17727 @end smallexample
17728
17729
17730 @node Creating Sample Bodies Using gnatstub
17731 @chapter Creating Sample Bodies Using @command{gnatstub}
17732 @findex gnatstub
17733
17734 @noindent
17735 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17736 for library unit declarations.
17737
17738 To create a body stub, @command{gnatstub} has to compile the library
17739 unit declaration. Therefore, bodies can be created only for legal
17740 library units. Moreover, if a library unit depends semantically upon
17741 units located outside the current directory, you have to provide
17742 the source search path when calling @command{gnatstub}, see the description
17743 of @command{gnatstub} switches below.
17744
17745 @menu
17746 * Running gnatstub::
17747 * Switches for gnatstub::
17748 @end menu
17749
17750 @node Running gnatstub
17751 @section Running @command{gnatstub}
17752
17753 @noindent
17754 @command{gnatstub} has the command-line interface of the form
17755
17756 @smallexample
17757 $ gnatstub [switches] filename [directory]
17758 @end smallexample
17759
17760 @noindent
17761 where
17762 @table @emph
17763 @item filename
17764 is the name of the source file that contains a library unit declaration
17765 for which a body must be created. The file name may contain the path
17766 information.
17767 The file name does not have to follow the GNAT file name conventions. If the
17768 name
17769 does not follow GNAT file naming conventions, the name of the body file must
17770 be provided
17771 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17772 If the file name follows the GNAT file naming
17773 conventions and the name of the body file is not provided,
17774 @command{gnatstub}
17775 creates the name
17776 of the body file from the argument file name by replacing the @file{.ads}
17777 suffix
17778 with the @file{.adb} suffix.
17779
17780 @item directory
17781 indicates the directory in which the body stub is to be placed (the default
17782 is the
17783 current directory)
17784
17785 @item switches
17786 is an optional sequence of switches as described in the next section
17787 @end table
17788
17789 @node Switches for gnatstub
17790 @section Switches for @command{gnatstub}
17791
17792 @table @option
17793 @c !sort!
17794
17795 @item ^-f^/FULL^
17796 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17797 If the destination directory already contains a file with the name of the
17798 body file
17799 for the argument spec file, replace it with the generated body stub.
17800
17801 @item ^-hs^/HEADER=SPEC^
17802 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17803 Put the comment header (i.e., all the comments preceding the
17804 compilation unit) from the source of the library unit declaration
17805 into the body stub.
17806
17807 @item ^-hg^/HEADER=GENERAL^
17808 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17809 Put a sample comment header into the body stub.
17810
17811 @ifclear vms
17812 @item -IDIR
17813 @cindex @option{-IDIR} (@command{gnatstub})
17814 @itemx -I-
17815 @cindex @option{-I-} (@command{gnatstub})
17816 @end ifclear
17817 @ifset vms
17818 @item /NOCURRENT_DIRECTORY
17819 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17820 @end ifset
17821 ^These switches have ^This switch has^ the same meaning as in calls to
17822 @command{gcc}.
17823 ^They define ^It defines ^ the source search path in the call to
17824 @command{gcc} issued
17825 by @command{gnatstub} to compile an argument source file.
17826
17827 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17828 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17829 This switch has the same meaning as in calls to @command{gcc}.
17830 It defines the additional configuration file to be passed to the call to
17831 @command{gcc} issued
17832 by @command{gnatstub} to compile an argument source file.
17833
17834 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17835 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17836 (@var{n} is a non-negative integer). Set the maximum line length in the
17837 body stub to @var{n}; the default is 79. The maximum value that can be
17838 specified is 32767. Note that in the special case of configuration
17839 pragma files, the maximum is always 32767 regardless of whether or
17840 not this switch appears.
17841
17842 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17843 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17844 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17845 the generated body sample to @var{n}.
17846 The default indentation is 3.
17847
17848 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17849 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17850 Order local bodies alphabetically. (By default local bodies are ordered
17851 in the same way as the corresponding local specs in the argument spec file.)
17852
17853 @item ^-i^/INDENTATION=^@var{n}
17854 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17855 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17856
17857 @item ^-k^/TREE_FILE=SAVE^
17858 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17859 Do not remove the tree file (i.e., the snapshot of the compiler internal
17860 structures used by @command{gnatstub}) after creating the body stub.
17861
17862 @item ^-l^/LINE_LENGTH=^@var{n}
17863 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17864 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17865
17866 @item ^-o^/BODY=^@var{body-name}
17867 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17868 Body file name.  This should be set if the argument file name does not
17869 follow
17870 the GNAT file naming
17871 conventions. If this switch is omitted the default name for the body will be
17872 obtained
17873 from the argument file name according to the GNAT file naming conventions.
17874
17875 @item ^-q^/QUIET^
17876 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17877 Quiet mode: do not generate a confirmation when a body is
17878 successfully created, and do not generate a message when a body is not
17879 required for an
17880 argument unit.
17881
17882 @item ^-r^/TREE_FILE=REUSE^
17883 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17884 Reuse the tree file (if it exists) instead of creating it.  Instead of
17885 creating the tree file for the library unit declaration, @command{gnatstub}
17886 tries to find it in the current directory and use it for creating
17887 a body. If the tree file is not found, no body is created. This option
17888 also implies @option{^-k^/SAVE^}, whether or not
17889 the latter is set explicitly.
17890
17891 @item ^-t^/TREE_FILE=OVERWRITE^
17892 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17893 Overwrite the existing tree file.  If the current directory already
17894 contains the file which, according to the GNAT file naming rules should
17895 be considered as a tree file for the argument source file,
17896 @command{gnatstub}
17897 will refuse to create the tree file needed to create a sample body
17898 unless this option is set.
17899
17900 @item ^-v^/VERBOSE^
17901 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17902 Verbose mode: generate version information.
17903
17904 @end table
17905
17906
17907 @node Other Utility Programs
17908 @chapter Other Utility Programs
17909
17910 @noindent
17911 This chapter discusses some other utility programs available in the Ada
17912 environment.
17913
17914 @menu
17915 * Using Other Utility Programs with GNAT::
17916 * The External Symbol Naming Scheme of GNAT::
17917 @ifclear vms
17918 * Ada Mode for Glide::
17919 @end ifclear
17920 * Converting Ada Files to html with gnathtml::
17921 * Installing gnathtml::
17922 @ifset vms
17923 * LSE::
17924 * Profiling::
17925 @end ifset
17926 @end menu
17927
17928 @node Using Other Utility Programs with GNAT
17929 @section Using Other Utility Programs with GNAT
17930
17931 @noindent
17932 The object files generated by GNAT are in standard system format and in
17933 particular the debugging information uses this format. This means
17934 programs generated by GNAT can be used with existing utilities that
17935 depend on these formats.
17936
17937 @ifclear vms
17938 In general, any utility program that works with C will also often work with
17939 Ada programs generated by GNAT. This includes software utilities such as
17940 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
17941 as Purify.
17942 @end ifclear
17943
17944 @node The External Symbol Naming Scheme of GNAT
17945 @section The External Symbol Naming Scheme of GNAT
17946
17947 @noindent
17948 In order to interpret the output from GNAT, when using tools that are
17949 originally intended for use with other languages, it is useful to
17950 understand the conventions used to generate link names from the Ada
17951 entity names.
17952
17953 All link names are in all lowercase letters. With the exception of library
17954 procedure names, the mechanism used is simply to use the full expanded
17955 Ada name with dots replaced by double underscores. For example, suppose
17956 we have the following package spec:
17957
17958 @smallexample @c ada
17959 @group
17960 @cartouche
17961 package QRS is
17962    MN : Integer;
17963 end QRS;
17964 @end cartouche
17965 @end group
17966 @end smallexample
17967
17968 @noindent
17969 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
17970 the corresponding link name is @code{qrs__mn}.
17971 @findex Export
17972 Of course if a @code{pragma Export} is used this may be overridden:
17973
17974 @smallexample @c ada
17975 @group
17976 @cartouche
17977 package Exports is
17978    Var1 : Integer;
17979    pragma Export (Var1, C, External_Name => "var1_name");
17980    Var2 : Integer;
17981    pragma Export (Var2, C, Link_Name => "var2_link_name");
17982 end Exports;
17983 @end cartouche
17984 @end group
17985 @end smallexample
17986
17987 @noindent
17988 In this case, the link name for @var{Var1} is whatever link name the
17989 C compiler would assign for the C function @var{var1_name}. This typically
17990 would be either @var{var1_name} or @var{_var1_name}, depending on operating
17991 system conventions, but other possibilities exist. The link name for
17992 @var{Var2} is @var{var2_link_name}, and this is not operating system
17993 dependent.
17994
17995 @findex _main
17996 One exception occurs for library level procedures. A potential ambiguity
17997 arises between the required name @code{_main} for the C main program,
17998 and the name we would otherwise assign to an Ada library level procedure
17999 called @code{Main} (which might well not be the main program).
18000
18001 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18002 names. So if we have a library level procedure such as
18003
18004 @smallexample @c ada
18005 @group
18006 @cartouche
18007 procedure Hello (S : String);
18008 @end cartouche
18009 @end group
18010 @end smallexample
18011
18012 @noindent
18013 the external name of this procedure will be @var{_ada_hello}.
18014
18015 @ifclear vms
18016 @node Ada Mode for Glide
18017 @section Ada Mode for @code{Glide}
18018 @cindex Ada mode (for Glide)
18019
18020 @noindent
18021 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
18022 user to understand and navigate existing code, and facilitates writing
18023 new code. It furthermore provides some utility functions for easier
18024 integration of standard Emacs features when programming in Ada.
18025
18026 Its general features include:
18027
18028 @itemize @bullet
18029 @item
18030 An Integrated Development Environment with functionality such as the
18031 following
18032
18033 @itemize @bullet
18034 @item
18035 ``Project files'' for configuration-specific aspects
18036 (e.g. directories and compilation options)
18037
18038 @item
18039 Compiling and stepping through error messages.
18040
18041 @item
18042 Running and debugging an applications within Glide.
18043 @end itemize
18044
18045 @item
18046 Pull-down menus
18047
18048 @item
18049 User configurability
18050 @end itemize
18051
18052 Some of the specific Ada mode features are:
18053
18054 @itemize @bullet
18055 @item
18056 Functions for easy and quick stepping through Ada code
18057
18058 @item
18059 Getting cross reference information for identifiers (e.g., finding a
18060 defining occurrence)
18061
18062 @item
18063 Displaying an index menu of types and subprograms, allowing
18064 direct selection for browsing
18065
18066 @item
18067 Automatic color highlighting of the various Ada entities
18068 @end itemize
18069
18070 Glide directly supports writing Ada code, via several facilities:
18071
18072 @itemize @bullet
18073 @item
18074 Switching between spec and body files with possible
18075 autogeneration of body files
18076
18077 @item
18078 Automatic formating of subprogram parameter lists
18079
18080 @item
18081 Automatic indentation according to Ada syntax
18082
18083 @item
18084 Automatic completion of identifiers
18085
18086 @item
18087 Automatic (and configurable) casing of identifiers, keywords, and attributes
18088
18089 @item
18090 Insertion of syntactic templates
18091
18092 @item
18093 Block commenting / uncommenting
18094 @end itemize
18095
18096 @noindent
18097 For more information, please refer to the online documentation
18098 available in the @code{Glide} @result{} @code{Help} menu.
18099 @end ifclear
18100
18101
18102 @node Converting Ada Files to html with gnathtml
18103 @section Converting Ada Files to HTML with @code{gnathtml}
18104
18105 @noindent
18106 This @code{Perl} script allows Ada source files to be browsed using
18107 standard Web browsers. For installation procedure, see the section
18108 @xref{Installing gnathtml}.
18109
18110 Ada reserved keywords are highlighted in a bold font and Ada comments in
18111 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18112 switch to suppress the generation of cross-referencing information, user
18113 defined variables and types will appear in a different color; you will
18114 be able to click on any identifier and go to its declaration.
18115
18116 The command line is as follow:
18117 @smallexample
18118 $ perl gnathtml.pl [switches] ada-files
18119 @end smallexample
18120
18121 @noindent
18122 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18123 an html file for every ada file, and a global file called @file{index.htm}.
18124 This file is an index of every identifier defined in the files.
18125
18126 The available switches are the following ones :
18127
18128 @table @option
18129 @item -83
18130 @cindex @option{-83} (@code{gnathtml})
18131 Only the subset on the Ada 83 keywords will be highlighted, not the full
18132 Ada 95 keywords set.
18133
18134 @item -cc @var{color}
18135 @cindex @option{-cc} (@code{gnathtml})
18136 This option allows you to change the color used for comments. The default
18137 value is green. The color argument can be any name accepted by html.
18138
18139 @item -d
18140 @cindex @option{-d} (@code{gnathtml})
18141 If the ada files depend on some other files (using for instance the
18142 @code{with} command, the latter will also be converted to html.
18143 Only the files in the user project will be converted to html, not the files
18144 in the run-time library itself.
18145
18146 @item -D
18147 @cindex @option{-D} (@code{gnathtml})
18148 This command is the same as @option{-d} above, but @command{gnathtml} will
18149 also look for files in the run-time library, and generate html files for them.
18150
18151 @item -ext @var{extension}
18152 @cindex @option{-ext} (@code{gnathtml})
18153 This option allows you to change the extension of the generated HTML files.
18154 If you do not specify an extension, it will default to @file{htm}.
18155
18156 @item -f
18157 @cindex @option{-f} (@code{gnathtml})
18158 By default, gnathtml will generate html links only for global entities
18159 ('with'ed units, global variables and types,...). If you specify the
18160 @option{-f} on the command line, then links will be generated for local
18161 entities too.
18162
18163 @item -l @var{number}
18164 @cindex @option{-l} (@code{gnathtml})
18165 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
18166 will number the html files every @var{number} line.
18167
18168 @item -I @var{dir}
18169 @cindex @option{-I} (@code{gnathtml})
18170 Specify a directory to search for library files (@file{.ALI} files) and
18171 source files. You can provide several -I switches on the command line,
18172 and the directories will be parsed in the order of the command line.
18173
18174 @item -o @var{dir}
18175 @cindex @option{-o} (@code{gnathtml})
18176 Specify the output directory for html files. By default, gnathtml will
18177 saved the generated html files in a subdirectory named @file{html/}.
18178
18179 @item -p @var{file}
18180 @cindex @option{-p} (@code{gnathtml})
18181 If you are using Emacs and the most recent Emacs Ada mode, which provides
18182 a full Integrated Development Environment for compiling, checking,
18183 running and debugging applications, you may use @file{.gpr} files
18184 to give the directories where Emacs can find sources and object files.
18185
18186 Using this switch, you can tell gnathtml to use these files. This allows
18187 you to get an html version of your application, even if it is spread
18188 over multiple directories.
18189
18190 @item -sc @var{color}
18191 @cindex @option{-sc} (@code{gnathtml})
18192 This option allows you to change the color used for symbol definitions.
18193 The default value is red. The color argument can be any name accepted by html.
18194
18195 @item -t @var{file}
18196 @cindex @option{-t} (@code{gnathtml})
18197 This switch provides the name of a file. This file contains a list of
18198 file names to be converted, and the effect is exactly as though they had
18199 appeared explicitly on the command line. This
18200 is the recommended way to work around the command line length limit on some
18201 systems.
18202
18203 @end table
18204
18205 @node Installing gnathtml
18206 @section Installing @code{gnathtml}
18207
18208 @noindent
18209 @code{Perl} needs to be installed on your machine to run this script.
18210 @code{Perl} is freely available for almost every architecture and
18211 Operating System via the Internet.
18212
18213 On Unix systems, you  may want to modify  the  first line of  the script
18214 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18215 is. The syntax of this line is :
18216 @smallexample
18217 #!full_path_name_to_perl
18218 @end smallexample
18219
18220 @noindent
18221 Alternatively, you may run the script using the following command line:
18222
18223 @smallexample
18224 $ perl gnathtml.pl [switches] files
18225 @end smallexample
18226
18227 @ifset vms
18228 @node LSE
18229 @section LSE
18230 @findex LSE
18231
18232 @noindent
18233 The GNAT distribution provides an Ada 95 template for the Digital Language
18234 Sensitive Editor (LSE), a component of DECset. In order to
18235 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18236
18237 @node Profiling
18238 @section Profiling
18239 @findex PCA
18240
18241 @noindent
18242 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
18243 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18244 the collection phase with the /DEBUG qualifier.
18245
18246 @smallexample
18247 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18248 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18249 $ RUN/DEBUG <PROGRAM_NAME>
18250 @end smallexample
18251 @noindent
18252 @end ifset
18253
18254 @node Running and Debugging Ada Programs
18255 @chapter Running and Debugging Ada Programs
18256 @cindex Debugging
18257
18258 @noindent
18259 This chapter discusses how to debug Ada programs. An incorrect Ada program
18260 may be handled in three ways by the GNAT compiler:
18261
18262 @enumerate
18263 @item
18264 The illegality may be a violation of the static semantics of Ada. In
18265 that case GNAT diagnoses the constructs in the program that are illegal.
18266 It is then a straightforward matter for the user to modify those parts of
18267 the program.
18268
18269 @item
18270 The illegality may be a violation of the dynamic semantics of Ada. In
18271 that case the program compiles and executes, but may generate incorrect
18272 results, or may terminate abnormally with some exception.
18273
18274 @item
18275 When presented with a program that contains convoluted errors, GNAT
18276 itself may terminate abnormally without providing full diagnostics on
18277 the incorrect user program.
18278 @end enumerate
18279
18280 @menu
18281 * The GNAT Debugger GDB::
18282 * Running GDB::
18283 * Introduction to GDB Commands::
18284 * Using Ada Expressions::
18285 * Calling User-Defined Subprograms::
18286 * Using the Next Command in a Function::
18287 * Ada Exceptions::
18288 * Ada Tasks::
18289 * Debugging Generic Units::
18290 * GNAT Abnormal Termination or Failure to Terminate::
18291 * Naming Conventions for GNAT Source Files::
18292 * Getting Internal Debugging Information::
18293 * Stack Traceback::
18294 @end menu
18295
18296 @cindex Debugger
18297 @findex gdb
18298
18299 @node The GNAT Debugger GDB
18300 @section The GNAT Debugger GDB
18301
18302 @noindent
18303 @code{GDB} is a general purpose, platform-independent debugger that
18304 can be used to debug mixed-language programs compiled with @code{GCC},
18305 and in particular is capable of debugging Ada programs compiled with
18306 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18307 complex Ada data structures.
18308
18309 The manual @cite{Debugging with GDB}
18310 @ifset vms
18311 , located in the GNU:[DOCS] directory,
18312 @end ifset
18313 contains full details on the usage of @code{GDB}, including a section on
18314 its usage on programs. This manual should be consulted for full
18315 details. The section that follows is a brief introduction to the
18316 philosophy and use of @code{GDB}.
18317
18318 When GNAT programs are compiled, the compiler optionally writes debugging
18319 information into the generated object file, including information on
18320 line numbers, and on declared types and variables. This information is
18321 separate from the generated code. It makes the object files considerably
18322 larger, but it does not add to the size of the actual executable that
18323 will be loaded into memory, and has no impact on run-time performance. The
18324 generation of debug information is triggered by the use of the
18325 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
18326 the compilations. It is important to emphasize that the use of these
18327 options does not change the generated code.
18328
18329 The debugging information is written in standard system formats that
18330 are used by many tools, including debuggers and profilers. The format
18331 of the information is typically designed to describe C types and
18332 semantics, but GNAT implements a translation scheme which allows full
18333 details about Ada types and variables to be encoded into these
18334 standard C formats. Details of this encoding scheme may be found in
18335 the file exp_dbug.ads in the GNAT source distribution. However, the
18336 details of this encoding are, in general, of no interest to a user,
18337 since @code{GDB} automatically performs the necessary decoding.
18338
18339 When a program is bound and linked, the debugging information is
18340 collected from the object files, and stored in the executable image of
18341 the program. Again, this process significantly increases the size of
18342 the generated executable file, but it does not increase the size of
18343 the executable program itself. Furthermore, if this program is run in
18344 the normal manner, it runs exactly as if the debug information were
18345 not present, and takes no more actual memory.
18346
18347 However, if the program is run under control of @code{GDB}, the
18348 debugger is activated.  The image of the program is loaded, at which
18349 point it is ready to run.  If a run command is given, then the program
18350 will run exactly as it would have if @code{GDB} were not present. This
18351 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18352 entirely non-intrusive until a breakpoint is encountered.  If no
18353 breakpoint is ever hit, the program will run exactly as it would if no
18354 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18355 the debugging information and can respond to user commands to inspect
18356 variables, and more generally to report on the state of execution.
18357
18358 @c **************
18359 @node Running GDB
18360 @section Running GDB
18361
18362 @noindent
18363 The debugger can be launched directly and simply from @code{glide} or
18364 through its graphical interface: @code{gvd}. It can also be used
18365 directly in text mode. Here is described the basic use of @code{GDB}
18366 in text mode. All the commands described below can be used in the
18367 @code{gvd} console window even though there is usually other more
18368 graphical ways to achieve the same goals.
18369
18370 @ifclear vms
18371 @noindent
18372 The command to run the graphical interface of the debugger is
18373 @smallexample
18374 $ gvd program
18375 @end smallexample
18376 @end ifclear
18377
18378 @noindent
18379 The command to run @code{GDB} in text mode is
18380
18381 @smallexample
18382 $ ^gdb program^$ GDB PROGRAM^
18383 @end smallexample
18384
18385 @noindent
18386 where @code{^program^PROGRAM^} is the name of the executable file. This
18387 activates the debugger and results in a prompt for debugger commands.
18388 The simplest command is simply @code{run}, which causes the program to run
18389 exactly as if the debugger were not present. The following section
18390 describes some of the additional commands that can be given to @code{GDB}.
18391
18392
18393 @c *******************************
18394 @node Introduction to GDB Commands
18395 @section Introduction to GDB Commands
18396
18397 @noindent
18398 @code{GDB} contains a large repertoire of commands. The manual
18399 @cite{Debugging with GDB}
18400 @ifset vms
18401 , located in the GNU:[DOCS] directory,
18402 @end ifset
18403 includes extensive documentation on the use
18404 of these commands, together with examples of their use. Furthermore,
18405 the command @var{help} invoked from within @code{GDB} activates a simple help
18406 facility which summarizes the available commands and their options.
18407 In this section we summarize a few of the most commonly
18408 used commands to give an idea of what @code{GDB} is about. You should create
18409 a simple program with debugging information and experiment with the use of
18410 these @code{GDB} commands on the program as you read through the
18411 following section.
18412
18413 @table @code
18414 @item set args @var{arguments}
18415 The @var{arguments} list above is a list of arguments to be passed to
18416 the program on a subsequent run command, just as though the arguments
18417 had been entered on a normal invocation of the program. The @code{set args}
18418 command is not needed if the program does not require arguments.
18419
18420 @item run
18421 The @code{run} command causes execution of the program to start from
18422 the beginning. If the program is already running, that is to say if
18423 you are currently positioned at a breakpoint, then a prompt will ask
18424 for confirmation that you want to abandon the current execution and
18425 restart.
18426
18427 @item breakpoint @var{location}
18428 The breakpoint command sets a breakpoint, that is to say a point at which
18429 execution will halt and @code{GDB} will await further
18430 commands. @var{location} is
18431 either a line number within a file, given in the format @code{file:linenumber},
18432 or it is the name of a subprogram. If you request that a breakpoint be set on
18433 a subprogram that is overloaded, a prompt will ask you to specify on which of
18434 those subprograms you want to breakpoint. You can also
18435 specify that all of them should be breakpointed. If the program is run
18436 and execution encounters the breakpoint, then the program
18437 stops and @code{GDB} signals that the breakpoint was encountered by
18438 printing the line of code before which the program is halted.
18439
18440 @item breakpoint exception @var{name}
18441 A special form of the breakpoint command which breakpoints whenever
18442 exception @var{name} is raised.
18443 If @var{name} is omitted,
18444 then a breakpoint will occur when any exception is raised.
18445
18446 @item print @var{expression}
18447 This will print the value of the given expression. Most simple
18448 Ada expression formats are properly handled by @code{GDB}, so the expression
18449 can contain function calls, variables, operators, and attribute references.
18450
18451 @item continue
18452 Continues execution following a breakpoint, until the next breakpoint or the
18453 termination of the program.
18454
18455 @item step
18456 Executes a single line after a breakpoint. If the next statement
18457 is a subprogram call, execution continues into (the first statement of)
18458 the called subprogram.
18459
18460 @item next
18461 Executes a single line. If this line is a subprogram call, executes and
18462 returns from the call.
18463
18464 @item list
18465 Lists a few lines around the current source location. In practice, it
18466 is usually more convenient to have a separate edit window open with the
18467 relevant source file displayed. Successive applications of this command
18468 print subsequent lines. The command can be given an argument which is a
18469 line number, in which case it displays a few lines around the specified one.
18470
18471 @item backtrace
18472 Displays a backtrace of the call chain. This command is typically
18473 used after a breakpoint has occurred, to examine the sequence of calls that
18474 leads to the current breakpoint. The display includes one line for each
18475 activation record (frame) corresponding to an active subprogram.
18476
18477 @item up
18478 At a breakpoint, @code{GDB} can display the values of variables local
18479 to the current frame. The command @code{up} can be used to
18480 examine the contents of other active frames, by moving the focus up
18481 the stack, that is to say from callee to caller, one frame at a time.
18482
18483 @item down
18484 Moves the focus of @code{GDB} down from the frame currently being
18485 examined to the frame of its callee (the reverse of the previous command),
18486
18487 @item frame @var{n}
18488 Inspect the frame with the given number. The value 0 denotes the frame
18489 of the current breakpoint, that is to say the top of the call stack.
18490
18491 @end table
18492
18493 The above list is a very short introduction to the commands that
18494 @code{GDB} provides. Important additional capabilities, including conditional
18495 breakpoints, the ability to execute command sequences on a breakpoint,
18496 the ability to debug at the machine instruction level and many other
18497 features are described in detail in @cite{Debugging with GDB}.
18498 Note that most commands can be abbreviated
18499 (for example, c for continue, bt for backtrace).
18500
18501 @node Using Ada Expressions
18502 @section Using Ada Expressions
18503 @cindex Ada expressions
18504
18505 @noindent
18506 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18507 extensions. The philosophy behind the design of this subset is
18508
18509 @itemize @bullet
18510 @item
18511 That @code{GDB} should provide basic literals and access to operations for
18512 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18513 leaving more sophisticated computations to subprograms written into the
18514 program (which therefore may be called from @code{GDB}).
18515
18516 @item
18517 That type safety and strict adherence to Ada language restrictions
18518 are not particularly important to the @code{GDB} user.
18519
18520 @item
18521 That brevity is important to the @code{GDB} user.
18522 @end itemize
18523
18524 Thus, for brevity, the debugger acts as if there were
18525 implicit @code{with} and @code{use} clauses in effect for all user-written
18526 packages, thus making it unnecessary to fully qualify most names with
18527 their packages, regardless of context. Where this causes ambiguity,
18528 @code{GDB} asks the user's intent.
18529
18530 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
18531
18532 @node Calling User-Defined Subprograms
18533 @section Calling User-Defined Subprograms
18534
18535 @noindent
18536 An important capability of @code{GDB} is the ability to call user-defined
18537 subprograms while debugging. This is achieved simply by entering
18538 a subprogram call statement in the form:
18539
18540 @smallexample
18541 call subprogram-name (parameters)
18542 @end smallexample
18543
18544 @noindent
18545 The keyword @code{call} can be omitted in the normal case where the
18546 @code{subprogram-name} does not coincide with any of the predefined
18547 @code{GDB} commands.
18548
18549 The effect is to invoke the given subprogram, passing it the
18550 list of parameters that is supplied. The parameters can be expressions and
18551 can include variables from the program being debugged. The
18552 subprogram must be defined
18553 at the library level within your program, and @code{GDB} will call the
18554 subprogram within the environment of your program execution (which
18555 means that the subprogram is free to access or even modify variables
18556 within your program).
18557
18558 The most important use of this facility is in allowing the inclusion of
18559 debugging routines that are tailored to particular data structures
18560 in your program. Such debugging routines can be written to provide a suitably
18561 high-level description of an abstract type, rather than a low-level dump
18562 of its physical layout. After all, the standard
18563 @code{GDB print} command only knows the physical layout of your
18564 types, not their abstract meaning. Debugging routines can provide information
18565 at the desired semantic level and are thus enormously useful.
18566
18567 For example, when debugging GNAT itself, it is crucial to have access to
18568 the contents of the tree nodes used to represent the program internally.
18569 But tree nodes are represented simply by an integer value (which in turn
18570 is an index into a table of nodes).
18571 Using the @code{print} command on a tree node would simply print this integer
18572 value, which is not very useful. But the PN routine (defined in file
18573 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18574 a useful high level representation of the tree node, which includes the
18575 syntactic category of the node, its position in the source, the integers
18576 that denote descendant nodes and parent node, as well as varied
18577 semantic information. To study this example in more detail, you might want to
18578 look at the body of the PN procedure in the stated file.
18579
18580 @node Using the Next Command in a Function
18581 @section Using the Next Command in a Function
18582
18583 @noindent
18584 When you use the @code{next} command in a function, the current source
18585 location will advance to the next statement as usual. A special case
18586 arises in the case of a @code{return} statement.
18587
18588 Part of the code for a return statement is the ``epilog'' of the function.
18589 This is the code that returns to the caller. There is only one copy of
18590 this epilog code, and it is typically associated with the last return
18591 statement in the function if there is more than one return. In some
18592 implementations, this epilog is associated with the first statement
18593 of the function.
18594
18595 The result is that if you use the @code{next} command from a return
18596 statement that is not the last return statement of the function you
18597 may see a strange apparent jump to the last return statement or to
18598 the start of the function. You should simply ignore this odd jump.
18599 The value returned is always that from the first return statement
18600 that was stepped through.
18601
18602 @node Ada Exceptions
18603 @section Breaking on Ada Exceptions
18604 @cindex Exceptions
18605
18606 @noindent
18607 You can set breakpoints that trip when your program raises
18608 selected exceptions.
18609
18610 @table @code
18611 @item break exception
18612 Set a breakpoint that trips whenever (any task in the) program raises
18613 any exception.
18614
18615 @item break exception @var{name}
18616 Set a breakpoint that trips whenever (any task in the) program raises
18617 the exception @var{name}.
18618
18619 @item break exception unhandled
18620 Set a breakpoint that trips whenever (any task in the) program raises an
18621 exception for which there is no handler.
18622
18623 @item info exceptions
18624 @itemx info exceptions @var{regexp}
18625 The @code{info exceptions} command permits the user to examine all defined
18626 exceptions within Ada programs. With a regular expression, @var{regexp}, as
18627 argument, prints out only those exceptions whose name matches @var{regexp}.
18628 @end table
18629
18630 @node Ada Tasks
18631 @section Ada Tasks
18632 @cindex Tasks
18633
18634 @noindent
18635 @code{GDB} allows the following task-related commands:
18636
18637 @table @code
18638 @item info tasks
18639 This command shows a list of current Ada tasks, as in the following example:
18640
18641 @smallexample
18642 @iftex
18643 @leftskip=0cm
18644 @end iftex
18645 (gdb) info tasks
18646   ID       TID P-ID   Thread Pri State                 Name
18647    1   8088000   0   807e000  15 Child Activation Wait main_task
18648    2   80a4000   1   80ae000  15 Accept/Select Wait    b
18649    3   809a800   1   80a4800  15 Child Activation Wait a
18650 *  4   80ae800   3   80b8000  15 Running               c
18651 @end smallexample
18652
18653 @noindent
18654 In this listing, the asterisk before the first task indicates it to be the
18655 currently running task. The first column lists the task ID that is used
18656 to refer to tasks in the following commands.
18657
18658 @item break @var{linespec} task @var{taskid}
18659 @itemx break @var{linespec} task @var{taskid} if @dots{}
18660 @cindex Breakpoints and tasks
18661 These commands are like the @code{break @dots{} thread @dots{}}.
18662 @var{linespec} specifies source lines.
18663
18664 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
18665 to specify that you only want @code{GDB} to stop the program when a
18666 particular Ada task reaches this breakpoint. @var{taskid} is one of the
18667 numeric task identifiers assigned by @code{GDB}, shown in the first
18668 column of the @samp{info tasks} display.
18669
18670 If you do not specify @samp{task @var{taskid}} when you set a
18671 breakpoint, the breakpoint applies to @emph{all} tasks of your
18672 program.
18673
18674 You can use the @code{task} qualifier on conditional breakpoints as
18675 well; in this case, place @samp{task @var{taskid}} before the
18676 breakpoint condition (before the @code{if}).
18677
18678 @item task @var{taskno}
18679 @cindex Task switching
18680
18681 This command allows to switch to the task referred by @var{taskno}. In
18682 particular, This allows to browse the backtrace of the specified
18683 task. It is advised to switch back to the original task before
18684 continuing execution otherwise the scheduling of the program may be
18685 perturbated.
18686 @end table
18687
18688 @noindent
18689 For more detailed information on the tasking support,
18690 see @cite{Debugging with GDB}.
18691
18692 @node Debugging Generic Units
18693 @section Debugging Generic Units
18694 @cindex Debugging Generic Units
18695 @cindex Generics
18696
18697 @noindent
18698 GNAT always uses code expansion for generic instantiation. This means that
18699 each time an instantiation occurs, a complete copy of the original code is
18700 made, with appropriate substitutions of formals by actuals.
18701
18702 It is not possible to refer to the original generic entities in
18703 @code{GDB}, but it is always possible to debug a particular instance of
18704 a generic, by using the appropriate expanded names. For example, if we have
18705
18706 @smallexample @c ada
18707 @group
18708 @cartouche
18709 procedure g is
18710
18711    generic package k is
18712       procedure kp (v1 : in out integer);
18713    end k;
18714
18715    package body k is
18716       procedure kp (v1 : in out integer) is
18717       begin
18718          v1 := v1 + 1;
18719       end kp;
18720    end k;
18721
18722    package k1 is new k;
18723    package k2 is new k;
18724
18725    var : integer := 1;
18726
18727 begin
18728    k1.kp (var);
18729    k2.kp (var);
18730    k1.kp (var);
18731    k2.kp (var);
18732 end;
18733 @end cartouche
18734 @end group
18735 @end smallexample
18736
18737 @noindent
18738 Then to break on a call to procedure kp in the k2 instance, simply
18739 use the command:
18740
18741 @smallexample
18742 (gdb) break g.k2.kp
18743 @end smallexample
18744
18745 @noindent
18746 When the breakpoint occurs, you can step through the code of the
18747 instance in the normal manner and examine the values of local variables, as for
18748 other units.
18749
18750 @node GNAT Abnormal Termination or Failure to Terminate
18751 @section GNAT Abnormal Termination or Failure to Terminate
18752 @cindex GNAT Abnormal Termination or Failure to Terminate
18753
18754 @noindent
18755 When presented with programs that contain serious errors in syntax
18756 or semantics,
18757 GNAT may on rare occasions  experience problems in operation, such
18758 as aborting with a
18759 segmentation fault or illegal memory access, raising an internal
18760 exception, terminating abnormally, or failing to terminate at all.
18761 In such cases, you can activate
18762 various features of GNAT that can help you pinpoint the construct in your
18763 program that is the likely source of the problem.
18764
18765 The following strategies are presented in increasing order of
18766 difficulty, corresponding to your experience in using GNAT and your
18767 familiarity with compiler internals.
18768
18769 @enumerate
18770 @item
18771 Run @code{gcc} with the @option{-gnatf}. This first
18772 switch causes all errors on a given line to be reported. In its absence,
18773 only the first error on a line is displayed.
18774
18775 The @option{-gnatdO} switch causes errors to be displayed as soon as they
18776 are encountered, rather than after compilation is terminated. If GNAT
18777 terminates prematurely or goes into an infinite loop, the last error
18778 message displayed may help to pinpoint the culprit.
18779
18780 @item
18781 Run @code{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this mode,
18782 @code{gcc} produces ongoing information about the progress of the
18783 compilation and provides the name of each procedure as code is
18784 generated. This switch allows you to find which Ada procedure was being
18785 compiled when it encountered a code generation problem.
18786
18787 @item
18788 @cindex @option{-gnatdc} switch
18789 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
18790 switch that does for the front-end what @option{^-v^VERBOSE^} does
18791 for the back end. The system prints the name of each unit,
18792 either a compilation unit or nested unit, as it is being analyzed.
18793 @item
18794 Finally, you can start
18795 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
18796 front-end of GNAT, and can be run independently (normally it is just
18797 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
18798 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
18799 @code{where} command is the first line of attack; the variable
18800 @code{lineno} (seen by @code{print lineno}), used by the second phase of
18801 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
18802 which the execution stopped, and @code{input_file name} indicates the name of
18803 the source file.
18804 @end enumerate
18805
18806 @node Naming Conventions for GNAT Source Files
18807 @section Naming Conventions for GNAT Source Files
18808
18809 @noindent
18810 In order to examine the workings of the GNAT system, the following
18811 brief description of its organization may be helpful:
18812
18813 @itemize @bullet
18814 @item
18815 Files with prefix @file{^sc^SC^} contain the lexical scanner.
18816
18817 @item
18818 All files prefixed with @file{^par^PAR^} are components of the parser. The
18819 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
18820 parsing of select statements can be found in @file{par-ch9.adb}.
18821
18822 @item
18823 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
18824 numbers correspond to chapters of the Ada standard. For example, all
18825 issues involving context clauses can be found in @file{sem_ch10.adb}. In
18826 addition, some features of the language require sufficient special processing
18827 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
18828 dynamic dispatching, etc.
18829
18830 @item
18831 All files prefixed with @file{^exp^EXP^} perform normalization and
18832 expansion of the intermediate representation (abstract syntax tree, or AST).
18833 these files use the same numbering scheme as the parser and semantics files.
18834 For example, the construction of record initialization procedures is done in
18835 @file{exp_ch3.adb}.
18836
18837 @item
18838 The files prefixed with @file{^bind^BIND^} implement the binder, which
18839 verifies the consistency of the compilation, determines an order of
18840 elaboration, and generates the bind file.
18841
18842 @item
18843 The files @file{atree.ads} and @file{atree.adb} detail the low-level
18844 data structures used by the front-end.
18845
18846 @item
18847 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
18848 the abstract syntax tree as produced by the parser.
18849
18850 @item
18851 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
18852 all entities, computed during semantic analysis.
18853
18854 @item
18855 Library management issues are dealt with in files with prefix
18856 @file{^lib^LIB^}.
18857
18858 @item
18859 @findex Ada
18860 @cindex Annex A
18861 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
18862 defined in Annex A.
18863
18864 @item
18865 @findex Interfaces
18866 @cindex Annex B
18867 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
18868 defined in Annex B.
18869
18870 @item
18871 @findex System
18872 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
18873 both language-defined children and GNAT run-time routines.
18874
18875 @item
18876 @findex GNAT
18877 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
18878 general-purpose packages, fully documented in their specifications. All
18879 the other @file{.c} files are modifications of common @code{gcc} files.
18880 @end itemize
18881
18882 @node Getting Internal Debugging Information
18883 @section Getting Internal Debugging Information
18884
18885 @noindent
18886 Most compilers have internal debugging switches and modes. GNAT
18887 does also, except GNAT internal debugging switches and modes are not
18888 secret. A summary and full description of all the compiler and binder
18889 debug flags are in the file @file{debug.adb}. You must obtain the
18890 sources of the compiler to see the full detailed effects of these flags.
18891
18892 The switches that print the source of the program (reconstructed from
18893 the internal tree) are of general interest for user programs, as are the
18894 options to print
18895 the full internal tree, and the entity table (the symbol table
18896 information). The reconstructed source provides a readable version of the
18897 program after the front-end has completed analysis and  expansion,
18898 and is useful when studying the performance of specific constructs.
18899 For example, constraint checks are indicated, complex aggregates
18900 are replaced with loops and assignments, and tasking primitives
18901 are replaced with run-time calls.
18902
18903 @node Stack Traceback
18904 @section Stack Traceback
18905 @cindex traceback
18906 @cindex stack traceback
18907 @cindex stack unwinding
18908
18909 @noindent
18910 Traceback is a mechanism to display the sequence of subprogram calls that
18911 leads to a specified execution point in a program. Often (but not always)
18912 the execution point is an instruction at which an exception has been raised.
18913 This mechanism is also known as @i{stack unwinding} because it obtains
18914 its information by scanning the run-time stack and recovering the activation
18915 records of all active subprograms. Stack unwinding is one of the most
18916 important tools for program debugging.
18917
18918 The first entry stored in traceback corresponds to the deepest calling level,
18919 that is to say the subprogram currently executing the instruction
18920 from which we want to obtain the traceback.
18921
18922 Note that there is no runtime performance penalty when stack traceback
18923 is enabled, and no exception is raised during program execution.
18924
18925 @menu
18926 * Non-Symbolic Traceback::
18927 * Symbolic Traceback::
18928 @end menu
18929
18930 @node Non-Symbolic Traceback
18931 @subsection Non-Symbolic Traceback
18932 @cindex traceback, non-symbolic
18933
18934 @noindent
18935 Note: this feature is not supported on all platforms. See
18936 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
18937 platforms.
18938
18939 @menu
18940 * Tracebacks From an Unhandled Exception::
18941 * Tracebacks From Exception Occurrences (non-symbolic)::
18942 * Tracebacks From Anywhere in a Program (non-symbolic)::
18943 @end menu
18944
18945 @node Tracebacks From an Unhandled Exception
18946 @subsubsection Tracebacks From an Unhandled Exception
18947
18948 @noindent
18949 A runtime non-symbolic traceback is a list of addresses of call instructions.
18950 To enable this feature you must use the @option{-E}
18951 @code{gnatbind}'s option. With this option a stack traceback is stored as part
18952 of exception information. You can retrieve this information using the
18953 @code{addr2line} tool.
18954
18955 Here is a simple example:
18956
18957 @smallexample @c ada
18958 @cartouche
18959 procedure STB is
18960
18961    procedure P1 is
18962    begin
18963       raise Constraint_Error;
18964    end P1;
18965
18966    procedure P2 is
18967    begin
18968       P1;
18969    end P2;
18970
18971 begin
18972    P2;
18973 end STB;
18974 @end cartouche
18975 @end smallexample
18976
18977 @smallexample
18978 $ gnatmake stb -bargs -E
18979 $ stb
18980
18981 Execution terminated by unhandled exception
18982 Exception name: CONSTRAINT_ERROR
18983 Message: stb.adb:5
18984 Call stack traceback locations:
18985 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
18986 @end smallexample
18987
18988 @noindent
18989 As we see the traceback lists a sequence of addresses for the unhandled
18990 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
18991 guess that this exception come from procedure P1. To translate these
18992 addresses into the source lines where the calls appear, the
18993 @code{addr2line} tool, described below, is invaluable. The use of this tool
18994 requires the program to be compiled with debug information.
18995
18996 @smallexample
18997 $ gnatmake -g stb -bargs -E
18998 $ stb
18999
19000 Execution terminated by unhandled exception
19001 Exception name: CONSTRAINT_ERROR
19002 Message: stb.adb:5
19003 Call stack traceback locations:
19004 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19005
19006 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19007    0x4011f1 0x77e892a4
19008
19009 00401373 at d:/stb/stb.adb:5
19010 0040138B at d:/stb/stb.adb:10
19011 0040139C at d:/stb/stb.adb:14
19012 00401335 at d:/stb/b~stb.adb:104
19013 004011C4 at /build/.../crt1.c:200
19014 004011F1 at /build/.../crt1.c:222
19015 77E892A4 in ?? at ??:0
19016 @end smallexample
19017
19018 @noindent
19019 The @code{addr2line} tool has several other useful options:
19020
19021 @table @code
19022 @item --functions
19023 to get the function name corresponding to any location
19024
19025 @item --demangle=gnat
19026 to use the gnat decoding mode for the function names. Note that
19027 for binutils version 2.9.x the option is simply @option{--demangle}.
19028 @end table
19029
19030 @smallexample
19031 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19032    0x40139c 0x401335 0x4011c4 0x4011f1
19033
19034 00401373 in stb.p1 at d:/stb/stb.adb:5
19035 0040138B in stb.p2 at d:/stb/stb.adb:10
19036 0040139C in stb at d:/stb/stb.adb:14
19037 00401335 in main at d:/stb/b~stb.adb:104
19038 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
19039 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
19040 @end smallexample
19041
19042 @noindent
19043 From this traceback we can see that the exception was raised in
19044 @file{stb.adb} at line 5, which was reached from a procedure call in
19045 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19046 which contains the call to the main program.
19047 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
19048 and the output will vary from platform to platform.
19049
19050 It is also possible to use @code{GDB} with these traceback addresses to debug
19051 the program. For example, we can break at a given code location, as reported
19052 in the stack traceback:
19053
19054 @smallexample
19055 $ gdb -nw stb
19056 @ifclear vms
19057 @noindent
19058 Furthermore, this feature is not implemented inside Windows DLL. Only
19059 the non-symbolic traceback is reported in this case.
19060 @end ifclear
19061
19062 (gdb) break *0x401373
19063 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19064 @end smallexample
19065
19066 @noindent
19067 It is important to note that the stack traceback addresses
19068 do not change when debug information is included. This is particularly useful
19069 because it makes it possible to release software without debug information (to
19070 minimize object size), get a field report that includes a stack traceback
19071 whenever an internal bug occurs, and then be able to retrieve the sequence
19072 of calls with the same program compiled with debug information.
19073
19074 @node Tracebacks From Exception Occurrences (non-symbolic)
19075 @subsubsection Tracebacks From Exception Occurrences
19076
19077 @noindent
19078 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19079 The stack traceback is attached to the exception information string, and can
19080 be retrieved in an exception handler within the Ada program, by means of the
19081 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19082
19083 @smallexample @c ada
19084 with Ada.Text_IO;
19085 with Ada.Exceptions;
19086
19087 procedure STB is
19088
19089    use Ada;
19090    use Ada.Exceptions;
19091
19092    procedure P1 is
19093       K : Positive := 1;
19094    begin
19095       K := K - 1;
19096    exception
19097       when E : others =>
19098          Text_IO.Put_Line (Exception_Information (E));
19099    end P1;
19100
19101    procedure P2 is
19102    begin
19103       P1;
19104    end P2;
19105
19106 begin
19107    P2;
19108 end STB;
19109 @end smallexample
19110
19111 @noindent
19112 This program will output:
19113
19114 @smallexample
19115 $ stb
19116
19117 Exception name: CONSTRAINT_ERROR
19118 Message: stb.adb:12
19119 Call stack traceback locations:
19120 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19121 @end smallexample
19122
19123 @node Tracebacks From Anywhere in a Program (non-symbolic)
19124 @subsubsection Tracebacks From Anywhere in a Program
19125
19126 @noindent
19127 It is also possible to retrieve a stack traceback from anywhere in a
19128 program. For this you need to
19129 use the @code{GNAT.Traceback} API. This package includes a procedure called
19130 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19131 display procedures described below. It is not necessary to use the
19132 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19133 is invoked explicitly.
19134
19135 @noindent
19136 In the following example we compute a traceback at a specific location in
19137 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19138 convert addresses to strings:
19139
19140 @smallexample @c ada
19141 with Ada.Text_IO;
19142 with GNAT.Traceback;
19143 with GNAT.Debug_Utilities;
19144
19145 procedure STB is
19146
19147    use Ada;
19148    use GNAT;
19149    use GNAT.Traceback;
19150
19151    procedure P1 is
19152       TB  : Tracebacks_Array (1 .. 10);
19153       --  We are asking for a maximum of 10 stack frames.
19154       Len : Natural;
19155       --  Len will receive the actual number of stack frames returned.
19156    begin
19157       Call_Chain (TB, Len);
19158
19159       Text_IO.Put ("In STB.P1 : ");
19160
19161       for K in 1 .. Len loop
19162          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19163          Text_IO.Put (' ');
19164       end loop;
19165
19166       Text_IO.New_Line;
19167    end P1;
19168
19169    procedure P2 is
19170    begin
19171       P1;
19172    end P2;
19173
19174 begin
19175    P2;
19176 end STB;
19177 @end smallexample
19178
19179 @smallexample
19180 $ gnatmake -g stb
19181 $ stb
19182
19183 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19184 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19185 @end smallexample
19186
19187 @noindent
19188 You can then get further information by invoking the @code{addr2line}
19189 tool as described earlier (note that the hexadecimal addresses
19190 need to be specified in C format, with a leading ``0x'').
19191
19192
19193 @node Symbolic Traceback
19194 @subsection Symbolic Traceback
19195 @cindex traceback, symbolic
19196
19197 @noindent
19198 A symbolic traceback is a stack traceback in which procedure names are
19199 associated with each code location.
19200
19201 @noindent
19202 Note that this feature is not supported on all platforms. See
19203 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19204 list of currently supported platforms.
19205
19206 @noindent
19207 Note that the symbolic traceback requires that the program be compiled
19208 with debug information. If it is not compiled with debug information
19209 only the non-symbolic information will be valid.
19210
19211 @menu
19212 * Tracebacks From Exception Occurrences (symbolic)::
19213 * Tracebacks From Anywhere in a Program (symbolic)::
19214 @end menu
19215
19216 @node Tracebacks From Exception Occurrences (symbolic)
19217 @subsubsection Tracebacks From Exception Occurrences
19218
19219 @smallexample @c ada
19220 with Ada.Text_IO;
19221 with GNAT.Traceback.Symbolic;
19222
19223 procedure STB is
19224
19225    procedure P1 is
19226    begin
19227       raise Constraint_Error;
19228    end P1;
19229
19230    procedure P2 is
19231    begin
19232       P1;
19233    end P2;
19234
19235    procedure P3 is
19236    begin
19237       P2;
19238    end P3;
19239
19240 begin
19241    P3;
19242 exception
19243    when E : others =>
19244       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19245 end STB;
19246 @end smallexample
19247
19248 @smallexample
19249 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19250 $ stb
19251
19252 0040149F in stb.p1 at stb.adb:8
19253 004014B7 in stb.p2 at stb.adb:13
19254 004014CF in stb.p3 at stb.adb:18
19255 004015DD in ada.stb at stb.adb:22
19256 00401461 in main at b~stb.adb:168
19257 004011C4 in __mingw_CRTStartup at crt1.c:200
19258 004011F1 in mainCRTStartup at crt1.c:222
19259 77E892A4 in ?? at ??:0
19260 @end smallexample
19261
19262 @noindent
19263 In the above example the ``.\'' syntax in the @command{gnatmake} command
19264 is currently required by @command{addr2line} for files that are in
19265 the current working directory.
19266 Moreover, the exact sequence of linker options may vary from platform
19267 to platform.
19268 The above @option{-largs} section is for Windows platforms. By contrast,
19269 under Unix there is no need for the @option{-largs} section.
19270 Differences across platforms are due to details of linker implementation.
19271
19272 @node Tracebacks From Anywhere in a Program (symbolic)
19273 @subsubsection Tracebacks From Anywhere in a Program
19274
19275 @noindent
19276 It is possible to get a symbolic stack traceback
19277 from anywhere in a program, just as for non-symbolic tracebacks.
19278 The first step is to obtain a non-symbolic
19279 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19280 information. Here is an example:
19281
19282 @smallexample @c ada
19283 with Ada.Text_IO;
19284 with GNAT.Traceback;
19285 with GNAT.Traceback.Symbolic;
19286
19287 procedure STB is
19288
19289    use Ada;
19290    use GNAT.Traceback;
19291    use GNAT.Traceback.Symbolic;
19292
19293    procedure P1 is
19294       TB  : Tracebacks_Array (1 .. 10);
19295       --  We are asking for a maximum of 10 stack frames.
19296       Len : Natural;
19297       --  Len will receive the actual number of stack frames returned.
19298    begin
19299       Call_Chain (TB, Len);
19300       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19301    end P1;
19302
19303    procedure P2 is
19304    begin
19305       P1;
19306    end P2;
19307
19308 begin
19309    P2;
19310 end STB;
19311 @end smallexample
19312
19313 @ifset vms
19314 @node Compatibility with DEC Ada
19315 @chapter Compatibility with DEC Ada
19316 @cindex Compatibility
19317
19318 @noindent
19319 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
19320 OpenVMS Alpha. GNAT achieves a high level of compatibility
19321 with DEC Ada, and it should generally be straightforward to port code
19322 from the DEC Ada environment to GNAT. However, there are a few language
19323 and implementation differences of which the user must be aware. These
19324 differences are discussed in this section. In
19325 addition, the operating environment and command structure for the
19326 compiler are different, and these differences are also discussed.
19327
19328 Note that this discussion addresses specifically the implementation
19329 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
19330 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19331 GNAT always follows the Alpha implementation.
19332
19333 @menu
19334 * Ada 95 Compatibility::
19335 * Differences in the Definition of Package System::
19336 * Language-Related Features::
19337 * The Package STANDARD::
19338 * The Package SYSTEM::
19339 * Tasking and Task-Related Features::
19340 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
19341 * Pragmas and Pragma-Related Features::
19342 * Library of Predefined Units::
19343 * Bindings::
19344 * Main Program Definition::
19345 * Implementation-Defined Attributes::
19346 * Compiler and Run-Time Interfacing::
19347 * Program Compilation and Library Management::
19348 * Input-Output::
19349 * Implementation Limits::
19350 * Tools::
19351 @end menu
19352
19353 @node Ada 95 Compatibility
19354 @section Ada 95 Compatibility
19355
19356 @noindent
19357 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
19358 compiler. Ada 95 is almost completely upwards compatible
19359 with Ada 83, and therefore Ada 83 programs will compile
19360 and run under GNAT with
19361 no changes or only minor changes. The Ada 95 Reference
19362 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
19363 incompatibilities.
19364
19365 GNAT provides the switch /83 on the GNAT COMPILE command,
19366 as well as the pragma ADA_83, to force the compiler to
19367 operate in Ada 83 mode. This mode does not guarantee complete
19368 conformance to Ada 83, but in practice is sufficient to
19369 eliminate most sources of incompatibilities.
19370 In particular, it eliminates the recognition of the
19371 additional Ada 95 keywords, so that their use as identifiers
19372 in Ada83 program is legal, and handles the cases of packages
19373 with optional bodies, and generics that instantiate unconstrained
19374 types without the use of @code{(<>)}.
19375
19376 @node Differences in the Definition of Package System
19377 @section Differences in the Definition of Package System
19378
19379 @noindent
19380 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
19381 implementation-dependent declarations to package System. In normal mode,
19382 GNAT does not take advantage of this permission, and the version of System
19383 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
19384
19385 However, DEC Ada adds an extensive set of declarations to package System,
19386 as fully documented in the DEC Ada manuals. To minimize changes required
19387 for programs that make use of these extensions, GNAT provides the pragma
19388 Extend_System for extending the definition of package System. By using:
19389
19390 @smallexample @c ada
19391 @group
19392 @cartouche
19393 pragma Extend_System (Aux_DEC);
19394 @end cartouche
19395 @end group
19396 @end smallexample
19397
19398 @noindent
19399 The set of definitions in System is extended to include those in package
19400 @code{System.Aux_DEC}.
19401 These definitions are incorporated directly into package
19402 System, as though they had been declared there in the first place. For a
19403 list of the declarations added, see the specification of this package,
19404 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
19405 The pragma Extend_System is a configuration pragma, which means that
19406 it can be placed in the file @file{gnat.adc}, so that it will automatically
19407 apply to all subsequent compilations. See the section on Configuration
19408 Pragmas for further details.
19409
19410 An alternative approach that avoids the use of the non-standard
19411 Extend_System pragma is to add a context clause to the unit that
19412 references these facilities:
19413
19414 @smallexample @c ada
19415 @group
19416 @cartouche
19417 with System.Aux_DEC;
19418 use  System.Aux_DEC;
19419 @end cartouche
19420 @end group
19421 @end smallexample
19422
19423 @noindent
19424 The effect is not quite semantically identical to incorporating
19425 the declarations directly into package @code{System},
19426 but most programs will not notice a difference
19427 unless they use prefix notation (e.g. @code{System.Integer_8})
19428 to reference the
19429 entities directly in package @code{System}.
19430 For units containing such references,
19431 the prefixes must either be removed, or the pragma @code{Extend_System}
19432 must be used.
19433
19434 @node Language-Related Features
19435 @section Language-Related Features
19436
19437 @noindent
19438 The following sections highlight differences in types,
19439 representations of types, operations, alignment, and
19440 related topics.
19441
19442 @menu
19443 * Integer Types and Representations::
19444 * Floating-Point Types and Representations::
19445 * Pragmas Float_Representation and Long_Float::
19446 * Fixed-Point Types and Representations::
19447 * Record and Array Component Alignment::
19448 * Address Clauses::
19449 * Other Representation Clauses::
19450 @end menu
19451
19452 @node Integer Types and Representations
19453 @subsection Integer Types and Representations
19454
19455 @noindent
19456 The set of predefined integer types is identical in DEC Ada and GNAT.
19457 Furthermore the representation of these integer types is also identical,
19458 including the capability of size clauses forcing biased representation.
19459
19460 In addition,
19461 DEC Ada for OpenVMS Alpha systems has defined the
19462 following additional integer types in package System:
19463
19464 @itemize @bullet
19465
19466 @item
19467 INTEGER_8
19468
19469 @item
19470 INTEGER_16
19471
19472 @item
19473 INTEGER_32
19474
19475 @item
19476 INTEGER_64
19477
19478 @item
19479 LARGEST_INTEGER
19480 @end itemize
19481
19482 @noindent
19483 When using GNAT, the first four of these types may be obtained from the
19484 standard Ada 95 package @code{Interfaces}.
19485 Alternatively, by use of the pragma
19486 @code{Extend_System}, identical
19487 declarations can be referenced directly in package @code{System}.
19488 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
19489
19490 @node Floating-Point Types and Representations
19491 @subsection Floating-Point Types and Representations
19492 @cindex Floating-Point types
19493
19494 @noindent
19495 The set of predefined floating-point types is identical in DEC Ada and GNAT.
19496 Furthermore the representation of these floating-point
19497 types is also identical. One important difference is that the default
19498 representation for DEC Ada is VAX_Float, but the default representation
19499 for GNAT is IEEE.
19500
19501 Specific types may be declared to be VAX_Float or IEEE, using the pragma
19502 @code{Float_Representation} as described in the DEC Ada documentation.
19503 For example, the declarations:
19504
19505 @smallexample @c ada
19506 @group
19507 @cartouche
19508 type F_Float is digits 6;
19509 pragma Float_Representation (VAX_Float, F_Float);
19510 @end cartouche
19511 @end group
19512 @end smallexample
19513
19514 @noindent
19515 declare a type F_Float that will be represented in VAX_Float format.
19516 This set of declarations actually appears in System.Aux_DEC, which provides
19517 the full set of additional floating-point declarations provided in
19518 the DEC Ada version of package
19519 System. This and similar declarations may be accessed in a user program
19520 by using pragma @code{Extend_System}. The use of this
19521 pragma, and the related pragma @code{Long_Float} is described in further
19522 detail in the following section.
19523
19524 @node Pragmas Float_Representation and Long_Float
19525 @subsection Pragmas Float_Representation and Long_Float
19526
19527 @noindent
19528 DEC Ada provides the pragma @code{Float_Representation}, which
19529 acts as a program library switch to allow control over
19530 the internal representation chosen for the predefined
19531 floating-point types declared in the package @code{Standard}.
19532 The format of this pragma is as follows:
19533
19534 @smallexample
19535 @group
19536 @cartouche
19537 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
19538 @end cartouche
19539 @end group
19540 @end smallexample
19541
19542 @noindent
19543 This pragma controls the representation of floating-point
19544 types as follows:
19545
19546 @itemize @bullet
19547 @item
19548 @code{VAX_Float} specifies that floating-point
19549 types are represented by default with the VAX hardware types
19550 F-floating, D-floating, G-floating. Note that the H-floating
19551 type is available only on DIGITAL Vax systems, and is not available
19552 in either DEC Ada or GNAT for Alpha systems.
19553
19554 @item
19555 @code{IEEE_Float} specifies that floating-point
19556 types are represented by default with the IEEE single and
19557 double floating-point types.
19558 @end itemize
19559
19560 @noindent
19561 GNAT provides an identical implementation of the pragma
19562 @code{Float_Representation}, except that it functions as a
19563 configuration pragma, as defined by Ada 95. Note that the
19564 notion of configuration pragma corresponds closely to the
19565 DEC Ada notion of a program library switch.
19566
19567 When no pragma is used in GNAT, the default is IEEE_Float, which is different
19568 from DEC Ada 83, where the default is VAX_Float. In addition, the
19569 predefined libraries in GNAT are built using IEEE_Float, so it is not
19570 advisable to change the format of numbers passed to standard library
19571 routines, and if necessary explicit type conversions may be needed.
19572
19573 The use of IEEE_Float is recommended in GNAT since it is more efficient,
19574 and (given that it conforms to an international standard) potentially more
19575 portable. The situation in which VAX_Float may be useful is in interfacing
19576 to existing code and data that expects the use of VAX_Float. There are
19577 two possibilities here. If the requirement for the use of VAX_Float is
19578 localized, then the best approach is to use the predefined VAX_Float
19579 types in package @code{System}, as extended by
19580 @code{Extend_System}. For example, use @code{System.F_Float}
19581 to specify the 32-bit @code{F-Float} format.
19582
19583 Alternatively, if an entire program depends heavily on the use of
19584 the @code{VAX_Float} and in particular assumes that the types in
19585 package @code{Standard} are in @code{Vax_Float} format, then it
19586 may be desirable to reconfigure GNAT to assume Vax_Float by default.
19587 This is done by using the GNAT LIBRARY command to rebuild the library, and
19588 then using the general form of the @code{Float_Representation}
19589 pragma to ensure that this default format is used throughout.
19590 The form of the GNAT LIBRARY command is:
19591
19592 @smallexample
19593 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
19594 @end smallexample
19595
19596 @noindent
19597 where @i{file} contains the new configuration pragmas
19598 and @i{directory} is the directory to be created to contain
19599 the new library.
19600
19601 @noindent
19602 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
19603 to allow control over the internal representation chosen
19604 for the predefined type @code{Long_Float} and for floating-point
19605 type declarations with digits specified in the range 7 .. 15.
19606 The format of this pragma is as follows:
19607
19608 @smallexample @c ada
19609 @cartouche
19610 pragma Long_Float (D_FLOAT | G_FLOAT);
19611 @end cartouche
19612 @end smallexample
19613
19614 @node Fixed-Point Types and Representations
19615 @subsection Fixed-Point Types and Representations
19616
19617 @noindent
19618 On DEC Ada for OpenVMS Alpha systems, rounding is
19619 away from zero for both positive and negative numbers.
19620 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
19621
19622 On GNAT for OpenVMS Alpha, the results of operations
19623 on fixed-point types are in accordance with the Ada 95
19624 rules. In particular, results of operations on decimal
19625 fixed-point types are truncated.
19626
19627 @node Record and Array Component Alignment
19628 @subsection Record and Array Component Alignment
19629
19630 @noindent
19631 On DEC Ada for OpenVMS Alpha, all non composite components
19632 are aligned on natural boundaries. For example, 1-byte
19633 components are aligned on byte boundaries, 2-byte
19634 components on 2-byte boundaries, 4-byte components on 4-byte
19635 byte boundaries, and so on. The OpenVMS Alpha hardware
19636 runs more efficiently with naturally aligned data.
19637
19638 ON GNAT for OpenVMS Alpha, alignment rules are compatible
19639 with DEC Ada for OpenVMS Alpha.
19640
19641 @node Address Clauses
19642 @subsection Address Clauses
19643
19644 @noindent
19645 In DEC Ada and GNAT, address clauses are supported for
19646 objects and imported subprograms.
19647 The predefined type @code{System.Address} is a private type
19648 in both compilers, with the same representation (it is simply
19649 a machine pointer). Addition, subtraction, and comparison
19650 operations are available in the standard Ada 95 package
19651 @code{System.Storage_Elements}, or in package @code{System}
19652 if it is extended to include @code{System.Aux_DEC} using a
19653 pragma @code{Extend_System} as previously described.
19654
19655 Note that code that with's both this extended package @code{System}
19656 and the package @code{System.Storage_Elements} should not @code{use}
19657 both packages, or ambiguities will result. In general it is better
19658 not to mix these two sets of facilities. The Ada 95 package was
19659 designed specifically to provide the kind of features that DEC Ada
19660 adds directly to package @code{System}.
19661
19662 GNAT is compatible with DEC Ada in its handling of address
19663 clauses, except for some limitations in
19664 the form of address clauses for composite objects with
19665 initialization. Such address clauses are easily replaced
19666 by the use of an explicitly-defined constant as described
19667 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
19668 of declarations:
19669
19670 @smallexample @c ada
19671 @cartouche
19672 X, Y : Integer := Init_Func;
19673 Q : String (X .. Y) := "abc";
19674 ...
19675 for Q'Address use Compute_Address;
19676 @end cartouche
19677 @end smallexample
19678
19679 @noindent
19680 will be rejected by GNAT, since the address cannot be computed at the time
19681 that Q is declared. To achieve the intended effect, write instead:
19682
19683 @smallexample @c ada
19684 @group
19685 @cartouche
19686 X, Y : Integer := Init_Func;
19687 Q_Address : constant Address := Compute_Address;
19688 Q : String (X .. Y) := "abc";
19689 ...
19690 for Q'Address use Q_Address;
19691 @end cartouche
19692 @end group
19693 @end smallexample
19694
19695 @noindent
19696 which will be accepted by GNAT (and other Ada 95 compilers), and is also
19697 backwards compatible with Ada 83. A fuller description of the restrictions
19698 on address specifications is found in the GNAT Reference Manual.
19699
19700 @node Other Representation Clauses
19701 @subsection Other Representation Clauses
19702
19703 @noindent
19704 GNAT supports in a compatible manner all the representation
19705 clauses supported by DEC Ada. In addition, it
19706 supports representation clause forms that are new in Ada 95
19707 including COMPONENT_SIZE and SIZE clauses for objects.
19708
19709 @node The Package STANDARD
19710 @section The Package STANDARD
19711
19712 @noindent
19713 The package STANDARD, as implemented by DEC Ada, is fully
19714 described in the Reference Manual for the Ada Programming
19715 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
19716 Language Reference Manual. As implemented by GNAT, the
19717 package STANDARD is described in the Ada 95 Reference
19718 Manual.
19719
19720 In addition, DEC Ada supports the Latin-1 character set in
19721 the type CHARACTER. GNAT supports the Latin-1 character set
19722 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
19723 the type WIDE_CHARACTER.
19724
19725 The floating-point types supported by GNAT are those
19726 supported by DEC Ada, but defaults are different, and are controlled by
19727 pragmas. See @pxref{Floating-Point Types and Representations} for details.
19728
19729 @node The Package SYSTEM
19730 @section The Package SYSTEM
19731
19732 @noindent
19733 DEC Ada provides a system-specific version of the package
19734 SYSTEM for each platform on which the language ships.
19735 For the complete specification of the package SYSTEM, see
19736 Appendix F of the DEC Ada Language Reference Manual.
19737
19738 On DEC Ada, the package SYSTEM includes the following conversion functions:
19739 @itemize @bullet
19740 @item TO_ADDRESS(INTEGER)
19741
19742 @item  TO_ADDRESS(UNSIGNED_LONGWORD)
19743
19744 @item  TO_ADDRESS(universal_integer)
19745
19746 @item  TO_INTEGER(ADDRESS)
19747
19748 @item  TO_UNSIGNED_LONGWORD(ADDRESS)
19749
19750 @item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
19751                  functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
19752 @end itemize
19753
19754 @noindent
19755 By default, GNAT supplies a version of SYSTEM that matches
19756 the definition given in the Ada 95 Reference Manual.
19757 This
19758 is a subset of the DIGITAL system definitions, which is as
19759 close as possible to the original definitions. The only difference
19760 is that the definition of SYSTEM_NAME is different:
19761
19762 @smallexample @c ada
19763 @group
19764 @cartouche
19765 type Name is (SYSTEM_NAME_GNAT);
19766 System_Name : constant Name := SYSTEM_NAME_GNAT;
19767 @end cartouche
19768 @end group
19769 @end smallexample
19770
19771 @noindent
19772 Also, GNAT adds the new Ada 95 declarations for
19773 BIT_ORDER and DEFAULT_BIT_ORDER.
19774
19775 However, the use of the following pragma causes GNAT
19776 to extend the definition of package SYSTEM so that it
19777 encompasses the full set of DIGITAL-specific extensions,
19778 including the functions listed above:
19779
19780 @smallexample @c ada
19781 @cartouche
19782 pragma Extend_System (Aux_DEC);
19783 @end cartouche
19784 @end smallexample
19785
19786 @noindent
19787 The pragma Extend_System is a configuration pragma that
19788 is most conveniently placed in the @file{gnat.adc} file. See the
19789 GNAT Reference Manual for further details.
19790
19791 DEC Ada does not allow the recompilation of the package
19792 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
19793 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
19794 the package SYSTEM. On OpenVMS Alpha systems, the pragma
19795 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
19796 its single argument.
19797
19798 GNAT does permit the recompilation of package SYSTEM using
19799 a special switch (@option{-gnatg}) and this switch can be used if
19800 it is necessary to modify the definitions in SYSTEM. GNAT does
19801 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
19802 or MEMORY_SIZE by any other means.
19803
19804 On GNAT systems, the pragma SYSTEM_NAME takes the
19805 enumeration literal SYSTEM_NAME_GNAT.
19806
19807 The definitions provided by the use of
19808
19809 @smallexample @c ada
19810 pragma Extend_System (AUX_Dec);
19811 @end smallexample
19812
19813 @noindent
19814 are virtually identical to those provided by the DEC Ada 83 package
19815 System. One important difference is that the name of the TO_ADDRESS
19816 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
19817 See the GNAT Reference manual for a discussion of why this change was
19818 necessary.
19819
19820 @noindent
19821 The version of TO_ADDRESS taking a universal integer argument is in fact
19822 an extension to Ada 83 not strictly compatible with the reference manual.
19823 In GNAT, we are constrained to be exactly compatible with the standard,
19824 and this means we cannot provide this capability. In DEC Ada 83, the
19825 point of this definition is to deal with a call like:
19826
19827 @smallexample @c ada
19828 TO_ADDRESS (16#12777#);
19829 @end smallexample
19830
19831 @noindent
19832 Normally, according to the Ada 83 standard, one would expect this to be
19833 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
19834 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
19835 definition using universal_integer takes precedence.
19836
19837 In GNAT, since the version with universal_integer cannot be supplied, it is
19838 not possible to be 100% compatible. Since there are many programs using
19839 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
19840 to change the name of the function in the UNSIGNED_LONGWORD case, so the
19841 declarations provided in the GNAT version of AUX_Dec are:
19842
19843 @smallexample @c ada
19844 function To_Address (X : Integer) return Address;
19845 pragma Pure_Function (To_Address);
19846
19847 function To_Address_Long (X : Unsigned_Longword) return Address;
19848 pragma Pure_Function (To_Address_Long);
19849 @end smallexample
19850
19851 @noindent
19852 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
19853 change the name to TO_ADDRESS_LONG.
19854
19855 @node Tasking and Task-Related Features
19856 @section Tasking and Task-Related Features
19857
19858 @noindent
19859 The concepts relevant to a comparison of tasking on GNAT
19860 and on DEC Ada for OpenVMS Alpha systems are discussed in
19861 the following sections.
19862
19863 For detailed information on concepts related to tasking in
19864 DEC Ada, see the DEC Ada Language Reference Manual and the
19865 relevant run-time reference manual.
19866
19867 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
19868 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
19869
19870 @noindent
19871 On OpenVMS Alpha systems, each Ada task (except a passive
19872 task) is implemented as a single stream of execution
19873 that is created and managed by the kernel. On these
19874 systems, DEC Ada tasking support is based on DECthreads,
19875 an implementation of the POSIX standard for threads.
19876
19877 Although tasks are implemented as threads, all tasks in
19878 an Ada program are part of the same process. As a result,
19879 resources such as open files and virtual memory can be
19880 shared easily among tasks. Having all tasks in one process
19881 allows better integration with the programming environment
19882 (the shell and the debugger, for example).
19883
19884 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
19885 code that calls DECthreads routines can be used together.
19886 The interaction between Ada tasks and DECthreads routines
19887 can have some benefits. For example when on OpenVMS Alpha,
19888 DEC Ada can call C code that is already threaded.
19889 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
19890 and Ada tasks are mapped to threads.
19891
19892 @menu
19893 * Assigning Task IDs::
19894 * Task IDs and Delays::
19895 * Task-Related Pragmas::
19896 * Scheduling and Task Priority::
19897 * The Task Stack::
19898 * External Interrupts::
19899 @end menu
19900
19901 @node Assigning Task IDs
19902 @subsection Assigning Task IDs
19903
19904 @noindent
19905 The DEC Ada Run-Time Library always assigns %TASK 1 to
19906 the environment task that executes the main program. On
19907 OpenVMS Alpha systems, %TASK 0 is often used for tasks
19908 that have been created but are not yet activated.
19909
19910 On OpenVMS Alpha systems, task IDs are assigned at
19911 activation. On GNAT systems, task IDs are also assigned at
19912 task creation but do not have the same form or values as
19913 task ID values in DEC Ada. There is no null task, and the
19914 environment task does not have a specific task ID value.
19915
19916 @node Task IDs and Delays
19917 @subsection Task IDs and Delays
19918
19919 @noindent
19920 On OpenVMS Alpha systems, tasking delays are implemented
19921 using Timer System Services. The Task ID is used for the
19922 identification of the timer request (the REQIDT parameter).
19923 If Timers are used in the application take care not to use
19924 0 for the identification, because cancelling such a timer
19925 will cancel all timers and may lead to unpredictable results.
19926
19927 @node Task-Related Pragmas
19928 @subsection Task-Related Pragmas
19929
19930 @noindent
19931 Ada supplies the pragma TASK_STORAGE, which allows
19932 specification of the size of the guard area for a task
19933 stack. (The guard area forms an area of memory that has no
19934 read or write access and thus helps in the detection of
19935 stack overflow.) On OpenVMS Alpha systems, if the pragma
19936 TASK_STORAGE specifies a value of zero, a minimal guard
19937 area is created. In the absence of a pragma TASK_STORAGE, a default guard
19938 area is created.
19939
19940 GNAT supplies the following task-related pragmas:
19941
19942 @itemize @bullet
19943 @item  TASK_INFO
19944
19945               This pragma appears within a task definition and
19946               applies to the task in which it appears. The argument
19947               must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
19948
19949 @item  TASK_STORAGE
19950
19951               GNAT implements pragma TASK_STORAGE in the same way as
19952               DEC Ada.
19953               Both DEC Ada and GNAT supply the pragmas PASSIVE,
19954               SUPPRESS, and VOLATILE.
19955 @end itemize
19956 @node Scheduling and Task Priority
19957 @subsection Scheduling and Task Priority
19958
19959 @noindent
19960 DEC Ada implements the Ada language requirement that
19961 when two tasks are eligible for execution and they have
19962 different priorities, the lower priority task does not
19963 execute while the higher priority task is waiting. The DEC
19964 Ada Run-Time Library keeps a task running until either the
19965 task is suspended or a higher priority task becomes ready.
19966
19967 On OpenVMS Alpha systems, the default strategy is round-
19968 robin with preemption. Tasks of equal priority take turns
19969 at the processor. A task is run for a certain period of
19970 time and then placed at the rear of the ready queue for
19971 its priority level.
19972
19973 DEC Ada provides the implementation-defined pragma TIME_SLICE,
19974 which can be used to enable or disable round-robin
19975 scheduling of tasks with the same priority.
19976 See the relevant DEC Ada run-time reference manual for
19977 information on using the pragmas to control DEC Ada task
19978 scheduling.
19979
19980 GNAT follows the scheduling rules of Annex D (real-time
19981 Annex) of the Ada 95 Reference Manual. In general, this
19982 scheduling strategy is fully compatible with DEC Ada
19983 although it provides some additional constraints (as
19984 fully documented in Annex D).
19985 GNAT implements time slicing control in a manner compatible with
19986 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
19987 to the DEC Ada 83 pragma of the same name.
19988 Note that it is not possible to mix GNAT tasking and
19989 DEC Ada 83 tasking in the same program, since the two run times are
19990 not compatible.
19991
19992 @node The Task Stack
19993 @subsection The Task Stack
19994
19995 @noindent
19996 In DEC Ada, a task stack is allocated each time a
19997 non passive task is activated. As soon as the task is
19998 terminated, the storage for the task stack is deallocated.
19999 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
20000 a default stack size is used. Also, regardless of the size
20001 specified, some additional space is allocated for task
20002 management purposes. On OpenVMS Alpha systems, at least
20003 one page is allocated.
20004
20005 GNAT handles task stacks in a similar manner. According to
20006 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
20007 an alternative method for controlling the task stack size.
20008 The specification of the attribute T'STORAGE_SIZE is also
20009 supported in a manner compatible with DEC Ada.
20010
20011 @node External Interrupts
20012 @subsection External Interrupts
20013
20014 @noindent
20015 On DEC Ada, external interrupts can be associated with task entries.
20016 GNAT is compatible with DEC Ada in its handling of external interrupts.
20017
20018 @node Pragmas and Pragma-Related Features
20019 @section Pragmas and Pragma-Related Features
20020
20021 @noindent
20022 Both DEC Ada and GNAT supply all language-defined pragmas
20023 as specified by the Ada 83 standard. GNAT also supplies all
20024 language-defined pragmas specified in the Ada 95 Reference Manual.
20025 In addition, GNAT implements the implementation-defined pragmas
20026 from DEC Ada 83.
20027
20028 @itemize @bullet
20029 @item  AST_ENTRY
20030
20031 @item  COMMON_OBJECT
20032
20033 @item  COMPONENT_ALIGNMENT
20034
20035 @item  EXPORT_EXCEPTION
20036
20037 @item  EXPORT_FUNCTION
20038
20039 @item  EXPORT_OBJECT
20040
20041 @item  EXPORT_PROCEDURE
20042
20043 @item  EXPORT_VALUED_PROCEDURE
20044
20045 @item  FLOAT_REPRESENTATION
20046
20047 @item  IDENT
20048
20049 @item  IMPORT_EXCEPTION
20050
20051 @item  IMPORT_FUNCTION
20052
20053 @item  IMPORT_OBJECT
20054
20055 @item  IMPORT_PROCEDURE
20056
20057 @item  IMPORT_VALUED_PROCEDURE
20058
20059 @item  INLINE_GENERIC
20060
20061 @item  INTERFACE_NAME
20062
20063 @item  LONG_FLOAT
20064
20065 @item  MAIN_STORAGE
20066
20067 @item  PASSIVE
20068
20069 @item  PSET_OBJECT
20070
20071 @item  SHARE_GENERIC
20072
20073 @item  SUPPRESS_ALL
20074
20075 @item  TASK_STORAGE
20076
20077 @item  TIME_SLICE
20078
20079 @item  TITLE
20080 @end itemize
20081
20082 @noindent
20083 These pragmas are all fully implemented, with the exception of @code{Title},
20084 @code{Passive}, and @code{Share_Generic}, which are
20085 recognized, but which have no
20086 effect in GNAT. The effect of @code{Passive} may be obtained by the
20087 use of protected objects in Ada 95. In GNAT, all generics are inlined.
20088
20089 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
20090 a separate subprogram specification which must appear before the
20091 subprogram body.
20092
20093 GNAT also supplies a number of implementation-defined pragmas as follows:
20094 @itemize @bullet
20095 @item  C_PASS_BY_COPY
20096
20097 @item  EXTEND_SYSTEM
20098
20099 @item  SOURCE_FILE_NAME
20100
20101 @item  UNSUPPRESS
20102
20103 @item  WARNINGS
20104
20105 @item  ABORT_DEFER
20106
20107 @item  ADA_83
20108
20109 @item  ADA_95
20110
20111 @item  ANNOTATE
20112
20113 @item  ASSERT
20114
20115 @item  CPP_CLASS
20116
20117 @item  CPP_CONSTRUCTOR
20118
20119 @item  CPP_DESTRUCTOR
20120
20121 @item  CPP_VIRTUAL
20122
20123 @item  CP_VTABLE
20124
20125 @item  DEBUG
20126
20127 @item  LINKER_ALIAS
20128
20129 @item  LINKER_SECTION
20130
20131 @item  MACHINE_ATTRIBUTE
20132
20133 @item  NO_RETURN
20134
20135 @item  PURE_FUNCTION
20136
20137 @item  SOURCE_REFERENCE
20138
20139 @item  TASK_INFO
20140
20141 @item  UNCHECKED_UNION
20142
20143 @item  UNIMPLEMENTED_UNIT
20144
20145 @item  UNIVERSAL_DATA
20146
20147 @item  WEAK_EXTERNAL
20148 @end itemize
20149
20150 @noindent
20151 For full details on these GNAT implementation-defined pragmas, see
20152 the GNAT Reference Manual.
20153
20154 @menu
20155 * Restrictions on the Pragma INLINE::
20156 * Restrictions on the Pragma INTERFACE::
20157 * Restrictions on the Pragma SYSTEM_NAME::
20158 @end menu
20159
20160 @node Restrictions on the Pragma INLINE
20161 @subsection Restrictions on the Pragma INLINE
20162
20163 @noindent
20164 DEC Ada applies the following restrictions to the pragma INLINE:
20165 @itemize @bullet
20166 @item  Parameters cannot be a task type.
20167
20168 @item  Function results cannot be task types, unconstrained
20169 array types, or unconstrained types with discriminants.
20170
20171 @item  Bodies cannot declare the following:
20172 @itemize @bullet
20173 @item  Subprogram body or stub (imported subprogram is allowed)
20174
20175 @item  Tasks
20176
20177 @item  Generic declarations
20178
20179 @item  Instantiations
20180
20181 @item  Exceptions
20182
20183 @item  Access types (types derived from access types allowed)
20184
20185 @item  Array or record types
20186
20187 @item  Dependent tasks
20188
20189 @item  Direct recursive calls of subprogram or containing
20190 subprogram, directly or via a renaming
20191
20192 @end itemize
20193 @end itemize
20194
20195 @noindent
20196 In GNAT, the only restriction on pragma INLINE is that the
20197 body must occur before the call if both are in the same
20198 unit, and the size must be appropriately small. There are
20199 no other specific restrictions which cause subprograms to
20200 be incapable of being inlined.
20201
20202 @node  Restrictions on the Pragma INTERFACE
20203 @subsection  Restrictions on the Pragma INTERFACE
20204
20205 @noindent
20206 The following lists and describes the restrictions on the
20207 pragma INTERFACE on DEC Ada and GNAT:
20208 @itemize @bullet
20209 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
20210 Default is the default on OpenVMS Alpha systems.
20211
20212 @item  Parameter passing: Language specifies default
20213 mechanisms but can be overridden with an EXPORT pragma.
20214
20215 @itemize @bullet
20216 @item  Ada: Use internal Ada rules.
20217
20218 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
20219 record or task type. Result cannot be a string, an
20220 array, or a record.
20221
20222 @item  Fortran: Parameters cannot be a task. Result cannot
20223 be a string, an array, or a record.
20224 @end itemize
20225 @end itemize
20226
20227 @noindent
20228 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
20229 record parameters for all languages.
20230
20231 @node  Restrictions on the Pragma SYSTEM_NAME
20232 @subsection  Restrictions on the Pragma SYSTEM_NAME
20233
20234 @noindent
20235 For DEC Ada for OpenVMS Alpha, the enumeration literal
20236 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
20237 literal for the type NAME is SYSTEM_NAME_GNAT.
20238
20239 @node  Library of Predefined Units
20240 @section  Library of Predefined Units
20241
20242 @noindent
20243 A library of predefined units is provided as part of the
20244 DEC Ada and GNAT implementations. DEC Ada does not provide
20245 the package MACHINE_CODE but instead recommends importing
20246 assembler code.
20247
20248 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
20249 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20250 version. During GNAT installation, the DEC Ada Predefined
20251 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
20252 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
20253 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
20254 for details.
20255
20256 The GNAT RTL is contained in
20257 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
20258 the default search path is set up to find DECLIB units in preference
20259 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
20260 for example).
20261
20262 However, it is possible to change the default so that the
20263 reverse is true, or even to mix them using child package
20264 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
20265 is the package name, and the Ada units are available in the
20266 standard manner defined for Ada 95, that is to say as Ada.xxx. To
20267 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
20268 appropriately. For example, to change the default to use the Ada95
20269 versions do:
20270
20271 @smallexample
20272 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
20273                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20274 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
20275                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20276 @end smallexample
20277
20278 @menu
20279 * Changes to DECLIB::
20280 @end menu
20281
20282 @node Changes to DECLIB
20283 @subsection Changes to DECLIB
20284
20285 @noindent
20286 The changes made to the DEC Ada predefined library for GNAT and Ada 95
20287 compatibility are minor and include the following:
20288
20289 @itemize @bullet
20290 @item  Adjusting the location of pragmas and record representation
20291 clauses to obey Ada 95 rules
20292
20293 @item  Adding the proper notation to generic formal parameters
20294 that take unconstrained types in instantiation
20295
20296 @item  Adding pragma ELABORATE_BODY to package specifications
20297 that have package bodies not otherwise allowed
20298
20299 @item  Occurrences of the identifier @code{"PROTECTED"} are renamed to
20300 @code{"PROTECTD"}.
20301 Currently these are found only in the STARLET package spec.
20302 @end itemize
20303
20304 @noindent
20305 None of the above changes is visible to users.
20306
20307 @node Bindings
20308 @section Bindings
20309
20310 @noindent
20311 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
20312 @itemize @bullet
20313
20314 @item  Command Language Interpreter (CLI interface)
20315
20316 @item  DECtalk Run-Time Library (DTK interface)
20317
20318 @item  Librarian utility routines (LBR interface)
20319
20320 @item  General Purpose Run-Time Library (LIB interface)
20321
20322 @item  Math Run-Time Library (MTH interface)
20323
20324 @item  National Character Set Run-Time Library (NCS interface)
20325
20326 @item  Compiled Code Support Run-Time Library (OTS interface)
20327
20328 @item  Parallel Processing Run-Time Library (PPL interface)
20329
20330 @item  Screen Management Run-Time Library (SMG interface)
20331
20332 @item  Sort Run-Time Library (SOR interface)
20333
20334 @item  String Run-Time Library (STR interface)
20335
20336 @item STARLET System Library
20337 @findex Starlet
20338
20339 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
20340
20341 @item  X Windows Toolkit (XT interface)
20342
20343 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
20344 @end itemize
20345
20346 @noindent
20347 GNAT provides implementations of these DEC bindings in the DECLIB directory.
20348
20349 The X/Motif bindings used to build DECLIB are whatever versions are in the
20350 DEC Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20351 The build script will
20352 automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt},
20353 and @code{X_Lib}
20354 causing the default X/Motif sharable image libraries to be linked in. This
20355 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20356 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20357
20358 It may be necessary to edit these options files to update or correct the
20359 library names if, for example, the newer X/Motif bindings from
20360 @file{ADA$EXAMPLES}
20361 had been (previous to installing GNAT) copied and renamed to supersede the
20362 default @file{ADA$PREDEFINED} versions.
20363
20364 @menu
20365 * Shared Libraries and Options Files::
20366 * Interfaces to C::
20367 @end menu
20368
20369 @node Shared Libraries and Options Files
20370 @subsection Shared Libraries and Options Files
20371
20372 @noindent
20373 When using the DEC Ada
20374 predefined X and Motif bindings, the linking with their sharable images is
20375 done automatically by @command{GNAT LINK}.
20376 When using other X and Motif bindings, you need
20377 to add the corresponding sharable images to the command line for
20378 @code{GNAT LINK}. When linking with shared libraries, or with
20379 @file{.OPT} files, you must
20380 also add them to the command line for @command{GNAT LINK}.
20381
20382 A shared library to be used with GNAT is built in the same way as other
20383 libraries under VMS. The VMS Link command can be used in standard fashion.
20384
20385 @node Interfaces to C
20386 @subsection Interfaces to C
20387
20388 @noindent
20389 DEC Ada
20390 provides the following Ada types and operations:
20391
20392 @itemize @bullet
20393 @item C types package (C_TYPES)
20394
20395 @item C strings (C_TYPES.NULL_TERMINATED)
20396
20397 @item Other_types (SHORT_INT)
20398 @end itemize
20399
20400 @noindent
20401 Interfacing to C with GNAT, one can use the above approach
20402 described for DEC Ada or the facilities of Annex B of
20403 the Ada 95 Reference Manual (packages INTERFACES.C,
20404 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
20405 information, see the section ``Interfacing to C'' in the
20406 @cite{GNAT Reference Manual}.
20407
20408 The @option{-gnatF} qualifier forces default and explicit
20409 @code{External_Name} parameters in pragmas Import and Export
20410 to be uppercased for compatibility with the default behavior
20411 of Compaq C. The qualifier has no effect on @code{Link_Name} parameters.
20412
20413 @node Main Program Definition
20414 @section Main Program Definition
20415
20416 @noindent
20417 The following section discusses differences in the
20418 definition of main programs on DEC Ada and GNAT.
20419 On DEC Ada, main programs are defined to meet the
20420 following conditions:
20421 @itemize @bullet
20422 @item  Procedure with no formal parameters (returns 0 upon
20423        normal completion)
20424
20425 @item  Procedure with no formal parameters (returns 42 when
20426        unhandled exceptions are raised)
20427
20428 @item  Function with no formal parameters whose returned value
20429        is of a discrete type
20430
20431 @item  Procedure with one OUT formal of a discrete type for
20432        which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
20433
20434 @end itemize
20435
20436 @noindent
20437 When declared with the pragma EXPORT_VALUED_PROCEDURE,
20438 a main function or main procedure returns a discrete
20439 value whose size is less than 64 bits (32 on VAX systems),
20440 the value is zero- or sign-extended as appropriate.
20441 On GNAT, main programs are defined as follows:
20442 @itemize @bullet
20443 @item  Must be a non-generic, parameter-less subprogram that
20444 is either a procedure or function returning an Ada
20445 STANDARD.INTEGER (the predefined type)
20446
20447 @item  Cannot be a generic subprogram or an instantiation of a
20448 generic subprogram
20449 @end itemize
20450
20451 @node Implementation-Defined Attributes
20452 @section Implementation-Defined Attributes
20453
20454 @noindent
20455 GNAT provides all DEC Ada implementation-defined
20456 attributes.
20457
20458 @node Compiler and Run-Time Interfacing
20459 @section Compiler and Run-Time Interfacing
20460
20461 @noindent
20462 DEC Ada provides the following ways to pass options to the linker
20463 (ACS LINK):
20464 @itemize @bullet
20465 @item  /WAIT and /SUBMIT qualifiers
20466
20467 @item  /COMMAND qualifier
20468
20469 @item  /[NO]MAP qualifier
20470
20471 @item  /OUTPUT=file-spec
20472
20473 @item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
20474 @end itemize
20475
20476 @noindent
20477 To pass options to the linker, GNAT provides the following
20478 switches:
20479
20480 @itemize @bullet
20481 @item   @option{/EXECUTABLE=exec-name}
20482
20483 @item   @option{/VERBOSE qualifier}
20484
20485 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers
20486 @end itemize
20487
20488 @noindent
20489 For more information on these switches, see
20490 @ref{Switches for gnatlink}.
20491 In DEC Ada, the command-line switch @option{/OPTIMIZE} is available
20492 to control optimization. DEC Ada also supplies the
20493 following pragmas:
20494 @itemize @bullet
20495 @item  @code{OPTIMIZE}
20496
20497 @item  @code{INLINE}
20498
20499 @item  @code{INLINE_GENERIC}
20500
20501 @item  @code{SUPPRESS_ALL}
20502
20503 @item  @code{PASSIVE}
20504 @end itemize
20505
20506 @noindent
20507 In GNAT, optimization is controlled strictly by command
20508 line parameters, as described in the corresponding section of this guide.
20509 The DIGITAL pragmas for control of optimization are
20510 recognized but ignored.
20511
20512 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
20513 the default is that optimization is turned on.
20514
20515 @node Program Compilation and Library Management
20516 @section Program Compilation and Library Management
20517
20518 @noindent
20519 DEC Ada and GNAT provide a comparable set of commands to
20520 build programs. DEC Ada also provides a program library,
20521 which is a concept that does not exist on GNAT. Instead,
20522 GNAT provides directories of sources that are compiled as
20523 needed.
20524
20525 The following table summarizes
20526 the DEC Ada commands and provides
20527 equivalent GNAT commands. In this table, some GNAT
20528 equivalents reflect the fact that GNAT does not use the
20529 concept of a program library. Instead, it uses a model
20530 in which collections of source and object files are used
20531 in a manner consistent with other languages like C and
20532 Fortran. Therefore, standard system file commands are used
20533 to manipulate these elements. Those GNAT commands are marked with
20534 an asterisk.
20535 Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards.
20536
20537 @need 1500
20538 @multitable @columnfractions .35 .65
20539
20540 @item @emph{DEC Ada Command}
20541 @tab @emph{GNAT Equivalent / Description}
20542
20543 @item @command{ADA}
20544 @tab @command{GNAT COMPILE}@*
20545 Invokes the compiler to compile one or more Ada source files.
20546
20547 @item @command{ACS ATTACH}@*
20548 @tab [No equivalent]@*
20549 Switches control of terminal from current process running the program
20550 library manager.
20551
20552 @item @command{ACS CHECK}
20553 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
20554 Forms the execution closure of one
20555 or more compiled units and checks completeness and currency.
20556
20557 @item @command{ACS COMPILE}
20558 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20559 Forms the execution closure of one or
20560 more specified units, checks completeness and currency,
20561 identifies units that have revised source files, compiles same,
20562 and recompiles units that are or will become obsolete.
20563 Also completes incomplete generic instantiations.
20564
20565 @item @command{ACS COPY FOREIGN}
20566 @tab Copy (*)@*
20567 Copies a foreign object file into the program library as a
20568 library unit body.
20569
20570 @item @command{ACS COPY UNIT}
20571 @tab Copy (*)@*
20572 Copies a compiled unit from one program library to another.
20573
20574 @item @command{ACS CREATE LIBRARY}
20575 @tab Create /directory (*)@*
20576 Creates a program library.
20577
20578 @item @command{ACS CREATE SUBLIBRARY}
20579 @tab Create /directory (*)@*
20580 Creates a program sublibrary.
20581
20582 @item @command{ACS DELETE LIBRARY}
20583 @tab @*
20584 Deletes a program library and its contents.
20585
20586 @item @command{ACS DELETE SUBLIBRARY}
20587 @tab @*
20588 Deletes a program sublibrary and its contents.
20589
20590 @item @command{ACS DELETE UNIT}
20591 @tab Delete file (*)@*
20592 On OpenVMS systems, deletes one or more compiled units from
20593 the current program library.
20594
20595 @item @command{ACS DIRECTORY}
20596 @tab Directory (*)@*
20597 On OpenVMS systems, lists units contained in the current
20598 program library.
20599
20600 @item @command{ACS ENTER FOREIGN}
20601 @tab Copy (*)@*
20602 Allows the import of a foreign body as an Ada library
20603 specification and enters a reference to a pointer.
20604
20605 @item @command{ACS ENTER UNIT}
20606 @tab Copy (*)@*
20607 Enters a reference (pointer) from the current program library to
20608 a unit compiled into another program library.
20609
20610 @item @command{ACS EXIT}
20611 @tab [No equivalent]@*
20612 Exits from the program library manager.
20613
20614 @item @command{ACS EXPORT}
20615 @tab Copy (*)@*
20616 Creates an object file that contains system-specific object code
20617 for one or more units. With GNAT, object files can simply be copied
20618 into the desired directory.
20619
20620 @item @command{ACS EXTRACT SOURCE}
20621 @tab Copy (*)@*
20622 Allows access to the copied source file for each Ada compilation unit
20623
20624 @item @command{ACS HELP}
20625 @tab @command{HELP GNAT}@*
20626 Provides online help.
20627
20628 @item @command{ACS LINK}
20629 @tab @command{GNAT LINK}@*
20630 Links an object file containing Ada units into an executable file.
20631
20632 @item @command{ACS LOAD}
20633 @tab Copy (*)@*
20634 Loads (partially compiles) Ada units into the program library.
20635 Allows loading a program from a collection of files into a library
20636 without knowing the relationship among units.
20637
20638 @item @command{ACS MERGE}
20639 @tab Copy (*)@*
20640 Merges into the current program library, one or more units from
20641 another library where they were modified.
20642
20643 @item @command{ACS RECOMPILE}
20644 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20645 Recompiles from   external or copied source files any obsolete
20646 unit in the closure. Also, completes any incomplete generic
20647 instantiations.
20648
20649 @item @command{ACS REENTER}
20650 @tab @command{GNAT MAKE}@*
20651 Reenters current references to units compiled after last entered
20652 with the @command{ACS ENTER UNIT} command.
20653
20654 @item @command{ACS SET LIBRARY}
20655 @tab Set default (*)@*
20656 Defines a program library to be the compilation context as well
20657 as the target library for compiler output and commands in general.
20658
20659 @item @command{ACS SET PRAGMA}
20660 @tab Edit @file{gnat.adc} (*)@*
20661 Redefines specified  values of the library characteristics
20662 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
20663 and @code{Float_Representation}.
20664
20665 @item @command{ACS SET SOURCE}
20666 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
20667 Defines the source file search list for the @command{ACS COMPILE} command.
20668
20669 @item @command{ACS SHOW LIBRARY}
20670 @tab Directory (*)@*
20671 Lists information about one or more program libraries.
20672
20673 @item @command{ACS SHOW PROGRAM}
20674 @tab [No equivalent]@*
20675 Lists information about the execution closure of one or
20676 more units in the program library.
20677
20678 @item @command{ACS SHOW SOURCE}
20679 @tab Show logical @code{ADA_INCLUDE_PATH}@*
20680 Shows the source file search used when compiling units.
20681
20682 @item @command{ACS SHOW VERSION}
20683 @tab Compile with @option{VERBOSE} option
20684 Displays the version number of the compiler and program library
20685 manager used.
20686
20687 @item @command{ACS SPAWN}
20688 @tab [No equivalent]@*
20689 Creates a subprocess of the current process (same as @command{DCL SPAWN}
20690 command).
20691
20692 @item @command{ACS VERIFY}
20693 @tab [No equivalent]@*
20694 Performs a series of consistency checks on a program library to
20695 determine whether the library structure and library files are in
20696 valid form.
20697 @end multitable
20698
20699 @noindent
20700
20701 @node Input-Output
20702 @section Input-Output
20703
20704 @noindent
20705 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
20706 Management Services (RMS) to perform operations on
20707 external files.
20708
20709 @noindent
20710 DEC Ada and GNAT predefine an identical set of input-
20711 output packages. To make the use of the
20712 generic TEXT_IO operations more convenient, DEC Ada
20713 provides predefined library packages that instantiate the
20714 integer and floating-point operations for the predefined
20715 integer and floating-point types as shown in the following table.
20716
20717 @multitable @columnfractions .45 .55
20718 @item @emph{Package Name} @tab Instantiation
20719
20720 @item @code{INTEGER_TEXT_IO}
20721 @tab @code{INTEGER_IO(INTEGER)}
20722
20723 @item @code{SHORT_INTEGER_TEXT_IO}
20724 @tab @code{INTEGER_IO(SHORT_INTEGER)}
20725
20726 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
20727 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
20728
20729 @item @code{FLOAT_TEXT_IO}
20730 @tab @code{FLOAT_IO(FLOAT)}
20731
20732 @item @code{LONG_FLOAT_TEXT_IO}
20733 @tab @code{FLOAT_IO(LONG_FLOAT)}
20734 @end multitable
20735
20736 @noindent
20737 The DEC Ada predefined packages and their operations
20738 are implemented using OpenVMS Alpha files and input-
20739 output facilities. DEC Ada supports asynchronous input-
20740 output on OpenVMS Alpha. Familiarity with the following is
20741 recommended:
20742 @itemize @bullet
20743 @item  RMS file organizations and access methods
20744
20745 @item  OpenVMS file specifications and directories
20746
20747 @item  OpenVMS File Definition Language (FDL)
20748 @end itemize
20749
20750 @noindent
20751 GNAT provides I/O facilities that are completely
20752 compatible with DEC Ada. The distribution includes the
20753 standard DEC Ada versions of all I/O packages, operating
20754 in a manner compatible with DEC Ada. In particular, the
20755 following packages are by default the DEC Ada (Ada 83)
20756 versions of these packages rather than the renamings
20757 suggested in annex J of the Ada 95 Reference Manual:
20758 @itemize @bullet
20759 @item  @code{TEXT_IO}
20760
20761 @item  @code{SEQUENTIAL_IO}
20762
20763 @item  @code{DIRECT_IO}
20764 @end itemize
20765
20766 @noindent
20767 The use of the standard Ada 95 syntax for child packages (for
20768 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
20769 packages, as defined in the Ada 95 Reference Manual.
20770 GNAT provides DIGITAL-compatible predefined instantiations
20771 of the @code{TEXT_IO} packages, and also
20772 provides the standard predefined instantiations required
20773 by the Ada 95 Reference Manual.
20774
20775 For further information on how GNAT interfaces to the file
20776 system or how I/O is implemented in programs written in
20777 mixed languages, see the chapter ``Implementation of the
20778 Standard I/O'' in the @cite{GNAT Reference Manual}.
20779 This chapter covers the following:
20780 @itemize @bullet
20781 @item  Standard I/O packages
20782
20783 @item  @code{FORM} strings
20784
20785 @item  @code{ADA.DIRECT_IO}
20786
20787 @item  @code{ADA.SEQUENTIAL_IO}
20788
20789 @item  @code{ADA.TEXT_IO}
20790
20791 @item  Stream pointer positioning
20792
20793 @item  Reading and writing non-regular files
20794
20795 @item  @code{GET_IMMEDIATE}
20796
20797 @item  Treating @code{TEXT_IO} files as streams
20798
20799 @item  Shared files
20800
20801 @item  Open modes
20802 @end itemize
20803
20804 @node Implementation Limits
20805 @section Implementation Limits
20806
20807 @noindent
20808 The following table lists implementation limits for DEC Ada
20809 and GNAT systems.
20810 @multitable @columnfractions .60 .20 .20
20811 @sp 1
20812 @item  @emph{Compilation Parameter}
20813 @tab   @emph{DEC Ada}
20814 @tab   @emph{GNAT}
20815 @sp 1
20816
20817 @item  In a subprogram or entry  declaration, maximum number of
20818        formal parameters that are of an unconstrained record type
20819 @tab   32
20820 @tab   No set limit
20821 @sp 1
20822
20823 @item  Maximum identifier length (number of characters)
20824 @tab   255
20825 @tab   255
20826 @sp 1
20827
20828 @item  Maximum number of characters in a source line
20829 @tab   255
20830 @tab   255
20831 @sp 1
20832
20833 @item  Maximum collection size   (number of bytes)
20834 @tab   2**31-1
20835 @tab   2**31-1
20836 @sp 1
20837
20838 @item  Maximum number of discriminants for a record type
20839 @tab   245
20840 @tab   No set limit
20841 @sp 1
20842
20843 @item  Maximum number of formal parameters in an entry or
20844        subprogram declaration
20845 @tab   246
20846 @tab    No set limit
20847 @sp 1
20848
20849 @item  Maximum number of dimensions in an array type
20850 @tab   255
20851 @tab   No set limit
20852 @sp 1
20853
20854 @item  Maximum number of library  units and subunits in a compilation.
20855 @tab   4095
20856 @tab   No set limit
20857 @sp 1
20858
20859 @item  Maximum number of library units and subunits in an execution.
20860 @tab   16383
20861 @tab   No set limit
20862 @sp 1
20863
20864 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
20865        or @code{PSECT_OBJECT}
20866 @tab   32757
20867 @tab   No set limit
20868 @sp 1
20869
20870 @item  Maximum number of enumeration literals in an enumeration type
20871        definition
20872 @tab   65535
20873 @tab   No set limit
20874 @sp 1
20875
20876 @item  Maximum number of lines in a source file
20877 @tab   65534
20878 @tab   No set limit
20879 @sp 1
20880
20881 @item  Maximum number of bits in any object
20882 @tab   2**31-1
20883 @tab   2**31-1
20884 @sp 1
20885
20886 @item  Maximum size of the static portion of a stack frame (approximate)
20887 @tab   2**31-1
20888 @tab   2**31-1
20889 @end multitable
20890
20891 @node  Tools
20892 @section Tools
20893
20894 @end ifset
20895
20896
20897 @c **************************************
20898 @node Platform-Specific Information for the Run-Time Libraries
20899 @appendix Platform-Specific Information for the Run-Time Libraries
20900 @cindex Tasking and threads libraries
20901 @cindex Threads libraries and tasking
20902 @cindex Run-time libraries (platform-specific information)
20903
20904 @noindent
20905 The GNAT run-time implementation
20906 may vary with respect to both the underlying threads library and
20907 the exception handling scheme.
20908 For threads support, one or more of the following are supplied:
20909 @itemize @bullet
20910 @item @b{native threads library}, a binding to the thread package from
20911 the underlying operating system
20912
20913 @item @b{FSU threads library}, a binding to the Florida State University
20914 threads implementation, which complies fully with the requirements of Annex D
20915
20916 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
20917 POSIX thread package
20918 @end itemize
20919
20920 @noindent
20921 For exception handling, either or both of two models are supplied:
20922 @itemize @bullet
20923 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
20924 Most programs should experience a substantial speed improvement by
20925 being compiled with a ZCX run-time.
20926 This is especially true for
20927 tasking applications or applications with many exception handlers.}
20928 @cindex Zero-Cost Exceptions
20929 @cindex ZCX (Zero-Cost Exceptions)
20930 which uses binder-generated tables that
20931 are interrogated at run time to locate a handler
20932
20933 @item @b{setjmp / longjmp} (``SJLJ''),
20934 @cindex setjmp/longjmp Exception Model
20935 @cindex SJLJ (setjmp/longjmp Exception Model)
20936 which uses dynamically-set data to establish
20937 the set of handlers
20938 @end itemize
20939
20940 @noindent
20941 This appendix summarizes which combinations of threads and exception support
20942 are supplied on various GNAT platforms.
20943 It then shows how to select a particular library either
20944 permanently or temporarily,
20945 explains the properties of (and tradeoffs among) the various threads
20946 libraries, and provides some additional
20947 information about several specific platforms.
20948
20949 @menu
20950 * Summary of Run-Time Configurations::
20951 * Specifying a Run-Time Library::
20952 * Choosing between Native and FSU Threads Libraries::
20953 * Choosing the Scheduling Policy::
20954 * Solaris-Specific Considerations::
20955 * IRIX-Specific Considerations::
20956 * Linux-Specific Considerations::
20957 * AIX-Specific Considerations::
20958 @end menu
20959
20960
20961 @node Summary of Run-Time Configurations
20962 @section Summary of Run-Time Configurations
20963
20964
20965 @multitable @columnfractions .30 .70
20966 @item @b{alpha-openvms}
20967 @item @code{@ @ }@i{rts-native (default)}
20968 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
20969 @item @code{@ @ @ @ }Exceptions @tab ZCX
20970 @*
20971 @item @b{pa-hpux}
20972 @item @code{@ @ }@i{rts-native (default)}
20973 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
20974 @item @code{@ @ @ @ }Exceptions @tab ZCX
20975 @*
20976 @item @code{@ @ }@i{rts-sjlj}
20977 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
20978 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20979 @*
20980 @item @b{sparc-solaris}  @tab
20981 @item @code{@ @ }@i{rts-native (default)}
20982 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
20983 @item @code{@ @ @ @ }Exceptions @tab ZCX
20984 @*
20985 @item @code{@ @ }@i{rts-fsu}    @tab
20986 @item @code{@ @ @ @ }Tasking    @tab FSU threads library
20987 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20988 @*
20989 @item @code{@ @ }@i{rts-m64}
20990 @item @code{@ @ @ @ }Tasking     @tab native Solaris threads library
20991 @item @code{@ @ @ @ }Exceptions  @tab ZCX
20992 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
20993 @item    @tab Use only on Solaris 8 or later.
20994 @item    @tab @xref{Building and Debugging 64-bit Applications}, for details.
20995 @*
20996 @item @code{@ @ }@i{rts-pthread}
20997 @item @code{@ @ @ @ }Tasking    @tab pthreads library
20998 @item @code{@ @ @ @ }Exceptions @tab ZCX
20999 @*
21000 @item @code{@ @ }@i{rts-sjlj}
21001 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21002 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21003 @*
21004 @item @b{x86-linux}
21005 @item @code{@ @ }@i{rts-native (default)}
21006 @item @code{@ @ @ @ }Tasking    @tab LinuxThread library
21007 @item @code{@ @ @ @ }Exceptions @tab ZCX
21008 @*
21009 @item @code{@ @ }@i{rts-fsu}
21010 @item @code{@ @ @ @ }Tasking    @tab FSU threads library
21011 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21012 @*
21013 @item @code{@ @ }@i{rts-sjlj}
21014 @item @code{@ @ @ @ }Tasking    @tab LinuxThread library
21015 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21016 @*
21017 @item @b{x86-windows}
21018 @item @code{@ @ }@i{rts-native (default)}
21019 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21020 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21021 @*
21022 @end multitable
21023
21024
21025
21026 @node Specifying a Run-Time Library
21027 @section Specifying a Run-Time Library
21028
21029 @noindent
21030 The @file{adainclude} subdirectory containing the sources of the GNAT
21031 run-time library, and the @file{adalib} subdirectory containing the
21032 @file{ALI} files and the static and/or shared GNAT library, are located
21033 in the gcc target-dependent area:
21034
21035 @smallexample
21036 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21037 @end smallexample
21038
21039 @noindent
21040 As indicated above, on some platforms several run-time libraries are supplied.
21041 These libraries are installed in the target dependent area and
21042 contain a complete source and binary subdirectory. The detailed description
21043 below explains the differences between the different libraries in terms of
21044 their thread support.
21045
21046 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21047 This default run time is selected by the means of soft links.
21048 For example on x86-linux:
21049
21050 @smallexample
21051 @group
21052  $(target-dir)
21053      |
21054      +--- adainclude----------+
21055      |                        |
21056      +--- adalib-----------+  |
21057      |                     |  |
21058      +--- rts-native       |  |
21059      |    |                |  |
21060      |    +--- adainclude <---+
21061      |    |                |
21062      |    +--- adalib <----+
21063      |
21064      +--- rts-fsu
21065      |    |
21066      |    +--- adainclude
21067      |    |
21068      |    +--- adalib
21069      |
21070      +--- rts-sjlj
21071           |
21072           +--- adainclude
21073           |
21074           +--- adalib
21075 @end group
21076 @end smallexample
21077
21078 @noindent
21079 If the @i{rts-fsu} library is to be selected on a permanent basis,
21080 these soft links can be modified with the following commands:
21081
21082 @smallexample
21083 $ cd $target
21084 $ rm -f adainclude adalib
21085 $ ln -s rts-fsu/adainclude adainclude
21086 $ ln -s rts-fsu/adalib adalib
21087 @end smallexample
21088
21089 @noindent
21090 Alternatively, you can specify @file{rts-fsu/adainclude} in the file
21091 @file{$target/ada_source_path} and @file{rts-fsu/adalib} in
21092 @file{$target/ada_object_path}.
21093
21094 Selecting another run-time library temporarily can be
21095 achieved by the regular mechanism for GNAT object or source path selection:
21096
21097 @itemize @bullet
21098 @item
21099 Set the environment variables:
21100
21101 @smallexample
21102 $ ADA_INCLUDE_PATH=$target/rts-fsu/adainclude:$ADA_INCLUDE_PATH
21103 $ ADA_OBJECTS_PATH=$target/rts-fsu/adalib:$ADA_OBJECTS_PATH
21104 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
21105 @end smallexample
21106
21107 @item
21108 Use @option{-aI$target/rts-fsu/adainclude}
21109 and @option{-aO$target/rts-fsu/adalib}
21110 on the @command{gnatmake} command line
21111
21112 @item
21113 Use the switch @option{--RTS}; e.g., @option{--RTS=fsu}
21114 @cindex @option{--RTS} option
21115 @end itemize
21116
21117 @noindent
21118 You can similarly switch to @emph{rts-sjlj}.
21119
21120 @node Choosing between Native and FSU Threads Libraries
21121 @section Choosing between Native and FSU Threads Libraries
21122 @cindex Native threads library
21123 @cindex FSU threads library
21124
21125 @noindent
21126 Some GNAT implementations offer a choice between
21127 native threads and FSU threads.
21128
21129 @itemize @bullet
21130 @item
21131 The @emph{native threads} library correspond to the standard system threads
21132 implementation (e.g. LinuxThreads on GNU/Linux,
21133 @cindex LinuxThreads library
21134 POSIX threads on AIX, or
21135 Solaris threads on Solaris). When this option is chosen, GNAT provides
21136 a full and accurate implementation of the core language tasking model
21137 as described in Chapter 9 of the Ada Reference Manual,
21138 but might not (and probably does not) implement
21139 the exact semantics as specified in @w{Annex D} (the Real-Time Systems Annex).
21140 @cindex Annex D (Real-Time Systems Annex) compliance
21141 @cindex Real-Time Systems Annex compliance
21142 Indeed, the reason that a choice of libraries is offered
21143 on a given target is because some of the
21144 ACATS tests for @w{Annex D} fail using the native threads library.
21145 As far as possible, this library is implemented
21146 in accordance with Ada semantics (e.g., modifying priorities as required
21147 to simulate ceiling locking),
21148 but there are often slight inaccuracies, most often in the area of
21149 absolutely respecting the priority rules on a single
21150 processor.
21151 Moreover, it is not possible in general to define the exact behavior,
21152 because the native threads implementations
21153 are not well enough documented.
21154
21155 On systems where the @code{SCHED_FIFO} POSIX scheduling policy is supported,
21156 @cindex POSIX scheduling policies
21157 @cindex @code{SCHED_FIFO} scheduling policy
21158 native threads will provide a behavior very close to the @w{Annex D}
21159 requirements (i.e., a run-till-blocked scheduler with fixed priorities), but
21160 on some systems (in particular GNU/Linux and Solaris), you need to have root
21161 privileges to use the @code{SCHED_FIFO} policy.
21162
21163 @item
21164 The @emph{FSU threads} library provides a completely accurate implementation
21165 of @w{Annex D}.
21166 Thus, operating with this library, GNAT is 100% compliant with both the core
21167 and all @w{Annex D}
21168 requirements.
21169 The formal validations for implementations offering
21170 a choice of threads packages are always carried out using the FSU
21171 threads option.
21172 @end itemize
21173
21174 @noindent
21175 From these considerations, it might seem that FSU threads are the
21176 better choice,
21177 but that is by no means always the case. The FSU threads package
21178 operates with all Ada tasks appearing to the system to be a single
21179 thread. This is often considerably more efficient than operating
21180 with separate threads, since for example, switching between tasks
21181 can be accomplished without the (in some cases considerable)
21182 overhead of a context switch between two system threads. However,
21183 it means that you may well lose concurrency at the system
21184 level. Notably, some system operations (such as I/O) may block all
21185 tasks in a program and not just the calling task. More
21186 significantly, the FSU threads approach likely means you cannot
21187 take advantage of multiple processors, since for this you need
21188 separate threads (or even separate processes) to operate on
21189 different processors.
21190
21191 For most programs, the native threads library is
21192 usually the better choice. Use the FSU threads if absolute
21193 conformance to @w{Annex D} is important for your application, or if
21194 you find that the improved efficiency of FSU threads is significant to you.
21195
21196 Note also that to take full advantage of Florist and Glade, it is highly
21197 recommended that you use native threads.
21198
21199
21200 @node Choosing the Scheduling Policy
21201 @section Choosing the Scheduling Policy
21202
21203 @noindent
21204 When using a POSIX threads implementation, you have a choice of several
21205 scheduling policies: @code{SCHED_FIFO},
21206 @cindex @code{SCHED_FIFO} scheduling policy
21207 @code{SCHED_RR}
21208 @cindex @code{SCHED_RR} scheduling policy
21209 and @code{SCHED_OTHER}.
21210 @cindex @code{SCHED_OTHER} scheduling policy
21211 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21212 or @code{SCHED_RR} requires special (e.g., root) privileges.
21213
21214 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21215 @code{SCHED_FIFO},
21216 @cindex @code{SCHED_FIFO} scheduling policy
21217 you can use one of the following:
21218
21219 @itemize @bullet
21220 @item
21221 @code{pragma Time_Slice (0.0)}
21222 @cindex pragma Time_Slice
21223 @item
21224 the corresponding binder option @option{-T0}
21225 @cindex @option{-T0} option
21226 @item
21227 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21228 @cindex pragma Task_Dispatching_Policy
21229 @end itemize
21230
21231 @noindent
21232 To specify @code{SCHED_RR},
21233 @cindex @code{SCHED_RR} scheduling policy
21234 you should use @code{pragma Time_Slice} with a
21235 value greater than @code{0.0}, or else use the corresponding @option{-T}
21236 binder option.
21237
21238
21239
21240 @node Solaris-Specific Considerations
21241 @section Solaris-Specific Considerations
21242 @cindex Solaris Sparc threads libraries
21243
21244 @noindent
21245 This section addresses some topics related to the various threads libraries
21246 on Sparc Solaris and then provides some information on building and
21247 debugging 64-bit applications.
21248
21249 @menu
21250 * Solaris Threads Issues::
21251 * Building and Debugging 64-bit Applications::
21252 @end menu
21253
21254
21255 @node Solaris Threads Issues
21256 @subsection Solaris Threads Issues
21257
21258 @noindent
21259 Starting with version 3.14, GNAT under Solaris comes with a new tasking
21260 run-time library based on POSIX threads --- @emph{rts-pthread}.
21261 @cindex rts-pthread threads library
21262 This run-time library has the advantage of being mostly shared across all
21263 POSIX-compliant thread implementations, and it also provides under
21264 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21265 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21266 and @code{PTHREAD_PRIO_PROTECT}
21267 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21268 semantics that can be selected using the predefined pragma
21269 @code{Locking_Policy}
21270 @cindex pragma Locking_Policy (under rts-pthread)
21271 with respectively
21272 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21273 @cindex @code{Inheritance_Locking} (under rts-pthread)
21274 @cindex @code{Ceiling_Locking} (under rts-pthread)
21275
21276 As explained above, the native run-time library is based on the Solaris thread
21277 library (@code{libthread}) and is the default library.
21278 The FSU run-time library is based on the FSU threads.
21279 @cindex FSU threads library
21280
21281 Starting with Solaris 2.5.1, when the Solaris threads library is used
21282 (this is the default), programs
21283 compiled with GNAT can automatically take advantage of
21284 and can thus execute on multiple processors.
21285 The user can alternatively specify a processor on which the program should run
21286 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21287 is made by
21288 setting the environment variable @code{GNAT_PROCESSOR}
21289 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21290 to one of the following:
21291
21292 @table @code
21293 @item -2
21294 Use the default configuration (run the program on all
21295          available processors) - this is the same as having
21296          @code{GNAT_PROCESSOR} unset
21297
21298 @item -1
21299 Let the run-time implementation choose one processor and run the program on
21300          that processor
21301
21302 @item 0 .. Last_Proc
21303 Run the program on the specified processor.
21304   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21305 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21306 @end table
21307
21308
21309 @node Building and Debugging 64-bit Applications
21310 @subsection Building and Debugging 64-bit Applications
21311
21312 @noindent
21313 In a 64-bit application, all the sources involved must be compiled with the
21314 @option{-m64} command-line option, and a specific GNAT library (compiled with
21315 this option) is required.
21316 The easiest way to build a 64bit application is to add
21317 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
21318
21319 To debug these applications, dwarf-2 debug information is required, so you
21320 have to add @option{-gdwarf-2} to your gnatmake arguments.
21321 In addition, a special
21322 version of gdb, called @command{gdb64}, needs to be used.
21323
21324 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
21325 amounts to:
21326
21327 @smallexample
21328      $ gnatmake -m64 -gdwarf-2 --RTS=m64 hello.adb
21329      $ gdb64 hello
21330 @end smallexample
21331
21332
21333
21334 @node IRIX-Specific Considerations
21335 @section IRIX-Specific Considerations
21336 @cindex IRIX thread library
21337
21338 @noindent
21339 On SGI IRIX, the thread library depends on which compiler is used.
21340 The @emph{o32 ABI} compiler comes with a run-time library based on the
21341 user-level @code{athread}
21342 library. Thus kernel-level capabilities such as nonblocking system
21343 calls or time slicing can only be achieved reliably by specifying different
21344 @code{sprocs} via the pragma @code{Task_Info}
21345 @cindex pragma Task_Info (and IRIX threads)
21346 and the
21347 @code{System.Task_Info} package.
21348 @cindex @code{System.Task_Info} package (and IRIX threads)
21349 See the @cite{GNAT Reference Manual} for further information.
21350
21351 The @emph{n32 ABI} compiler comes with a run-time library based on the
21352 kernel POSIX threads and thus does not have the limitations mentioned above.
21353
21354
21355 @node Linux-Specific Considerations
21356 @section Linux-Specific Considerations
21357 @cindex Linux threads libraries
21358
21359 @noindent
21360 The default thread library under GNU/Linux has the following disadvantages
21361 compared to other native thread libraries:
21362
21363 @itemize @bullet
21364 @item The size of the task's stack is limited to 2 megabytes.
21365 @item  The signal model is not POSIX compliant, which means that to send a
21366   signal to the process, you need to send the signal to all threads,
21367   e.g. by using @code{killpg()}.
21368 @end itemize
21369
21370 @node AIX-Specific Considerations
21371 @section AIX-Specific Considerations
21372 @cindex AIX resolver library
21373
21374 @noindent
21375 On AIX, the resolver library initializes some internal structure on
21376 the first call to @code{get*by*} functions, which are used to implement
21377 @code{GNAT.Sockets.Get_Host_By_Name} and
21378 @code{GNAT.Sockets.Get_Host_By_Addrss}.
21379 If such initialization occurs within an Ada task, and the stack size for
21380 the task is the default size, a stack overflow may occur.
21381
21382 To avoid this overflow, the user should either ensure that the first call
21383 to @code{GNAT.Sockets.Get_Host_By_Name} or
21384 @code{GNAT.Sockets.Get_Host_By_Addrss}
21385 occurs in the environment task, or use @code{pragma Storage_Size} to
21386 specify a sufficiently large size for the stack of the task that contains
21387 this call.
21388
21389 @c *******************************
21390 @node Example of Binder Output File
21391 @appendix Example of Binder Output File
21392
21393 @noindent
21394 This Appendix displays the source code for @command{gnatbind}'s output
21395 file generated for a simple ``Hello World'' program.
21396 Comments have been added for clarification purposes.
21397
21398
21399 @smallexample @c adanocomment
21400 @iftex
21401 @leftskip=0cm
21402 @end iftex
21403 --  The package is called Ada_Main unless this name is actually used
21404 --  as a unit name in the partition, in which case some other unique
21405 --  name is used.
21406
21407 with System;
21408 package ada_main is
21409
21410    Elab_Final_Code : Integer;
21411    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
21412
21413    --  The main program saves the parameters (argument count,
21414    --  argument values, environment pointer) in global variables
21415    --  for later access by other units including
21416    --  Ada.Command_Line.
21417
21418    gnat_argc : Integer;
21419    gnat_argv : System.Address;
21420    gnat_envp : System.Address;
21421
21422    --  The actual variables are stored in a library routine. This
21423    --  is useful for some shared library situations, where there
21424    --  are problems if variables are not in the library.
21425
21426    pragma Import (C, gnat_argc);
21427    pragma Import (C, gnat_argv);
21428    pragma Import (C, gnat_envp);
21429
21430    --  The exit status is similarly an external location
21431
21432    gnat_exit_status : Integer;
21433    pragma Import (C, gnat_exit_status);
21434
21435    GNAT_Version : constant String :=
21436                     "GNAT Version: 3.15w (20010315)";
21437    pragma Export (C, GNAT_Version, "__gnat_version");
21438
21439    --  This is the generated adafinal routine that performs
21440    --  finalization at the end of execution. In the case where
21441    --  Ada is the main program, this main program makes a call
21442    --  to adafinal at program termination.
21443
21444    procedure adafinal;
21445    pragma Export (C, adafinal, "adafinal");
21446
21447    --  This is the generated adainit routine that performs
21448    --  initialization at the start of execution. In the case
21449    --  where Ada is the main program, this main program makes
21450    --  a call to adainit at program startup.
21451
21452    procedure adainit;
21453    pragma Export (C, adainit, "adainit");
21454
21455    --  This routine is called at the start of execution. It is
21456    --  a dummy routine that is used by the debugger to breakpoint
21457    --  at the start of execution.
21458
21459    procedure Break_Start;
21460    pragma Import (C, Break_Start, "__gnat_break_start");
21461
21462    --  This is the actual generated main program (it would be
21463    --  suppressed if the no main program switch were used). As
21464    --  required by standard system conventions, this program has
21465    --  the external name main.
21466
21467    function main
21468      (argc : Integer;
21469       argv : System.Address;
21470       envp : System.Address)
21471       return Integer;
21472    pragma Export (C, main, "main");
21473
21474    --  The following set of constants give the version
21475    --  identification values for every unit in the bound
21476    --  partition. This identification is computed from all
21477    --  dependent semantic units, and corresponds to the
21478    --  string that would be returned by use of the
21479    --  Body_Version or Version attributes.
21480
21481    type Version_32 is mod 2 ** 32;
21482    u00001 : constant Version_32 := 16#7880BEB3#;
21483    u00002 : constant Version_32 := 16#0D24CBD0#;
21484    u00003 : constant Version_32 := 16#3283DBEB#;
21485    u00004 : constant Version_32 := 16#2359F9ED#;
21486    u00005 : constant Version_32 := 16#664FB847#;
21487    u00006 : constant Version_32 := 16#68E803DF#;
21488    u00007 : constant Version_32 := 16#5572E604#;
21489    u00008 : constant Version_32 := 16#46B173D8#;
21490    u00009 : constant Version_32 := 16#156A40CF#;
21491    u00010 : constant Version_32 := 16#033DABE0#;
21492    u00011 : constant Version_32 := 16#6AB38FEA#;
21493    u00012 : constant Version_32 := 16#22B6217D#;
21494    u00013 : constant Version_32 := 16#68A22947#;
21495    u00014 : constant Version_32 := 16#18CC4A56#;
21496    u00015 : constant Version_32 := 16#08258E1B#;
21497    u00016 : constant Version_32 := 16#367D5222#;
21498    u00017 : constant Version_32 := 16#20C9ECA4#;
21499    u00018 : constant Version_32 := 16#50D32CB6#;
21500    u00019 : constant Version_32 := 16#39A8BB77#;
21501    u00020 : constant Version_32 := 16#5CF8FA2B#;
21502    u00021 : constant Version_32 := 16#2F1EB794#;
21503    u00022 : constant Version_32 := 16#31AB6444#;
21504    u00023 : constant Version_32 := 16#1574B6E9#;
21505    u00024 : constant Version_32 := 16#5109C189#;
21506    u00025 : constant Version_32 := 16#56D770CD#;
21507    u00026 : constant Version_32 := 16#02F9DE3D#;
21508    u00027 : constant Version_32 := 16#08AB6B2C#;
21509    u00028 : constant Version_32 := 16#3FA37670#;
21510    u00029 : constant Version_32 := 16#476457A0#;
21511    u00030 : constant Version_32 := 16#731E1B6E#;
21512    u00031 : constant Version_32 := 16#23C2E789#;
21513    u00032 : constant Version_32 := 16#0F1BD6A1#;
21514    u00033 : constant Version_32 := 16#7C25DE96#;
21515    u00034 : constant Version_32 := 16#39ADFFA2#;
21516    u00035 : constant Version_32 := 16#571DE3E7#;
21517    u00036 : constant Version_32 := 16#5EB646AB#;
21518    u00037 : constant Version_32 := 16#4249379B#;
21519    u00038 : constant Version_32 := 16#0357E00A#;
21520    u00039 : constant Version_32 := 16#3784FB72#;
21521    u00040 : constant Version_32 := 16#2E723019#;
21522    u00041 : constant Version_32 := 16#623358EA#;
21523    u00042 : constant Version_32 := 16#107F9465#;
21524    u00043 : constant Version_32 := 16#6843F68A#;
21525    u00044 : constant Version_32 := 16#63305874#;
21526    u00045 : constant Version_32 := 16#31E56CE1#;
21527    u00046 : constant Version_32 := 16#02917970#;
21528    u00047 : constant Version_32 := 16#6CCBA70E#;
21529    u00048 : constant Version_32 := 16#41CD4204#;
21530    u00049 : constant Version_32 := 16#572E3F58#;
21531    u00050 : constant Version_32 := 16#20729FF5#;
21532    u00051 : constant Version_32 := 16#1D4F93E8#;
21533    u00052 : constant Version_32 := 16#30B2EC3D#;
21534    u00053 : constant Version_32 := 16#34054F96#;
21535    u00054 : constant Version_32 := 16#5A199860#;
21536    u00055 : constant Version_32 := 16#0E7F912B#;
21537    u00056 : constant Version_32 := 16#5760634A#;
21538    u00057 : constant Version_32 := 16#5D851835#;
21539
21540    --  The following Export pragmas export the version numbers
21541    --  with symbolic names ending in B (for body) or S
21542    --  (for spec) so that they can be located in a link. The
21543    --  information provided here is sufficient to track down
21544    --  the exact versions of units used in a given build.
21545
21546    pragma Export (C, u00001, "helloB");
21547    pragma Export (C, u00002, "system__standard_libraryB");
21548    pragma Export (C, u00003, "system__standard_libraryS");
21549    pragma Export (C, u00004, "adaS");
21550    pragma Export (C, u00005, "ada__text_ioB");
21551    pragma Export (C, u00006, "ada__text_ioS");
21552    pragma Export (C, u00007, "ada__exceptionsB");
21553    pragma Export (C, u00008, "ada__exceptionsS");
21554    pragma Export (C, u00009, "gnatS");
21555    pragma Export (C, u00010, "gnat__heap_sort_aB");
21556    pragma Export (C, u00011, "gnat__heap_sort_aS");
21557    pragma Export (C, u00012, "systemS");
21558    pragma Export (C, u00013, "system__exception_tableB");
21559    pragma Export (C, u00014, "system__exception_tableS");
21560    pragma Export (C, u00015, "gnat__htableB");
21561    pragma Export (C, u00016, "gnat__htableS");
21562    pragma Export (C, u00017, "system__exceptionsS");
21563    pragma Export (C, u00018, "system__machine_state_operationsB");
21564    pragma Export (C, u00019, "system__machine_state_operationsS");
21565    pragma Export (C, u00020, "system__machine_codeS");
21566    pragma Export (C, u00021, "system__storage_elementsB");
21567    pragma Export (C, u00022, "system__storage_elementsS");
21568    pragma Export (C, u00023, "system__secondary_stackB");
21569    pragma Export (C, u00024, "system__secondary_stackS");
21570    pragma Export (C, u00025, "system__parametersB");
21571    pragma Export (C, u00026, "system__parametersS");
21572    pragma Export (C, u00027, "system__soft_linksB");
21573    pragma Export (C, u00028, "system__soft_linksS");
21574    pragma Export (C, u00029, "system__stack_checkingB");
21575    pragma Export (C, u00030, "system__stack_checkingS");
21576    pragma Export (C, u00031, "system__tracebackB");
21577    pragma Export (C, u00032, "system__tracebackS");
21578    pragma Export (C, u00033, "ada__streamsS");
21579    pragma Export (C, u00034, "ada__tagsB");
21580    pragma Export (C, u00035, "ada__tagsS");
21581    pragma Export (C, u00036, "system__string_opsB");
21582    pragma Export (C, u00037, "system__string_opsS");
21583    pragma Export (C, u00038, "interfacesS");
21584    pragma Export (C, u00039, "interfaces__c_streamsB");
21585    pragma Export (C, u00040, "interfaces__c_streamsS");
21586    pragma Export (C, u00041, "system__file_ioB");
21587    pragma Export (C, u00042, "system__file_ioS");
21588    pragma Export (C, u00043, "ada__finalizationB");
21589    pragma Export (C, u00044, "ada__finalizationS");
21590    pragma Export (C, u00045, "system__finalization_rootB");
21591    pragma Export (C, u00046, "system__finalization_rootS");
21592    pragma Export (C, u00047, "system__finalization_implementationB");
21593    pragma Export (C, u00048, "system__finalization_implementationS");
21594    pragma Export (C, u00049, "system__string_ops_concat_3B");
21595    pragma Export (C, u00050, "system__string_ops_concat_3S");
21596    pragma Export (C, u00051, "system__stream_attributesB");
21597    pragma Export (C, u00052, "system__stream_attributesS");
21598    pragma Export (C, u00053, "ada__io_exceptionsS");
21599    pragma Export (C, u00054, "system__unsigned_typesS");
21600    pragma Export (C, u00055, "system__file_control_blockS");
21601    pragma Export (C, u00056, "ada__finalization__list_controllerB");
21602    pragma Export (C, u00057, "ada__finalization__list_controllerS");
21603
21604    -- BEGIN ELABORATION ORDER
21605    -- ada (spec)
21606    -- gnat (spec)
21607    -- gnat.heap_sort_a (spec)
21608    -- gnat.heap_sort_a (body)
21609    -- gnat.htable (spec)
21610    -- gnat.htable (body)
21611    -- interfaces (spec)
21612    -- system (spec)
21613    -- system.machine_code (spec)
21614    -- system.parameters (spec)
21615    -- system.parameters (body)
21616    -- interfaces.c_streams (spec)
21617    -- interfaces.c_streams (body)
21618    -- system.standard_library (spec)
21619    -- ada.exceptions (spec)
21620    -- system.exception_table (spec)
21621    -- system.exception_table (body)
21622    -- ada.io_exceptions (spec)
21623    -- system.exceptions (spec)
21624    -- system.storage_elements (spec)
21625    -- system.storage_elements (body)
21626    -- system.machine_state_operations (spec)
21627    -- system.machine_state_operations (body)
21628    -- system.secondary_stack (spec)
21629    -- system.stack_checking (spec)
21630    -- system.soft_links (spec)
21631    -- system.soft_links (body)
21632    -- system.stack_checking (body)
21633    -- system.secondary_stack (body)
21634    -- system.standard_library (body)
21635    -- system.string_ops (spec)
21636    -- system.string_ops (body)
21637    -- ada.tags (spec)
21638    -- ada.tags (body)
21639    -- ada.streams (spec)
21640    -- system.finalization_root (spec)
21641    -- system.finalization_root (body)
21642    -- system.string_ops_concat_3 (spec)
21643    -- system.string_ops_concat_3 (body)
21644    -- system.traceback (spec)
21645    -- system.traceback (body)
21646    -- ada.exceptions (body)
21647    -- system.unsigned_types (spec)
21648    -- system.stream_attributes (spec)
21649    -- system.stream_attributes (body)
21650    -- system.finalization_implementation (spec)
21651    -- system.finalization_implementation (body)
21652    -- ada.finalization (spec)
21653    -- ada.finalization (body)
21654    -- ada.finalization.list_controller (spec)
21655    -- ada.finalization.list_controller (body)
21656    -- system.file_control_block (spec)
21657    -- system.file_io (spec)
21658    -- system.file_io (body)
21659    -- ada.text_io (spec)
21660    -- ada.text_io (body)
21661    -- hello (body)
21662    -- END ELABORATION ORDER
21663
21664 end ada_main;
21665
21666 --  The following source file name pragmas allow the generated file
21667 --  names to be unique for different main programs. They are needed
21668 --  since the package name will always be Ada_Main.
21669
21670 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
21671 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
21672
21673 --  Generated package body for Ada_Main starts here
21674
21675 package body ada_main is
21676
21677    --  The actual finalization is performed by calling the
21678    --  library routine in System.Standard_Library.Adafinal
21679
21680    procedure Do_Finalize;
21681    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
21682
21683    -------------
21684    -- adainit --
21685    -------------
21686
21687 @findex adainit
21688    procedure adainit is
21689
21690       --  These booleans are set to True once the associated unit has
21691       --  been elaborated. It is also used to avoid elaborating the
21692       --  same unit twice.
21693
21694       E040 : Boolean;
21695       pragma Import (Ada, E040, "interfaces__c_streams_E");
21696
21697       E008 : Boolean;
21698       pragma Import (Ada, E008, "ada__exceptions_E");
21699
21700       E014 : Boolean;
21701       pragma Import (Ada, E014, "system__exception_table_E");
21702
21703       E053 : Boolean;
21704       pragma Import (Ada, E053, "ada__io_exceptions_E");
21705
21706       E017 : Boolean;
21707       pragma Import (Ada, E017, "system__exceptions_E");
21708
21709       E024 : Boolean;
21710       pragma Import (Ada, E024, "system__secondary_stack_E");
21711
21712       E030 : Boolean;
21713       pragma Import (Ada, E030, "system__stack_checking_E");
21714
21715       E028 : Boolean;
21716       pragma Import (Ada, E028, "system__soft_links_E");
21717
21718       E035 : Boolean;
21719       pragma Import (Ada, E035, "ada__tags_E");
21720
21721       E033 : Boolean;
21722       pragma Import (Ada, E033, "ada__streams_E");
21723
21724       E046 : Boolean;
21725       pragma Import (Ada, E046, "system__finalization_root_E");
21726
21727       E048 : Boolean;
21728       pragma Import (Ada, E048, "system__finalization_implementation_E");
21729
21730       E044 : Boolean;
21731       pragma Import (Ada, E044, "ada__finalization_E");
21732
21733       E057 : Boolean;
21734       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
21735
21736       E055 : Boolean;
21737       pragma Import (Ada, E055, "system__file_control_block_E");
21738
21739       E042 : Boolean;
21740       pragma Import (Ada, E042, "system__file_io_E");
21741
21742       E006 : Boolean;
21743       pragma Import (Ada, E006, "ada__text_io_E");
21744
21745       --  Set_Globals is a library routine that stores away the
21746       --  value of the indicated set of global values in global
21747       --  variables within the library.
21748
21749       procedure Set_Globals
21750         (Main_Priority            : Integer;
21751          Time_Slice_Value         : Integer;
21752          WC_Encoding              : Character;
21753          Locking_Policy           : Character;
21754          Queuing_Policy           : Character;
21755          Task_Dispatching_Policy  : Character;
21756          Adafinal                 : System.Address;
21757          Unreserve_All_Interrupts : Integer;
21758          Exception_Tracebacks     : Integer);
21759 @findex __gnat_set_globals
21760       pragma Import (C, Set_Globals, "__gnat_set_globals");
21761
21762       --  SDP_Table_Build is a library routine used to build the
21763       --  exception tables. See unit Ada.Exceptions in files
21764       --  a-except.ads/adb for full details of how zero cost
21765       --  exception handling works. This procedure, the call to
21766       --  it, and the two following tables are all omitted if the
21767       --  build is in longjmp/setjump exception mode.
21768
21769 @findex SDP_Table_Build
21770 @findex Zero Cost Exceptions
21771       procedure SDP_Table_Build
21772         (SDP_Addresses   : System.Address;
21773          SDP_Count       : Natural;
21774          Elab_Addresses  : System.Address;
21775          Elab_Addr_Count : Natural);
21776       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
21777
21778       --  Table of Unit_Exception_Table addresses. Used for zero
21779       --  cost exception handling to build the top level table.
21780
21781       ST : aliased constant array (1 .. 23) of System.Address := (
21782         Hello'UET_Address,
21783         Ada.Text_Io'UET_Address,
21784         Ada.Exceptions'UET_Address,
21785         Gnat.Heap_Sort_A'UET_Address,
21786         System.Exception_Table'UET_Address,
21787         System.Machine_State_Operations'UET_Address,
21788         System.Secondary_Stack'UET_Address,
21789         System.Parameters'UET_Address,
21790         System.Soft_Links'UET_Address,
21791         System.Stack_Checking'UET_Address,
21792         System.Traceback'UET_Address,
21793         Ada.Streams'UET_Address,
21794         Ada.Tags'UET_Address,
21795         System.String_Ops'UET_Address,
21796         Interfaces.C_Streams'UET_Address,
21797         System.File_Io'UET_Address,
21798         Ada.Finalization'UET_Address,
21799         System.Finalization_Root'UET_Address,
21800         System.Finalization_Implementation'UET_Address,
21801         System.String_Ops_Concat_3'UET_Address,
21802         System.Stream_Attributes'UET_Address,
21803         System.File_Control_Block'UET_Address,
21804         Ada.Finalization.List_Controller'UET_Address);
21805
21806       --  Table of addresses of elaboration routines. Used for
21807       --  zero cost exception handling to make sure these
21808       --  addresses are included in the top level procedure
21809       --  address table.
21810
21811       EA : aliased constant array (1 .. 23) of System.Address := (
21812         adainit'Code_Address,
21813         Do_Finalize'Code_Address,
21814         Ada.Exceptions'Elab_Spec'Address,
21815         System.Exceptions'Elab_Spec'Address,
21816         Interfaces.C_Streams'Elab_Spec'Address,
21817         System.Exception_Table'Elab_Body'Address,
21818         Ada.Io_Exceptions'Elab_Spec'Address,
21819         System.Stack_Checking'Elab_Spec'Address,
21820         System.Soft_Links'Elab_Body'Address,
21821         System.Secondary_Stack'Elab_Body'Address,
21822         Ada.Tags'Elab_Spec'Address,
21823         Ada.Tags'Elab_Body'Address,
21824         Ada.Streams'Elab_Spec'Address,
21825         System.Finalization_Root'Elab_Spec'Address,
21826         Ada.Exceptions'Elab_Body'Address,
21827         System.Finalization_Implementation'Elab_Spec'Address,
21828         System.Finalization_Implementation'Elab_Body'Address,
21829         Ada.Finalization'Elab_Spec'Address,
21830         Ada.Finalization.List_Controller'Elab_Spec'Address,
21831         System.File_Control_Block'Elab_Spec'Address,
21832         System.File_Io'Elab_Body'Address,
21833         Ada.Text_Io'Elab_Spec'Address,
21834         Ada.Text_Io'Elab_Body'Address);
21835
21836    --  Start of processing for adainit
21837
21838    begin
21839
21840       --  Call SDP_Table_Build to build the top level procedure
21841       --  table for zero cost exception handling (omitted in
21842       --  longjmp/setjump mode).
21843
21844       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
21845
21846       --  Call Set_Globals to record various information for
21847       --  this partition.  The values are derived by the binder
21848       --  from information stored in the ali files by the compiler.
21849
21850 @findex __gnat_set_globals
21851       Set_Globals
21852         (Main_Priority            => -1,
21853          --  Priority of main program, -1 if no pragma Priority used
21854
21855          Time_Slice_Value         => -1,
21856          --  Time slice from Time_Slice pragma, -1 if none used
21857
21858          WC_Encoding              => 'b',
21859          --  Wide_Character encoding used, default is brackets
21860
21861          Locking_Policy           => ' ',
21862          --  Locking_Policy used, default of space means not
21863          --  specified, otherwise it is the first character of
21864          --  the policy name.
21865
21866          Queuing_Policy           => ' ',
21867          --  Queuing_Policy used, default of space means not
21868          --  specified, otherwise it is the first character of
21869          --  the policy name.
21870
21871          Task_Dispatching_Policy  => ' ',
21872          --  Task_Dispatching_Policy used, default of space means
21873          --  not specified, otherwise first character of the
21874          --  policy name.
21875
21876          Adafinal                 => System.Null_Address,
21877          --  Address of Adafinal routine, not used anymore
21878
21879          Unreserve_All_Interrupts => 0,
21880          --  Set true if pragma Unreserve_All_Interrupts was used
21881
21882          Exception_Tracebacks     => 0);
21883          --  Indicates if exception tracebacks are enabled
21884
21885       Elab_Final_Code := 1;
21886
21887       --  Now we have the elaboration calls for all units in the partition.
21888       --  The Elab_Spec and Elab_Body attributes generate references to the
21889       --  implicit elaboration procedures generated by the compiler for
21890       --  each unit that requires elaboration.
21891
21892       if not E040 then
21893          Interfaces.C_Streams'Elab_Spec;
21894       end if;
21895       E040 := True;
21896       if not E008 then
21897          Ada.Exceptions'Elab_Spec;
21898       end if;
21899       if not E014 then
21900          System.Exception_Table'Elab_Body;
21901          E014 := True;
21902       end if;
21903       if not E053 then
21904          Ada.Io_Exceptions'Elab_Spec;
21905          E053 := True;
21906       end if;
21907       if not E017 then
21908          System.Exceptions'Elab_Spec;
21909          E017 := True;
21910       end if;
21911       if not E030 then
21912          System.Stack_Checking'Elab_Spec;
21913       end if;
21914       if not E028 then
21915          System.Soft_Links'Elab_Body;
21916          E028 := True;
21917       end if;
21918       E030 := True;
21919       if not E024 then
21920          System.Secondary_Stack'Elab_Body;
21921          E024 := True;
21922       end if;
21923       if not E035 then
21924          Ada.Tags'Elab_Spec;
21925       end if;
21926       if not E035 then
21927          Ada.Tags'Elab_Body;
21928          E035 := True;
21929       end if;
21930       if not E033 then
21931          Ada.Streams'Elab_Spec;
21932          E033 := True;
21933       end if;
21934       if not E046 then
21935          System.Finalization_Root'Elab_Spec;
21936       end if;
21937       E046 := True;
21938       if not E008 then
21939          Ada.Exceptions'Elab_Body;
21940          E008 := True;
21941       end if;
21942       if not E048 then
21943          System.Finalization_Implementation'Elab_Spec;
21944       end if;
21945       if not E048 then
21946          System.Finalization_Implementation'Elab_Body;
21947          E048 := True;
21948       end if;
21949       if not E044 then
21950          Ada.Finalization'Elab_Spec;
21951       end if;
21952       E044 := True;
21953       if not E057 then
21954          Ada.Finalization.List_Controller'Elab_Spec;
21955       end if;
21956       E057 := True;
21957       if not E055 then
21958          System.File_Control_Block'Elab_Spec;
21959          E055 := True;
21960       end if;
21961       if not E042 then
21962          System.File_Io'Elab_Body;
21963          E042 := True;
21964       end if;
21965       if not E006 then
21966          Ada.Text_Io'Elab_Spec;
21967       end if;
21968       if not E006 then
21969          Ada.Text_Io'Elab_Body;
21970          E006 := True;
21971       end if;
21972
21973       Elab_Final_Code := 0;
21974    end adainit;
21975
21976    --------------
21977    -- adafinal --
21978    --------------
21979
21980 @findex adafinal
21981    procedure adafinal is
21982    begin
21983       Do_Finalize;
21984    end adafinal;
21985
21986    ----------
21987    -- main --
21988    ----------
21989
21990    --  main is actually a function, as in the ANSI C standard,
21991    --  defined to return the exit status. The three parameters
21992    --  are the argument count, argument values and environment
21993    --  pointer.
21994
21995 @findex Main Program
21996    function main
21997      (argc : Integer;
21998       argv : System.Address;
21999       envp : System.Address)
22000       return Integer
22001    is
22002       --  The initialize routine performs low level system
22003       --  initialization using a standard library routine which
22004       --  sets up signal handling and performs any other
22005       --  required setup. The routine can be found in file
22006       --  a-init.c.
22007
22008 @findex __gnat_initialize
22009       procedure initialize;
22010       pragma Import (C, initialize, "__gnat_initialize");
22011
22012       --  The finalize routine performs low level system
22013       --  finalization using a standard library routine. The
22014       --  routine is found in file a-final.c and in the standard
22015       --  distribution is a dummy routine that does nothing, so
22016       --  really this is a hook for special user finalization.
22017
22018 @findex __gnat_finalize
22019       procedure finalize;
22020       pragma Import (C, finalize, "__gnat_finalize");
22021
22022       --  We get to the main program of the partition by using
22023       --  pragma Import because if we try to with the unit and
22024       --  call it Ada style, then not only do we waste time
22025       --  recompiling it, but also, we don't really know the right
22026       --  switches (e.g. identifier character set) to be used
22027       --  to compile it.
22028
22029       procedure Ada_Main_Program;
22030       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22031
22032    --  Start of processing for main
22033
22034    begin
22035       --  Save global variables
22036
22037       gnat_argc := argc;
22038       gnat_argv := argv;
22039       gnat_envp := envp;
22040
22041       --  Call low level system initialization
22042
22043       Initialize;
22044
22045       --  Call our generated Ada initialization routine
22046
22047       adainit;
22048
22049       --  This is the point at which we want the debugger to get
22050       --  control
22051
22052       Break_Start;
22053
22054       --  Now we call the main program of the partition
22055
22056       Ada_Main_Program;
22057
22058       --  Perform Ada finalization
22059
22060       adafinal;
22061
22062       --  Perform low level system finalization
22063
22064       Finalize;
22065
22066       --  Return the proper exit status
22067       return (gnat_exit_status);
22068    end;
22069
22070 --  This section is entirely comments, so it has no effect on the
22071 --  compilation of the Ada_Main package. It provides the list of
22072 --  object files and linker options, as well as some standard
22073 --  libraries needed for the link. The gnatlink utility parses
22074 --  this b~hello.adb file to read these comment lines to generate
22075 --  the appropriate command line arguments for the call to the
22076 --  system linker. The BEGIN/END lines are used for sentinels for
22077 --  this parsing operation.
22078
22079 --  The exact file names will of course depend on the environment,
22080 --  host/target and location of files on the host system.
22081
22082 @findex Object file list
22083 -- BEGIN Object file/option list
22084    --   ./hello.o
22085    --   -L./
22086    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22087    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22088 -- END Object file/option list
22089
22090 end ada_main;
22091 @end smallexample
22092
22093 @noindent
22094 The Ada code in the above example is exactly what is generated by the
22095 binder. We have added comments to more clearly indicate the function
22096 of each part of the generated @code{Ada_Main} package.
22097
22098 The code is standard Ada in all respects, and can be processed by any
22099 tools that handle Ada. In particular, it is possible to use the debugger
22100 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22101 suppose that for reasons that you do not understand, your program is crashing
22102 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22103 you can place a breakpoint on the call:
22104
22105 @smallexample @c ada
22106 Ada.Text_Io'Elab_Body;
22107 @end smallexample
22108
22109 @noindent
22110 and trace the elaboration routine for this package to find out where
22111 the problem might be (more usually of course you would be debugging
22112 elaboration code in your own application).
22113
22114
22115 @node Elaboration Order Handling in GNAT
22116 @appendix Elaboration Order Handling in GNAT
22117 @cindex Order of elaboration
22118 @cindex Elaboration control
22119
22120 @menu
22121 * Elaboration Code in Ada 95::
22122 * Checking the Elaboration Order in Ada 95::
22123 * Controlling the Elaboration Order in Ada 95::
22124 * Controlling Elaboration in GNAT - Internal Calls::
22125 * Controlling Elaboration in GNAT - External Calls::
22126 * Default Behavior in GNAT - Ensuring Safety::
22127 * Treatment of Pragma Elaborate::
22128 * Elaboration Issues for Library Tasks::
22129 * Mixing Elaboration Models::
22130 * What to Do If the Default Elaboration Behavior Fails::
22131 * Elaboration for Access-to-Subprogram Values::
22132 * Summary of Procedures for Elaboration Control::
22133 * Other Elaboration Order Considerations::
22134 @end menu
22135
22136 @noindent
22137 This chapter describes the handling of elaboration code in Ada 95 and
22138 in GNAT, and discusses how the order of elaboration of program units can
22139 be controlled in GNAT, either automatically or with explicit programming
22140 features.
22141
22142 @node Elaboration Code in Ada 95
22143 @section Elaboration Code in Ada 95
22144
22145 @noindent
22146 Ada 95 provides rather general mechanisms for executing code at elaboration
22147 time, that is to say before the main program starts executing. Such code arises
22148 in three contexts:
22149
22150 @table @asis
22151 @item Initializers for variables.
22152 Variables declared at the library level, in package specs or bodies, can
22153 require initialization that is performed at elaboration time, as in:
22154 @smallexample @c ada
22155 @cartouche
22156 Sqrt_Half : Float := Sqrt (0.5);
22157 @end cartouche
22158 @end smallexample
22159
22160 @item Package initialization code
22161 Code in a @code{BEGIN-END} section at the outer level of a package body is
22162 executed as part of the package body elaboration code.
22163
22164 @item Library level task allocators
22165 Tasks that are declared using task allocators at the library level
22166 start executing immediately and hence can execute at elaboration time.
22167 @end table
22168
22169 @noindent
22170 Subprogram calls are possible in any of these contexts, which means that
22171 any arbitrary part of the program may be executed as part of the elaboration
22172 code. It is even possible to write a program which does all its work at
22173 elaboration time, with a null main program, although stylistically this
22174 would usually be considered an inappropriate way to structure
22175 a program.
22176
22177 An important concern arises in the context of elaboration code:
22178 we have to be sure that it is executed in an appropriate order. What we
22179 have is a series of elaboration code sections, potentially one section
22180 for each unit in the program. It is important that these execute
22181 in the correct order. Correctness here means that, taking the above
22182 example of the declaration of @code{Sqrt_Half},
22183 if some other piece of
22184 elaboration code references @code{Sqrt_Half},
22185 then it must run after the
22186 section of elaboration code that contains the declaration of
22187 @code{Sqrt_Half}.
22188
22189 There would never be any order of elaboration problem if we made a rule
22190 that whenever you @code{with} a unit, you must elaborate both the spec and body
22191 of that unit before elaborating the unit doing the @code{with}'ing:
22192
22193 @smallexample @c ada
22194 @group
22195 @cartouche
22196 with Unit_1;
22197 package Unit_2 is ...
22198 @end cartouche
22199 @end group
22200 @end smallexample
22201
22202 @noindent
22203 would require that both the body and spec of @code{Unit_1} be elaborated
22204 before the spec of @code{Unit_2}. However, a rule like that would be far too
22205 restrictive. In particular, it would make it impossible to have routines
22206 in separate packages that were mutually recursive.
22207
22208 You might think that a clever enough compiler could look at the actual
22209 elaboration code and determine an appropriate correct order of elaboration,
22210 but in the general case, this is not possible. Consider the following
22211 example.
22212
22213 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22214 that references
22215 the variable @code{Sqrt_1}, which is declared in the elaboration code
22216 of the body of @code{Unit_1}:
22217
22218 @smallexample @c ada
22219 @cartouche
22220 Sqrt_1 : Float := Sqrt (0.1);
22221 @end cartouche
22222 @end smallexample
22223
22224 @noindent
22225 The elaboration code of the body of @code{Unit_1} also contains:
22226
22227 @smallexample @c ada
22228 @group
22229 @cartouche
22230 if expression_1 = 1 then
22231    Q := Unit_2.Func_2;
22232 end if;
22233 @end cartouche
22234 @end group
22235 @end smallexample
22236
22237 @noindent
22238 @code{Unit_2} is exactly parallel,
22239 it has a procedure @code{Func_2} that references
22240 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22241 the body @code{Unit_2}:
22242
22243 @smallexample @c ada
22244 @cartouche
22245 Sqrt_2 : Float := Sqrt (0.1);
22246 @end cartouche
22247 @end smallexample
22248
22249 @noindent
22250 The elaboration code of the body of @code{Unit_2} also contains:
22251
22252 @smallexample @c ada
22253 @group
22254 @cartouche
22255 if expression_2 = 2 then
22256    Q := Unit_1.Func_1;
22257 end if;
22258 @end cartouche
22259 @end group
22260 @end smallexample
22261
22262 @noindent
22263 Now the question is, which of the following orders of elaboration is
22264 acceptable:
22265
22266 @smallexample
22267 @group
22268 Spec of Unit_1
22269 Spec of Unit_2
22270 Body of Unit_1
22271 Body of Unit_2
22272 @end group
22273 @end smallexample
22274
22275 @noindent
22276 or
22277
22278 @smallexample
22279 @group
22280 Spec of Unit_2
22281 Spec of Unit_1
22282 Body of Unit_2
22283 Body of Unit_1
22284 @end group
22285 @end smallexample
22286
22287 @noindent
22288 If you carefully analyze the flow here, you will see that you cannot tell
22289 at compile time the answer to this question.
22290 If @code{expression_1} is not equal to 1,
22291 and @code{expression_2} is not equal to 2,
22292 then either order is acceptable, because neither of the function calls is
22293 executed. If both tests evaluate to true, then neither order is acceptable
22294 and in fact there is no correct order.
22295
22296 If one of the two expressions is true, and the other is false, then one
22297 of the above orders is correct, and the other is incorrect. For example,
22298 if @code{expression_1} = 1 and @code{expression_2} /= 2,
22299 then the call to @code{Func_2}
22300 will occur, but not the call to @code{Func_1.}
22301 This means that it is essential
22302 to elaborate the body of @code{Unit_1} before
22303 the body of @code{Unit_2}, so the first
22304 order of elaboration is correct and the second is wrong.
22305
22306 By making @code{expression_1} and @code{expression_2}
22307 depend on input data, or perhaps
22308 the time of day, we can make it impossible for the compiler or binder
22309 to figure out which of these expressions will be true, and hence it
22310 is impossible to guarantee a safe order of elaboration at run time.
22311
22312 @node Checking the Elaboration Order in Ada 95
22313 @section Checking the Elaboration Order in Ada 95
22314
22315 @noindent
22316 In some languages that involve the same kind of elaboration problems,
22317 e.g. Java and C++, the programmer is expected to worry about these
22318 ordering problems himself, and it is common to
22319 write a program in which an incorrect elaboration order  gives
22320 surprising results, because it references variables before they
22321 are initialized.
22322 Ada 95 is designed to be a safe language, and a programmer-beware approach is
22323 clearly not sufficient. Consequently, the language provides three lines
22324 of defense:
22325
22326 @table @asis
22327 @item Standard rules
22328 Some standard rules restrict the possible choice of elaboration
22329 order. In particular, if you @code{with} a unit, then its spec is always
22330 elaborated before the unit doing the @code{with}. Similarly, a parent
22331 spec is always elaborated before the child spec, and finally
22332 a spec is always elaborated before its corresponding body.
22333
22334 @item Dynamic elaboration checks
22335 @cindex Elaboration checks
22336 @cindex Checks, elaboration
22337 Dynamic checks are made at run time, so that if some entity is accessed
22338 before it is elaborated (typically  by means of a subprogram call)
22339 then the exception (@code{Program_Error}) is raised.
22340
22341 @item Elaboration control
22342 Facilities are provided for the programmer to specify the desired order
22343 of elaboration.
22344 @end table
22345
22346 Let's look at these facilities in more detail. First, the rules for
22347 dynamic checking. One possible rule would be simply to say that the
22348 exception is raised if you access a variable which has not yet been
22349 elaborated. The trouble with this approach is that it could require
22350 expensive checks on every variable reference. Instead Ada 95 has two
22351 rules which are a little more restrictive, but easier to check, and
22352 easier to state:
22353
22354 @table @asis
22355 @item Restrictions on calls
22356 A subprogram can only be called at elaboration time if its body
22357 has been elaborated. The rules for elaboration given above guarantee
22358 that the spec of the subprogram has been elaborated before the
22359 call, but not the body. If this rule is violated, then the
22360 exception @code{Program_Error} is raised.
22361
22362 @item Restrictions on instantiations
22363 A generic unit can only be instantiated if the body of the generic
22364 unit has been elaborated. Again, the rules for elaboration given above
22365 guarantee that the spec of the generic unit has been elaborated
22366 before the instantiation, but not the body. If this rule is
22367 violated, then the exception @code{Program_Error} is raised.
22368 @end table
22369
22370 @noindent
22371 The idea is that if the body has been elaborated, then any variables
22372 it references must have been elaborated; by checking for the body being
22373 elaborated we guarantee that none of its references causes any
22374 trouble. As we noted above, this is a little too restrictive, because a
22375 subprogram that has no non-local references in its body may in fact be safe
22376 to call. However, it really would be unsafe to rely on this, because
22377 it would mean that the caller was aware of details of the implementation
22378 in the body. This goes against the basic tenets of Ada.
22379
22380 A plausible implementation can be described as follows.
22381 A Boolean variable is associated with each subprogram
22382 and each generic unit. This variable is initialized to False, and is set to
22383 True at the point body is elaborated. Every call or instantiation checks the
22384 variable, and raises @code{Program_Error} if the variable is False.
22385
22386 Note that one might think that it would be good enough to have one Boolean
22387 variable for each package, but that would not deal with cases of trying
22388 to call a body in the same package as the call
22389 that has not been elaborated yet.
22390 Of course a compiler may be able to do enough analysis to optimize away
22391 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
22392 does such optimizations, but still the easiest conceptual model is to
22393 think of there being one variable per subprogram.
22394
22395 @node Controlling the Elaboration Order in Ada 95
22396 @section Controlling the Elaboration Order in Ada 95
22397
22398 @noindent
22399 In the previous section we discussed the rules in Ada 95 which ensure
22400 that @code{Program_Error} is raised if an incorrect elaboration order is
22401 chosen. This prevents erroneous executions, but we need mechanisms to
22402 specify a correct execution and avoid the exception altogether.
22403 To achieve this, Ada 95 provides a number of features for controlling
22404 the order of elaboration. We discuss these features in this section.
22405
22406 First, there are several ways of indicating to the compiler that a given
22407 unit has no elaboration problems:
22408
22409 @table @asis
22410 @item packages that do not require a body
22411 In Ada 95, a library package that does not require a body does not permit
22412 a body. This means that if we have a such a package, as in:
22413
22414 @smallexample @c ada
22415 @group
22416 @cartouche
22417 package Definitions is
22418    generic
22419       type m is new integer;
22420    package Subp is
22421       type a is array (1 .. 10) of m;
22422       type b is array (1 .. 20) of m;
22423    end Subp;
22424 end Definitions;
22425 @end cartouche
22426 @end group
22427 @end smallexample
22428
22429 @noindent
22430 A package that @code{with}'s @code{Definitions} may safely instantiate
22431 @code{Definitions.Subp} because the compiler can determine that there
22432 definitely is no package body to worry about in this case
22433
22434 @item pragma Pure
22435 @cindex pragma Pure
22436 @findex Pure
22437 Places sufficient restrictions on a unit to guarantee that
22438 no call to any subprogram in the unit can result in an
22439 elaboration problem. This means that the compiler does not need
22440 to worry about the point of elaboration of such units, and in
22441 particular, does not need to check any calls to any subprograms
22442 in this unit.
22443
22444 @item pragma Preelaborate
22445 @findex Preelaborate
22446 @cindex pragma Preelaborate
22447 This pragma places slightly less stringent restrictions on a unit than
22448 does pragma Pure,
22449 but these restrictions are still sufficient to ensure that there
22450 are no elaboration problems with any calls to the unit.
22451
22452 @item pragma Elaborate_Body
22453 @findex Elaborate_Body
22454 @cindex pragma Elaborate_Body
22455 This pragma requires that the body of a unit be elaborated immediately
22456 after its spec. Suppose a unit @code{A} has such a pragma,
22457 and unit @code{B} does
22458 a @code{with} of unit @code{A}. Recall that the standard rules require
22459 the spec of unit @code{A}
22460 to be elaborated before the @code{with}'ing unit; given the pragma in
22461 @code{A}, we also know that the body of @code{A}
22462 will be elaborated before @code{B}, so
22463 that calls to @code{A} are safe and do not need a check.
22464 @end table
22465
22466 @noindent
22467 Note that,
22468 unlike pragma @code{Pure} and pragma @code{Preelaborate},
22469 the use of
22470 @code{Elaborate_Body} does not guarantee that the program is
22471 free of elaboration problems, because it may not be possible
22472 to satisfy the requested elaboration order.
22473 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
22474 If a programmer
22475 marks @code{Unit_1} as @code{Elaborate_Body},
22476 and not @code{Unit_2,} then the order of
22477 elaboration will be:
22478
22479 @smallexample
22480 @group
22481 Spec of Unit_2
22482 Spec of Unit_1
22483 Body of Unit_1
22484 Body of Unit_2
22485 @end group
22486 @end smallexample
22487
22488 @noindent
22489 Now that means that the call to @code{Func_1} in @code{Unit_2}
22490 need not be checked,
22491 it must be safe. But the call to @code{Func_2} in
22492 @code{Unit_1} may still fail if
22493 @code{Expression_1} is equal to 1,
22494 and the programmer must still take
22495 responsibility for this not being the case.
22496
22497 If all units carry a pragma @code{Elaborate_Body}, then all problems are
22498 eliminated, except for calls entirely within a body, which are
22499 in any case fully under programmer control. However, using the pragma
22500 everywhere is not always possible.
22501 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
22502 we marked both of them as having pragma @code{Elaborate_Body}, then
22503 clearly there would be no possible elaboration order.
22504
22505 The above pragmas allow a server to guarantee safe use by clients, and
22506 clearly this is the preferable approach. Consequently a good rule in
22507 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
22508 and if this is not possible,
22509 mark them as @code{Elaborate_Body} if possible.
22510 As we have seen, there are situations where neither of these
22511 three pragmas can be used.
22512 So we also provide methods for clients to control the
22513 order of elaboration of the servers on which they depend:
22514
22515 @table @asis
22516 @item pragma Elaborate (unit)
22517 @findex Elaborate
22518 @cindex pragma Elaborate
22519 This pragma is placed in the context clause, after a @code{with} clause,
22520 and it requires that the body of the named unit be elaborated before
22521 the unit in which the pragma occurs. The idea is to use this pragma
22522 if the current unit calls at elaboration time, directly or indirectly,
22523 some subprogram in the named unit.
22524
22525 @item pragma Elaborate_All (unit)
22526 @findex Elaborate_All
22527 @cindex pragma Elaborate_All
22528 This is a stronger version of the Elaborate pragma. Consider the
22529 following example:
22530
22531 @smallexample
22532 Unit A @code{with}'s unit B and calls B.Func in elab code
22533 Unit B @code{with}'s unit C, and B.Func calls C.Func
22534 @end smallexample
22535
22536 @noindent
22537 Now if we put a pragma @code{Elaborate (B)}
22538 in unit @code{A}, this ensures that the
22539 body of @code{B} is elaborated before the call, but not the
22540 body of @code{C}, so
22541 the call to @code{C.Func} could still cause @code{Program_Error} to
22542 be raised.
22543
22544 The effect of a pragma @code{Elaborate_All} is stronger, it requires
22545 not only that the body of the named unit be elaborated before the
22546 unit doing the @code{with}, but also the bodies of all units that the
22547 named unit uses, following @code{with} links transitively. For example,
22548 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
22549 then it requires
22550 not only that the body of @code{B} be elaborated before @code{A},
22551 but also the
22552 body of @code{C}, because @code{B} @code{with}'s @code{C}.
22553 @end table
22554
22555 @noindent
22556 We are now in a position to give a usage rule in Ada 95 for avoiding
22557 elaboration problems, at least if dynamic dispatching and access to
22558 subprogram values are not used. We will handle these cases separately
22559 later.
22560
22561 The rule is simple. If a unit has elaboration code that can directly or
22562 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
22563 a generic unit in a @code{with}'ed unit,
22564 then if the @code{with}'ed unit does not have
22565 pragma @code{Pure} or @code{Preelaborate}, then the client should have
22566 a pragma @code{Elaborate_All}
22567 for the @code{with}'ed unit. By following this rule a client is
22568 assured that calls can be made without risk of an exception.
22569 If this rule is not followed, then a program may be in one of four
22570 states:
22571
22572 @table @asis
22573 @item No order exists
22574 No order of elaboration exists which follows the rules, taking into
22575 account any @code{Elaborate}, @code{Elaborate_All},
22576 or @code{Elaborate_Body} pragmas. In
22577 this case, an Ada 95 compiler must diagnose the situation at bind
22578 time, and refuse to build an executable program.
22579
22580 @item One or more orders exist, all incorrect
22581 One or more acceptable elaboration orders exists, and all of them
22582 generate an elaboration order problem. In this case, the binder
22583 can build an executable program, but @code{Program_Error} will be raised
22584 when the program is run.
22585
22586 @item Several orders exist, some right, some incorrect
22587 One or more acceptable elaboration orders exists, and some of them
22588 work, and some do not. The programmer has not controlled
22589 the order of elaboration, so the binder may or may not pick one of
22590 the correct orders, and the program may or may not raise an
22591 exception when it is run. This is the worst case, because it means
22592 that the program may fail when moved to another compiler, or even
22593 another version of the same compiler.
22594
22595 @item One or more orders exists, all correct
22596 One ore more acceptable elaboration orders exist, and all of them
22597 work. In this case the program runs successfully. This state of
22598 affairs can be guaranteed by following the rule we gave above, but
22599 may be true even if the rule is not followed.
22600 @end table
22601
22602 @noindent
22603 Note that one additional advantage of following our Elaborate_All rule
22604 is that the program continues to stay in the ideal (all orders OK) state
22605 even if maintenance
22606 changes some bodies of some subprograms. Conversely, if a program that does
22607 not follow this rule happens to be safe at some point, this state of affairs
22608 may deteriorate silently as a result of maintenance changes.
22609
22610 You may have noticed that the above discussion did not mention
22611 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
22612 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
22613 code in the body makes calls to some other unit, so it is still necessary
22614 to use @code{Elaborate_All} on such units.
22615
22616 @node Controlling Elaboration in GNAT - Internal Calls
22617 @section Controlling Elaboration in GNAT - Internal Calls
22618
22619 @noindent
22620 In the case of internal calls, i.e. calls within a single package, the
22621 programmer has full control over the order of elaboration, and it is up
22622 to the programmer to elaborate declarations in an appropriate order. For
22623 example writing:
22624
22625 @smallexample @c ada
22626 @group
22627 @cartouche
22628 function One return Float;
22629
22630 Q : Float := One;
22631
22632 function One return Float is
22633 begin
22634      return 1.0;
22635 end One;
22636 @end cartouche
22637 @end group
22638 @end smallexample
22639
22640 @noindent
22641 will obviously raise @code{Program_Error} at run time, because function
22642 One will be called before its body is elaborated. In this case GNAT will
22643 generate a warning that the call will raise @code{Program_Error}:
22644
22645 @smallexample
22646 @group
22647 @cartouche
22648  1. procedure y is
22649  2.    function One return Float;
22650  3.
22651  4.    Q : Float := One;
22652                     |
22653     >>> warning: cannot call "One" before body is elaborated
22654     >>> warning: Program_Error will be raised at run time
22655
22656  5.
22657  6.    function One return Float is
22658  7.    begin
22659  8.         return 1.0;
22660  9.    end One;
22661 10.
22662 11. begin
22663 12.    null;
22664 13. end;
22665 @end cartouche
22666 @end group
22667 @end smallexample
22668
22669 @noindent
22670 Note that in this particular case, it is likely that the call is safe, because
22671 the function @code{One} does not access any global variables.
22672 Nevertheless in Ada 95, we do not want the validity of the check to depend on
22673 the contents of the body (think about the separate compilation case), so this
22674 is still wrong, as we discussed in the previous sections.
22675
22676 The error is easily corrected by rearranging the declarations so that the
22677 body of One appears before the declaration containing the call
22678 (note that in Ada 95,
22679 declarations can appear in any order, so there is no restriction that
22680 would prevent this reordering, and if we write:
22681
22682 @smallexample @c ada
22683 @group
22684 @cartouche
22685 function One return Float;
22686
22687 function One return Float is
22688 begin
22689      return 1.0;
22690 end One;
22691
22692 Q : Float := One;
22693 @end cartouche
22694 @end group
22695 @end smallexample
22696
22697 @noindent
22698 then all is well, no warning is generated, and no
22699 @code{Program_Error} exception
22700 will be raised.
22701 Things are more complicated when a chain of subprograms is executed:
22702
22703 @smallexample @c ada
22704 @group
22705 @cartouche
22706 function A return Integer;
22707 function B return Integer;
22708 function C return Integer;
22709
22710 function B return Integer is begin return A; end;
22711 function C return Integer is begin return B; end;
22712
22713 X : Integer := C;
22714
22715 function A return Integer is begin return 1; end;
22716 @end cartouche
22717 @end group
22718 @end smallexample
22719
22720 @noindent
22721 Now the call to @code{C}
22722 at elaboration time in the declaration of @code{X} is correct, because
22723 the body of @code{C} is already elaborated,
22724 and the call to @code{B} within the body of
22725 @code{C} is correct, but the call
22726 to @code{A} within the body of @code{B} is incorrect, because the body
22727 of @code{A} has not been elaborated, so @code{Program_Error}
22728 will be raised on the call to @code{A}.
22729 In this case GNAT will generate a
22730 warning that @code{Program_Error} may be
22731 raised at the point of the call. Let's look at the warning:
22732
22733 @smallexample
22734 @group
22735 @cartouche
22736  1. procedure x is
22737  2.    function A return Integer;
22738  3.    function B return Integer;
22739  4.    function C return Integer;
22740  5.
22741  6.    function B return Integer is begin return A; end;
22742                                                     |
22743     >>> warning: call to "A" before body is elaborated may
22744                  raise Program_Error
22745     >>> warning: "B" called at line 7
22746     >>> warning: "C" called at line 9
22747
22748  7.    function C return Integer is begin return B; end;
22749  8.
22750  9.    X : Integer := C;
22751 10.
22752 11.    function A return Integer is begin return 1; end;
22753 12.
22754 13. begin
22755 14.    null;
22756 15. end;
22757 @end cartouche
22758 @end group
22759 @end smallexample
22760
22761 @noindent
22762 Note that the message here says ``may raise'', instead of the direct case,
22763 where the message says ``will be raised''. That's because whether
22764 @code{A} is
22765 actually called depends in general on run-time flow of control.
22766 For example, if the body of @code{B} said
22767
22768 @smallexample @c ada
22769 @group
22770 @cartouche
22771 function B return Integer is
22772 begin
22773    if some-condition-depending-on-input-data then
22774       return A;
22775    else
22776       return 1;
22777    end if;
22778 end B;
22779 @end cartouche
22780 @end group
22781 @end smallexample
22782
22783 @noindent
22784 then we could not know until run time whether the incorrect call to A would
22785 actually occur, so @code{Program_Error} might
22786 or might not be raised. It is possible for a compiler to
22787 do a better job of analyzing bodies, to
22788 determine whether or not @code{Program_Error}
22789 might be raised, but it certainly
22790 couldn't do a perfect job (that would require solving the halting problem
22791 and is provably impossible), and because this is a warning anyway, it does
22792 not seem worth the effort to do the analysis. Cases in which it
22793 would be relevant are rare.
22794
22795 In practice, warnings of either of the forms given
22796 above will usually correspond to
22797 real errors, and should be examined carefully and eliminated.
22798 In the rare case where a warning is bogus, it can be suppressed by any of
22799 the following methods:
22800
22801 @itemize @bullet
22802 @item
22803 Compile with the @option{-gnatws} switch set
22804
22805 @item
22806 Suppress @code{Elaboration_Check} for the called subprogram
22807
22808 @item
22809 Use pragma @code{Warnings_Off} to turn warnings off for the call
22810 @end itemize
22811
22812 @noindent
22813 For the internal elaboration check case,
22814 GNAT by default generates the
22815 necessary run-time checks to ensure
22816 that @code{Program_Error} is raised if any
22817 call fails an elaboration check. Of course this can only happen if a
22818 warning has been issued as described above. The use of pragma
22819 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
22820 some of these checks, meaning that it may be possible (but is not
22821 guaranteed) for a program to be able to call a subprogram whose body
22822 is not yet elaborated, without raising a @code{Program_Error} exception.
22823
22824 @node Controlling Elaboration in GNAT - External Calls
22825 @section Controlling Elaboration in GNAT - External Calls
22826
22827 @noindent
22828 The previous section discussed the case in which the execution of a
22829 particular thread of elaboration code occurred entirely within a
22830 single unit. This is the easy case to handle, because a programmer
22831 has direct and total control over the order of elaboration, and
22832 furthermore, checks need only be generated in cases which are rare
22833 and which the compiler can easily detect.
22834 The situation is more complex when separate compilation is taken into account.
22835 Consider the following:
22836
22837 @smallexample @c ada
22838 @cartouche
22839 @group
22840 package Math is
22841    function Sqrt (Arg : Float) return Float;
22842 end Math;
22843
22844 package body Math is
22845    function Sqrt (Arg : Float) return Float is
22846    begin
22847          ...
22848    end Sqrt;
22849 end Math;
22850 @end group
22851 @group
22852 with Math;
22853 package Stuff is
22854    X : Float := Math.Sqrt (0.5);
22855 end Stuff;
22856
22857 with Stuff;
22858 procedure Main is
22859 begin
22860    ...
22861 end Main;
22862 @end group
22863 @end cartouche
22864 @end smallexample
22865
22866 @noindent
22867 where @code{Main} is the main program. When this program is executed, the
22868 elaboration code must first be executed, and one of the jobs of the
22869 binder is to determine the order in which the units of a program are
22870 to be elaborated. In this case we have four units: the spec and body
22871 of @code{Math},
22872 the spec of @code{Stuff} and the body of @code{Main}).
22873 In what order should the four separate sections of elaboration code
22874 be executed?
22875
22876 There are some restrictions in the order of elaboration that the binder
22877 can choose. In particular, if unit U has a @code{with}
22878 for a package @code{X}, then you
22879 are assured that the spec of @code{X}
22880 is elaborated before U , but you are
22881 not assured that the body of @code{X}
22882 is elaborated before U.
22883 This means that in the above case, the binder is allowed to choose the
22884 order:
22885
22886 @smallexample
22887 spec of Math
22888 spec of Stuff
22889 body of Math
22890 body of Main
22891 @end smallexample
22892
22893 @noindent
22894 but that's not good, because now the call to @code{Math.Sqrt}
22895 that happens during
22896 the elaboration of the @code{Stuff}
22897 spec happens before the body of @code{Math.Sqrt} is
22898 elaborated, and hence causes @code{Program_Error} exception to be raised.
22899 At first glance, one might say that the binder is misbehaving, because
22900 obviously you want to elaborate the body of something you @code{with}
22901 first, but
22902 that is not a general rule that can be followed in all cases. Consider
22903
22904 @smallexample @c ada
22905 @group
22906 @cartouche
22907 package X is ...
22908
22909 package Y is ...
22910
22911 with X;
22912 package body Y is ...
22913
22914 with Y;
22915 package body X is ...
22916 @end cartouche
22917 @end group
22918 @end smallexample
22919
22920 @noindent
22921 This is a common arrangement, and, apart from the order of elaboration
22922 problems that might arise in connection with elaboration code, this works fine.
22923 A rule that says that you must first elaborate the body of anything you
22924 @code{with} cannot work in this case:
22925 the body of @code{X} @code{with}'s @code{Y},
22926 which means you would have to
22927 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
22928 which means
22929 you have to elaborate the body of @code{X} first, but ... and we have a
22930 loop that cannot be broken.
22931
22932 It is true that the binder can in many cases guess an order of elaboration
22933 that is unlikely to cause a @code{Program_Error}
22934 exception to be raised, and it tries to do so (in the
22935 above example of @code{Math/Stuff/Spec}, the GNAT binder will
22936 by default
22937 elaborate the body of @code{Math} right after its spec, so all will be well).
22938
22939 However, a program that blindly relies on the binder to be helpful can
22940 get into trouble, as we discussed in the previous sections, so
22941 GNAT
22942 provides a number of facilities for assisting the programmer in
22943 developing programs that are robust with respect to elaboration order.
22944
22945 @node Default Behavior in GNAT - Ensuring Safety
22946 @section Default Behavior in GNAT - Ensuring Safety
22947
22948 @noindent
22949 The default behavior in GNAT ensures elaboration safety. In its
22950 default mode GNAT implements the
22951 rule we previously described as the right approach. Let's restate it:
22952
22953 @itemize
22954 @item
22955 @emph{If a unit has elaboration code that can directly or indirectly make a
22956 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
22957 in a @code{with}'ed unit, then if the @code{with}'ed unit
22958 does not have pragma @code{Pure} or
22959 @code{Preelaborate}, then the client should have an
22960 @code{Elaborate_All} for the @code{with}'ed unit.}
22961 @end itemize
22962
22963 @noindent
22964 By following this rule a client is assured that calls and instantiations
22965 can be made without risk of an exception.
22966
22967 In this mode GNAT traces all calls that are potentially made from
22968 elaboration code, and puts in any missing implicit @code{Elaborate_All}
22969 pragmas.
22970 The advantage of this approach is that no elaboration problems
22971 are possible if the binder can find an elaboration order that is
22972 consistent with these implicit @code{Elaborate_All} pragmas. The
22973 disadvantage of this approach is that no such order may exist.
22974
22975 If the binder does not generate any diagnostics, then it means that it
22976 has found an elaboration order that is guaranteed to be safe. However,
22977 the binder may still be relying on implicitly generated
22978 @code{Elaborate_All} pragmas so portability to other compilers than
22979 GNAT is not guaranteed.
22980
22981 If it is important to guarantee portability, then the compilations should
22982 use the
22983 @option{-gnatwl}
22984 (warn on elaboration problems) switch. This will cause warning messages
22985 to be generated indicating the missing @code{Elaborate_All} pragmas.
22986 Consider the following source program:
22987
22988 @smallexample @c ada
22989 @group
22990 @cartouche
22991 with k;
22992 package j is
22993   m : integer := k.r;
22994 end;
22995 @end cartouche
22996 @end group
22997 @end smallexample
22998
22999 @noindent
23000 where it is clear that there
23001 should be a pragma @code{Elaborate_All}
23002 for unit @code{k}. An implicit pragma will be generated, and it is
23003 likely that the binder will be able to honor it. However, if you want
23004 to port this program to some other Ada compiler than GNAT.
23005 it is safer to include the pragma explicitly in the source. If this
23006 unit is compiled with the
23007 @option{-gnatwl}
23008 switch, then the compiler outputs a warning:
23009
23010 @smallexample
23011 @group
23012 @cartouche
23013 1. with k;
23014 2. package j is
23015 3.   m : integer := k.r;
23016                      |
23017    >>> warning: call to "r" may raise Program_Error
23018    >>> warning: missing pragma Elaborate_All for "k"
23019
23020 4. end;
23021 @end cartouche
23022 @end group
23023 @end smallexample
23024
23025 @noindent
23026 and these warnings can be used as a guide for supplying manually
23027 the missing pragmas. It is usually a bad idea to use this warning
23028 option during development. That's because it will warn you when
23029 you need to put in a pragma, but cannot warn you when it is time
23030 to take it out. So the use of pragma Elaborate_All may lead to
23031 unnecessary dependencies and even false circularities.
23032
23033 This default mode is more restrictive than the Ada Reference
23034 Manual, and it is possible to construct programs which will compile
23035 using the dynamic model described there, but will run into a
23036 circularity using the safer static model we have described.
23037
23038 Of course any Ada compiler must be able to operate in a mode
23039 consistent with the requirements of the Ada Reference Manual,
23040 and in particular must have the capability of implementing the
23041 standard dynamic model of elaboration with run-time checks.
23042
23043 In GNAT, this standard mode can be achieved either by the use of
23044 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
23045 command, or by the use of the configuration pragma:
23046
23047 @smallexample @c ada
23048 pragma Elaboration_Checks (RM);
23049 @end smallexample
23050
23051 @noindent
23052 Either approach will cause the unit affected to be compiled using the
23053 standard dynamic run-time elaboration checks described in the Ada
23054 Reference Manual. The static model is generally preferable, since it
23055 is clearly safer to rely on compile and link time checks rather than
23056 run-time checks. However, in the case of legacy code, it may be
23057 difficult to meet the requirements of the static model. This
23058 issue is further discussed in
23059 @ref{What to Do If the Default Elaboration Behavior Fails}.
23060
23061 Note that the static model provides a strict subset of the allowed
23062 behavior and programs of the Ada Reference Manual, so if you do
23063 adhere to the static model and no circularities exist,
23064 then you are assured that your program will
23065 work using the dynamic model, providing that you remove any
23066 pragma Elaborate statements from the source.
23067
23068 @node Treatment of Pragma Elaborate
23069 @section Treatment of Pragma Elaborate
23070 @cindex Pragma Elaborate
23071
23072 @noindent
23073 The use of @code{pragma Elaborate}
23074 should generally be avoided in Ada 95 programs.
23075 The reason for this is that there is no guarantee that transitive calls
23076 will be properly handled. Indeed at one point, this pragma was placed
23077 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23078
23079 Now that's a bit restrictive. In practice, the case in which
23080 @code{pragma Elaborate} is useful is when the caller knows that there
23081 are no transitive calls, or that the called unit contains all necessary
23082 transitive @code{pragma Elaborate} statements, and legacy code often
23083 contains such uses.
23084
23085 Strictly speaking the static mode in GNAT should ignore such pragmas,
23086 since there is no assurance at compile time that the necessary safety
23087 conditions are met. In practice, this would cause GNAT to be incompatible
23088 with correctly written Ada 83 code that had all necessary
23089 @code{pragma Elaborate} statements in place. Consequently, we made the
23090 decision that GNAT in its default mode will believe that if it encounters
23091 a @code{pragma Elaborate} then the programmer knows what they are doing,
23092 and it will trust that no elaboration errors can occur.
23093
23094 The result of this decision is two-fold. First to be safe using the
23095 static mode, you should remove all @code{pragma Elaborate} statements.
23096 Second, when fixing circularities in existing code, you can selectively
23097 use @code{pragma Elaborate} statements to convince the static mode of
23098 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23099 statement.
23100
23101 When using the static mode with @option{-gnatwl}, any use of
23102 @code{pragma Elaborate} will generate a warning about possible
23103 problems.
23104
23105 @node Elaboration Issues for Library Tasks
23106 @section Elaboration Issues for Library Tasks
23107 @cindex Library tasks, elaboration issues
23108 @cindex Elaboration of library tasks
23109
23110 @noindent
23111 In this section we examine special elaboration issues that arise for
23112 programs that declare library level tasks.
23113
23114 Generally the model of execution of an Ada program is that all units are
23115 elaborated, and then execution of the program starts. However, the
23116 declaration of library tasks definitely does not fit this model. The
23117 reason for this is that library tasks start as soon as they are declared
23118 (more precisely, as soon as the statement part of the enclosing package
23119 body is reached), that is to say before elaboration
23120 of the program is complete. This means that if such a task calls a
23121 subprogram, or an entry in another task, the callee may or may not be
23122 elaborated yet, and in the standard
23123 Reference Manual model of dynamic elaboration checks, you can even
23124 get timing dependent Program_Error exceptions, since there can be
23125 a race between the elaboration code and the task code.
23126
23127 The static model of elaboration in GNAT seeks to avoid all such
23128 dynamic behavior, by being conservative, and the conservative
23129 approach in this particular case is to assume that all the code
23130 in a task body is potentially executed at elaboration time if
23131 a task is declared at the library level.
23132
23133 This can definitely result in unexpected circularities. Consider
23134 the following example
23135
23136 @smallexample @c ada
23137 package Decls is
23138   task Lib_Task is
23139      entry Start;
23140   end Lib_Task;
23141
23142   type My_Int is new Integer;
23143
23144   function Ident (M : My_Int) return My_Int;
23145 end Decls;
23146
23147 with Utils;
23148 package body Decls is
23149   task body Lib_Task is
23150   begin
23151      accept Start;
23152      Utils.Put_Val (2);
23153   end Lib_Task;
23154
23155   function Ident (M : My_Int) return My_Int is
23156   begin
23157      return M;
23158   end Ident;
23159 end Decls;
23160
23161 with Decls;
23162 package Utils is
23163   procedure Put_Val (Arg : Decls.My_Int);
23164 end Utils;
23165
23166 with Text_IO;
23167 package body Utils is
23168   procedure Put_Val (Arg : Decls.My_Int) is
23169   begin
23170      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23171   end Put_Val;
23172 end Utils;
23173
23174 with Decls;
23175 procedure Main is
23176 begin
23177    Decls.Lib_Task.Start;
23178 end;
23179 @end smallexample
23180
23181 @noindent
23182 If the above example is compiled in the default static elaboration
23183 mode, then a circularity occurs. The circularity comes from the call
23184 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23185 this call occurs in elaboration code, we need an implicit pragma
23186 @code{Elaborate_All} for @code{Utils}. This means that not only must
23187 the spec and body of @code{Utils} be elaborated before the body
23188 of @code{Decls}, but also the spec and body of any unit that is
23189 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23190 the body of @code{Decls}. This is the transitive implication of
23191 pragma @code{Elaborate_All} and it makes sense, because in general
23192 the body of @code{Put_Val} might have a call to something in a
23193 @code{with'ed} unit.
23194
23195 In this case, the body of Utils (actually its spec) @code{with's}
23196 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23197 must be elaborated before itself, in case there is a call from the
23198 body of @code{Utils}.
23199
23200 Here is the exact chain of events we are worrying about:
23201
23202 @enumerate
23203 @item
23204 In the body of @code{Decls} a call is made from within the body of a library
23205 task to a subprogram in the package @code{Utils}. Since this call may
23206 occur at elaboration time (given that the task is activated at elaboration
23207 time), we have to assume the worst, i.e. that the
23208 call does happen at elaboration time.
23209
23210 @item
23211 This means that the body and spec of @code{Util} must be elaborated before
23212 the body of @code{Decls} so that this call does not cause an access before
23213 elaboration.
23214
23215 @item
23216 Within the body of @code{Util}, specifically within the body of
23217 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23218 by this package.
23219
23220 @item
23221 One such @code{with}'ed package is package @code{Decls}, so there
23222 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23223 In fact there is such a call in this example, but we would have to
23224 assume that there was such a call even if it were not there, since
23225 we are not supposed to write the body of @code{Decls} knowing what
23226 is in the body of @code{Utils}; certainly in the case of the
23227 static elaboration model, the compiler does not know what is in
23228 other bodies and must assume the worst.
23229
23230 @item
23231 This means that the spec and body of @code{Decls} must also be
23232 elaborated before we elaborate the unit containing the call, but
23233 that unit is @code{Decls}! This means that the body of @code{Decls}
23234 must be elaborated before itself, and that's a circularity.
23235 @end enumerate
23236
23237 @noindent
23238 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
23239 the body of @code{Decls} you will get a true Ada Reference Manual
23240 circularity that makes the program illegal.
23241
23242 In practice, we have found that problems with the static model of
23243 elaboration in existing code often arise from library tasks, so
23244 we must address this particular situation.
23245
23246 Note that if we compile and run the program above, using the dynamic model of
23247 elaboration (that is to say use the @option{-gnatE} switch),
23248 then it compiles, binds,
23249 links, and runs, printing the expected result of 2. Therefore in some sense
23250 the circularity here is only apparent, and we need to capture
23251 the properties of this program that  distinguish it from other library-level
23252 tasks that have real elaboration problems.
23253
23254 We have four possible answers to this question:
23255
23256 @itemize @bullet
23257
23258 @item
23259 Use the dynamic model of elaboration.
23260
23261 If we use the @option{-gnatE} switch, then as noted above, the program works.
23262 Why is this? If we examine the task body, it is apparent that the task cannot
23263 proceed past the
23264 @code{accept} statement until after elaboration has been completed, because
23265 the corresponding entry call comes from the main program, not earlier.
23266 This is why the dynamic model works here. But that's really giving
23267 up on a precise analysis, and we prefer to take this approach only if we cannot
23268 solve the
23269 problem in any other manner. So let us examine two ways to reorganize
23270 the program to avoid the potential elaboration problem.
23271
23272 @item
23273 Split library tasks into separate packages.
23274
23275 Write separate packages, so that library tasks are isolated from
23276 other declarations as much as possible. Let us look at a variation on
23277 the above program.
23278
23279 @smallexample @c ada
23280 package Decls1 is
23281   task Lib_Task is
23282      entry Start;
23283   end Lib_Task;
23284 end Decls1;
23285
23286 with Utils;
23287 package body Decls1 is
23288   task body Lib_Task is
23289   begin
23290      accept Start;
23291      Utils.Put_Val (2);
23292   end Lib_Task;
23293 end Decls1;
23294
23295 package Decls2 is
23296   type My_Int is new Integer;
23297   function Ident (M : My_Int) return My_Int;
23298 end Decls2;
23299
23300 with Utils;
23301 package body Decls2 is
23302   function Ident (M : My_Int) return My_Int is
23303   begin
23304      return M;
23305   end Ident;
23306 end Decls2;
23307
23308 with Decls2;
23309 package Utils is
23310   procedure Put_Val (Arg : Decls2.My_Int);
23311 end Utils;
23312
23313 with Text_IO;
23314 package body Utils is
23315   procedure Put_Val (Arg : Decls2.My_Int) is
23316   begin
23317      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23318   end Put_Val;
23319 end Utils;
23320
23321 with Decls1;
23322 procedure Main is
23323 begin
23324    Decls1.Lib_Task.Start;
23325 end;
23326 @end smallexample
23327
23328 @noindent
23329 All we have done is to split @code{Decls} into two packages, one
23330 containing the library task, and one containing everything else. Now
23331 there is no cycle, and the program compiles, binds, links and executes
23332 using the default static model of elaboration.
23333
23334 @item
23335 Declare separate task types.
23336
23337 A significant part of the problem arises because of the use of the
23338 single task declaration form. This means that the elaboration of
23339 the task type, and the elaboration of the task itself (i.e. the
23340 creation of the task) happen at the same time. A good rule
23341 of style in Ada 95 is to always create explicit task types. By
23342 following the additional step of placing task objects in separate
23343 packages from the task type declaration, many elaboration problems
23344 are avoided. Here is another modified example of the example program:
23345
23346 @smallexample @c ada
23347 package Decls is
23348   task type Lib_Task_Type is
23349      entry Start;
23350   end Lib_Task_Type;
23351
23352   type My_Int is new Integer;
23353
23354   function Ident (M : My_Int) return My_Int;
23355 end Decls;
23356
23357 with Utils;
23358 package body Decls is
23359   task body Lib_Task_Type is
23360   begin
23361      accept Start;
23362      Utils.Put_Val (2);
23363   end Lib_Task_Type;
23364
23365   function Ident (M : My_Int) return My_Int is
23366   begin
23367      return M;
23368   end Ident;
23369 end Decls;
23370
23371 with Decls;
23372 package Utils is
23373   procedure Put_Val (Arg : Decls.My_Int);
23374 end Utils;
23375
23376 with Text_IO;
23377 package body Utils is
23378   procedure Put_Val (Arg : Decls.My_Int) is
23379   begin
23380      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23381   end Put_Val;
23382 end Utils;
23383
23384 with Decls;
23385 package Declst is
23386    Lib_Task : Decls.Lib_Task_Type;
23387 end Declst;
23388
23389 with Declst;
23390 procedure Main is
23391 begin
23392    Declst.Lib_Task.Start;
23393 end;
23394 @end smallexample
23395
23396 @noindent
23397 What we have done here is to replace the @code{task} declaration in
23398 package @code{Decls} with a @code{task type} declaration. Then we
23399 introduce a separate package @code{Declst} to contain the actual
23400 task object. This separates the elaboration issues for
23401 the @code{task type}
23402 declaration, which causes no trouble, from the elaboration issues
23403 of the task object, which is also unproblematic, since it is now independent
23404 of the elaboration of  @code{Utils}.
23405 This separation of concerns also corresponds to
23406 a generally sound engineering principle of separating declarations
23407 from instances. This version of the program also compiles, binds, links,
23408 and executes, generating the expected output.
23409
23410 @item
23411 Use No_Entry_Calls_In_Elaboration_Code restriction.
23412 @cindex No_Entry_Calls_In_Elaboration_Code
23413
23414 The previous two approaches described how a program can be restructured
23415 to avoid the special problems caused by library task bodies. in practice,
23416 however, such restructuring may be difficult to apply to existing legacy code,
23417 so we must consider solutions that do not require massive rewriting.
23418
23419 Let us consider more carefully why our original sample program works
23420 under the dynamic model of elaboration. The reason is that the code
23421 in the task body blocks immediately on the @code{accept}
23422 statement. Now of course there is nothing to prohibit elaboration
23423 code from making entry calls (for example from another library level task),
23424 so we cannot tell in isolation that
23425 the task will not execute the accept statement  during elaboration.
23426
23427 However, in practice it is very unusual to see elaboration code
23428 make any entry calls, and the pattern of tasks starting
23429 at elaboration time and then immediately blocking on @code{accept} or
23430 @code{select} statements is very common. What this means is that
23431 the compiler is being too pessimistic when it analyzes the
23432 whole package body as though it might be executed at elaboration
23433 time.
23434
23435 If we know that the elaboration code contains no entry calls, (a very safe
23436 assumption most of the time, that could almost be made the default
23437 behavior), then we can compile all units of the program under control
23438 of the following configuration pragma:
23439
23440 @smallexample
23441 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
23442 @end smallexample
23443
23444 @noindent
23445 This pragma can be placed in the @file{gnat.adc} file in the usual
23446 manner. If we take our original unmodified program and compile it
23447 in the presence of a @file{gnat.adc} containing the above pragma,
23448 then once again, we can compile, bind, link, and execute, obtaining
23449 the expected result. In the presence of this pragma, the compiler does
23450 not trace calls in a task body, that appear after the first @code{accept}
23451 or @code{select} statement, and therefore does not report a potential
23452 circularity in the original program.
23453
23454 The compiler will check to the extent it can that the above
23455 restriction is not violated, but it is not always possible to do a
23456 complete check at compile time, so it is important to use this
23457 pragma only if the stated restriction is in fact met, that is to say
23458 no task receives an entry call before elaboration of all units is completed.
23459
23460 @end itemize
23461
23462 @node Mixing Elaboration Models
23463 @section Mixing Elaboration Models
23464 @noindent
23465 So far, we have assumed that the entire program is either compiled
23466 using the dynamic model or static model, ensuring consistency. It
23467 is possible to mix the two models, but rules have to be followed
23468 if this mixing is done to ensure that elaboration checks are not
23469 omitted.
23470
23471 The basic rule is that @emph{a unit compiled with the static model cannot
23472 be @code{with'ed} by a unit compiled with the dynamic model}. The
23473 reason for this is that in the static model, a unit assumes that
23474 its clients guarantee to use (the equivalent of) pragma
23475 @code{Elaborate_All} so that no elaboration checks are required
23476 in inner subprograms, and this assumption is violated if the
23477 client is compiled with dynamic checks.
23478
23479 The precise rule is as follows. A unit that is compiled with dynamic
23480 checks can only @code{with} a unit that meets at least one of the
23481 following criteria:
23482
23483 @itemize @bullet
23484
23485 @item
23486 The @code{with'ed} unit is itself compiled with dynamic elaboration
23487 checks (that is with the @option{-gnatE} switch.
23488
23489 @item
23490 The @code{with'ed} unit is an internal GNAT implementation unit from
23491 the System, Interfaces, Ada, or GNAT hierarchies.
23492
23493 @item
23494 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
23495
23496 @item
23497 The @code{with'ing} unit (that is the client) has an explicit pragma
23498 @code{Elaborate_All} for the @code{with'ed} unit.
23499
23500 @end itemize
23501
23502 @noindent
23503 If this rule is violated, that is if a unit with dynamic elaboration
23504 checks @code{with's} a unit that does not meet one of the above four
23505 criteria, then the binder (@code{gnatbind}) will issue a warning
23506 similar to that in the following example:
23507
23508 @smallexample
23509 warning: "x.ads" has dynamic elaboration checks and with's
23510 warning:   "y.ads" which has static elaboration checks
23511 @end smallexample
23512
23513 @noindent
23514 These warnings indicate that the rule has been violated, and that as a result
23515 elaboration checks may be missed in the resulting executable file.
23516 This warning may be suppressed using the @option{-ws} binder switch
23517 in the usual manner.
23518
23519 One useful application of this mixing rule is in the case of a subsystem
23520 which does not itself @code{with} units from the remainder of the
23521 application. In this case, the entire subsystem can be compiled with
23522 dynamic checks to resolve a circularity in the subsystem, while
23523 allowing the main application that uses this subsystem to be compiled
23524 using the more reliable default static model.
23525
23526 @node What to Do If the Default Elaboration Behavior Fails
23527 @section What to Do If the Default Elaboration Behavior Fails
23528
23529 @noindent
23530 If the binder cannot find an acceptable order, it outputs detailed
23531 diagnostics. For example:
23532 @smallexample
23533 @group
23534 @iftex
23535 @leftskip=0cm
23536 @end iftex
23537 error: elaboration circularity detected
23538 info:   "proc (body)" must be elaborated before "pack (body)"
23539 info:     reason: Elaborate_All probably needed in unit "pack (body)"
23540 info:     recompile "pack (body)" with -gnatwl
23541 info:                             for full details
23542 info:       "proc (body)"
23543 info:         is needed by its spec:
23544 info:       "proc (spec)"
23545 info:         which is withed by:
23546 info:       "pack (body)"
23547 info:  "pack (body)" must be elaborated before "proc (body)"
23548 info:     reason: pragma Elaborate in unit "proc (body)"
23549 @end group
23550
23551 @end smallexample
23552
23553 @noindent
23554 In this case we have a cycle that the binder cannot break. On the one
23555 hand, there is an explicit pragma Elaborate in @code{proc} for
23556 @code{pack}. This means that the body of @code{pack} must be elaborated
23557 before the body of @code{proc}. On the other hand, there is elaboration
23558 code in @code{pack} that calls a subprogram in @code{proc}. This means
23559 that for maximum safety, there should really be a pragma
23560 Elaborate_All in @code{pack} for @code{proc} which would require that
23561 the body of @code{proc} be elaborated before the body of
23562 @code{pack}. Clearly both requirements cannot be satisfied.
23563 Faced with a circularity of this kind, you have three different options.
23564
23565 @table @asis
23566 @item Fix the program
23567 The most desirable option from the point of view of long-term maintenance
23568 is to rearrange the program so that the elaboration problems are avoided.
23569 One useful technique is to place the elaboration code into separate
23570 child packages. Another is to move some of the initialization code to
23571 explicitly called subprograms, where the program controls the order
23572 of initialization explicitly. Although this is the most desirable option,
23573 it may be impractical and involve too much modification, especially in
23574 the case of complex legacy code.
23575
23576 @item Perform dynamic checks
23577 If the compilations are done using the
23578 @option{-gnatE}
23579 (dynamic elaboration check) switch, then GNAT behaves in
23580 a quite different manner. Dynamic checks are generated for all calls
23581 that could possibly result in raising an exception. With this switch,
23582 the compiler does not generate implicit @code{Elaborate_All} pragmas.
23583 The behavior then is exactly as specified in the Ada 95 Reference Manual.
23584 The binder will generate an executable program that may or may not
23585 raise @code{Program_Error}, and then it is the programmer's job to ensure
23586 that it does not raise an exception. Note that it is important to
23587 compile all units with the switch, it cannot be used selectively.
23588
23589 @item Suppress checks
23590 The drawback of dynamic checks is that they generate a
23591 significant overhead at run time, both in space and time. If you
23592 are absolutely sure that your program cannot raise any elaboration
23593 exceptions, and you still want to use the dynamic elaboration model,
23594 then you can use the configuration pragma
23595 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
23596 example this pragma could be placed in the @file{gnat.adc} file.
23597
23598 @item Suppress checks selectively
23599 When you know that certain calls in elaboration code cannot possibly
23600 lead to an elaboration error, and the binder nevertheless generates warnings
23601 on those calls and inserts Elaborate_All pragmas that lead to elaboration
23602 circularities, it is possible to remove those warnings locally and obtain
23603 a program that will bind. Clearly this can be unsafe, and it is the
23604 responsibility of the programmer to make sure that the resulting program has
23605 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
23606 be used with different granularity to suppress warnings and break
23607 elaboration circularities:
23608
23609 @itemize @bullet
23610 @item
23611 Place the pragma that names the called subprogram in the declarative part
23612 that contains the call.
23613
23614 @item
23615 Place the pragma in the declarative part, without naming an entity. This
23616 disables warnings on all calls in the corresponding  declarative region.
23617
23618 @item
23619 Place the pragma in the package spec that declares the called subprogram,
23620 and name the subprogram. This disables warnings on all elaboration calls to
23621 that subprogram.
23622
23623 @item
23624 Place the pragma in the package spec that declares the called subprogram,
23625 without naming any entity. This disables warnings on all elaboration calls to
23626 all subprograms declared in this spec.
23627
23628 @item Use Pragma Elaborate
23629 As previously described in section @xref{Treatment of Pragma Elaborate},
23630 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
23631 that no elaboration checks are required on calls to the designated unit.
23632 There may be cases in which the caller knows that no transitive calls
23633 can occur, so that a @code{pragma Elaborate} will be sufficient in a
23634 case where @code{pragma Elaborate_All} would cause a circularity.
23635 @end itemize
23636
23637 @noindent
23638 These five cases are listed in order of decreasing safety, and therefore
23639 require increasing programmer care in their application. Consider the
23640 following program:
23641
23642 @smallexample @c adanocomment
23643 package Pack1 is
23644   function F1 return Integer;
23645   X1 : Integer;
23646 end Pack1;
23647
23648 package Pack2 is
23649   function F2 return Integer;
23650   function Pure (x : integer) return integer;
23651   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
23652   --  pragma Suppress (Elaboration_Check);              -- (4)
23653 end Pack2;
23654
23655 with Pack2;
23656 package body Pack1 is
23657   function F1 return Integer is
23658   begin
23659     return 100;
23660   end F1;
23661   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
23662 begin
23663   declare
23664     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
23665     --  pragma Suppress(Elaboration_Check);             -- (2)
23666   begin
23667     X1 := Pack2.F2 + 1;                --  Elab. call (2)
23668   end;
23669 end Pack1;
23670
23671 with Pack1;
23672 package body Pack2 is
23673   function F2 return Integer is
23674   begin
23675      return Pack1.F1;
23676   end F2;
23677   function Pure (x : integer) return integer is
23678   begin
23679      return x ** 3 - 3 * x;
23680   end;
23681 end Pack2;
23682
23683 with Pack1, Ada.Text_IO;
23684 procedure Proc3 is
23685 begin
23686   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
23687 end Proc3;
23688 @end smallexample
23689 In the absence of any pragmas, an attempt to bind this program produces
23690 the following diagnostics:
23691 @smallexample
23692 @group
23693 @iftex
23694 @leftskip=.5cm
23695 @end iftex
23696 error: elaboration circularity detected
23697 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
23698 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
23699 info:       recompile "pack1 (body)" with -gnatwl for full details
23700 info:          "pack1 (body)"
23701 info:             must be elaborated along with its spec:
23702 info:          "pack1 (spec)"
23703 info:             which is withed by:
23704 info:          "pack2 (body)"
23705 info:             which must be elaborated along with its spec:
23706 info:          "pack2 (spec)"
23707 info:             which is withed by:
23708 info:          "pack1 (body)"
23709 @end group
23710 @end smallexample
23711 The sources of the circularity are the two calls to @code{Pack2.Pure} and
23712 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
23713 F2 is safe, even though F2 calls F1, because the call appears after the
23714 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
23715 remove the warning on the call. It is also possible to use pragma (2)
23716 because there are no other potentially unsafe calls in the block.
23717
23718 @noindent
23719 The call to @code{Pure} is safe because this function does not depend on the
23720 state of @code{Pack2}. Therefore any call to this function is safe, and it
23721 is correct to place pragma (3) in the corresponding package spec.
23722
23723 @noindent
23724 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
23725 warnings on all calls to functions declared therein. Note that this is not
23726 necessarily safe, and requires more detailed examination of the subprogram
23727 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
23728 be already elaborated.
23729 @end table
23730
23731 @noindent
23732 It is hard to generalize on which of these four approaches should be
23733 taken. Obviously if it is possible to fix the program so that the default
23734 treatment works, this is preferable, but this may not always be practical.
23735 It is certainly simple enough to use
23736 @option{-gnatE}
23737 but the danger in this case is that, even if the GNAT binder
23738 finds a correct elaboration order, it may not always do so,
23739 and certainly a binder from another Ada compiler might not. A
23740 combination of testing and analysis (for which the warnings generated
23741 with the
23742 @option{-gnatwl}
23743 switch can be useful) must be used to ensure that the program is free
23744 of errors. One switch that is useful in this testing is the
23745 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
23746 switch for
23747 @code{gnatbind}.
23748 Normally the binder tries to find an order that has the best chance of
23749 of avoiding elaboration problems. With this switch, the binder
23750 plays a devil's advocate role, and tries to choose the order that
23751 has the best chance of failing. If your program works even with this
23752 switch, then it has a better chance of being error free, but this is still
23753 not a guarantee.
23754
23755 For an example of this approach in action, consider the C-tests (executable
23756 tests) from the ACVC suite. If these are compiled and run with the default
23757 treatment, then all but one of them succeed without generating any error
23758 diagnostics from the binder. However, there is one test that fails, and
23759 this is not surprising, because the whole point of this test is to ensure
23760 that the compiler can handle cases where it is impossible to determine
23761 a correct order statically, and it checks that an exception is indeed
23762 raised at run time.
23763
23764 This one test must be compiled and run using the
23765 @option{-gnatE}
23766 switch, and then it passes. Alternatively, the entire suite can
23767 be run using this switch. It is never wrong to run with the dynamic
23768 elaboration switch if your code is correct, and we assume that the
23769 C-tests are indeed correct (it is less efficient, but efficiency is
23770 not a factor in running the ACVC tests.)
23771
23772 @node Elaboration for Access-to-Subprogram Values
23773 @section Elaboration for Access-to-Subprogram Values
23774 @cindex Access-to-subprogram
23775
23776 @noindent
23777 The introduction of access-to-subprogram types in Ada 95 complicates
23778 the handling of elaboration. The trouble is that it becomes
23779 impossible to tell at compile time which procedure
23780 is being called. This means that it is not possible for the binder
23781 to analyze the elaboration requirements in this case.
23782
23783 If at the point at which the access value is created
23784 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
23785 the body of the subprogram is
23786 known to have been elaborated, then the access value is safe, and its use
23787 does not require a check. This may be achieved by appropriate arrangement
23788 of the order of declarations if the subprogram is in the current unit,
23789 or, if the subprogram is in another unit, by using pragma
23790 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
23791 on the referenced unit.
23792
23793 If the referenced body is not known to have been elaborated at the point
23794 the access value is created, then any use of the access value must do a
23795 dynamic check, and this dynamic check will fail and raise a
23796 @code{Program_Error} exception if the body has not been elaborated yet.
23797 GNAT will generate the necessary checks, and in addition, if the
23798 @option{-gnatwl}
23799 switch is set, will generate warnings that such checks are required.
23800
23801 The use of dynamic dispatching for tagged types similarly generates
23802 a requirement for dynamic checks, and premature calls to any primitive
23803 operation of a tagged type before the body of the operation has been
23804 elaborated, will result in the raising of @code{Program_Error}.
23805
23806 @node Summary of Procedures for Elaboration Control
23807 @section Summary of Procedures for Elaboration Control
23808 @cindex Elaboration control
23809
23810 @noindent
23811 First, compile your program with the default options, using none of
23812 the special elaboration control switches. If the binder successfully
23813 binds your program, then you can be confident that, apart from issues
23814 raised by the use of access-to-subprogram types and dynamic dispatching,
23815 the program is free of elaboration errors. If it is important that the
23816 program be portable, then use the
23817 @option{-gnatwl}
23818 switch to generate warnings about missing @code{Elaborate_All}
23819 pragmas, and supply the missing pragmas.
23820
23821 If the program fails to bind using the default static elaboration
23822 handling, then you can fix the program to eliminate the binder
23823 message, or recompile the entire program with the
23824 @option{-gnatE} switch to generate dynamic elaboration checks,
23825 and, if you are sure there really are no elaboration problems,
23826 use a global pragma @code{Suppress (Elaboration_Check)}.
23827
23828 @node Other Elaboration Order Considerations
23829 @section Other Elaboration Order Considerations
23830 @noindent
23831 This section has been entirely concerned with the issue of finding a valid
23832 elaboration order, as defined by the Ada Reference Manual. In a case
23833 where several elaboration orders are valid, the task is to find one
23834 of the possible valid elaboration orders (and the static model in GNAT
23835 will ensure that this is achieved).
23836
23837 The purpose of the elaboration rules in the Ada Reference Manual is to
23838 make sure that no entity is accessed before it has been elaborated. For
23839 a subprogram, this means that the spec and body must have been elaborated
23840 before the subprogram is called. For an object, this means that the object
23841 must have been elaborated before its value is read or written. A violation
23842 of either of these two requirements is an access before elaboration order,
23843 and this section has been all about avoiding such errors.
23844
23845 In the case where more than one order of elaboration is possible, in the
23846 sense that access before elaboration errors are avoided, then any one of
23847 the orders is ``correct'' in the sense that it meets the requirements of
23848 the Ada Reference Manual, and no such error occurs.
23849
23850 However, it may be the case for a given program, that there are
23851 constraints on the order of elaboration that come not from consideration
23852 of avoiding elaboration errors, but rather from extra-lingual logic
23853 requirements. Consider this example:
23854
23855 @smallexample @c ada
23856 with Init_Constants;
23857 package Constants is
23858    X : Integer := 0;
23859    Y : Integer := 0;
23860 end Constants;
23861
23862 package Init_Constants is
23863    procedure P; -- require a body
23864 end Init_Constants;
23865
23866 with Constants;
23867 package body Init_Constants is
23868    procedure P is begin null; end;
23869 begin
23870    Constants.X := 3;
23871    Constants.Y := 4;
23872 end Init_Constants;
23873
23874 with Constants;
23875 package Calc is
23876    Z : Integer := Constants.X + Constants.Y;
23877 end Calc;
23878
23879 with Calc;
23880 with Text_IO; use Text_IO;
23881 procedure Main is
23882 begin
23883    Put_Line (Calc.Z'Img);
23884 end Main;
23885 @end smallexample
23886
23887 @noindent
23888 In this example, there is more than one valid order of elaboration. For
23889 example both the following are correct orders:
23890
23891 @smallexample
23892 Init_Constants spec
23893 Constants spec
23894 Calc spec
23895 Init_Constants body
23896 Main body
23897
23898   and
23899
23900 Init_Constants spec
23901 Init_Constants body
23902 Constants spec
23903 Calc spec
23904 Main body
23905 @end smallexample
23906
23907 @noindent
23908 There is no language rule to prefer one or the other, both are correct
23909 from an order of elaboration point of view. But the programmatic effects
23910 of the two orders are very different. In the first, the elaboration routine
23911 of @code{Calc} initializes @code{Z} to zero, and then the main program
23912 runs with this value of zero. But in the second order, the elaboration
23913 routine of @code{Calc} runs after the body of Init_Constants has set
23914 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
23915 runs.
23916
23917 One could perhaps by applying pretty clever non-artificial intelligence
23918 to the situation guess that it is more likely that the second order of
23919 elaboration is the one desired, but there is no formal linguistic reason
23920 to prefer one over the other. In fact in this particular case, GNAT will
23921 prefer the second order, because of the rule that bodies are elaborated
23922 as soon as possible, but it's just luck that this is what was wanted
23923 (if indeed the second order was preferred).
23924
23925 If the program cares about the order of elaboration routines in a case like
23926 this, it is important to specify the order required. In this particular
23927 case, that could have been achieved by adding to the spec of Calc:
23928
23929 @smallexample @c ada
23930 pragma Elaborate_All (Constants);
23931 @end smallexample
23932
23933 @noindent
23934 which requires that the body (if any) and spec of @code{Constants},
23935 as well as the body and spec of any unit @code{with}'ed by
23936 @code{Constants} be elaborated before @code{Calc} is elaborated.
23937
23938 Clearly no automatic method can always guess which alternative you require,
23939 and if you are working with legacy code that had constraints of this kind
23940 which were not properly specified by adding @code{Elaborate} or
23941 @code{Elaborate_All} pragmas, then indeed it is possible that two different
23942 compilers can choose different orders.
23943
23944 The @code{gnatbind}
23945 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
23946 out problems. This switch causes bodies to be elaborated as late as possible
23947 instead of as early as possible. In the example above, it would have forced
23948 the choice of the first elaboration order. If you get different results
23949 when using this switch, and particularly if one set of results is right,
23950 and one is wrong as far as you are concerned, it shows that you have some
23951 missing @code{Elaborate} pragmas. For the example above, we have the
23952 following output:
23953
23954 @smallexample
23955 gnatmake -f -q main
23956 main
23957  7
23958 gnatmake -f -q main -bargs -p
23959 main
23960  0
23961 @end smallexample
23962
23963 @noindent
23964 It is of course quite unlikely that both these results are correct, so
23965 it is up to you in a case like this to investigate the source of the
23966 difference, by looking at the two elaboration orders that are chosen,
23967 and figuring out which is correct, and then adding the necessary
23968 @code{Elaborate_All} pragmas to ensure the desired order.
23969
23970
23971 @node Inline Assembler
23972 @appendix Inline Assembler
23973
23974 @noindent
23975 If you need to write low-level software that interacts directly
23976 with the hardware, Ada provides two ways to incorporate assembly
23977 language code into your program.  First, you can import and invoke
23978 external routines written in assembly language, an Ada feature fully
23979 supported by GNAT.  However, for small sections of code it may be simpler
23980 or more efficient to include assembly language statements directly
23981 in your Ada source program, using the facilities of the implementation-defined
23982 package @code{System.Machine_Code}, which incorporates the gcc
23983 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
23984 including the following:
23985
23986 @itemize @bullet
23987 @item No need to use non-Ada tools
23988 @item Consistent interface over different targets
23989 @item Automatic usage of the proper calling conventions
23990 @item Access to Ada constants and variables
23991 @item Definition of intrinsic routines
23992 @item Possibility of inlining a subprogram comprising assembler code
23993 @item Code optimizer can take Inline Assembler code into account
23994 @end itemize
23995
23996 This chapter presents a series of examples to show you how to use
23997 the Inline Assembler.  Although it focuses on the Intel x86,
23998 the general approach applies also to other processors.
23999 It is assumed that you are familiar with Ada
24000 and with assembly language programming.
24001
24002 @menu
24003 * Basic Assembler Syntax::
24004 * A Simple Example of Inline Assembler::
24005 * Output Variables in Inline Assembler::
24006 * Input Variables in Inline Assembler::
24007 * Inlining Inline Assembler Code::
24008 * Other Asm Functionality::
24009 * A Complete Example::
24010 @end menu
24011
24012 @c ---------------------------------------------------------------------------
24013 @node Basic Assembler Syntax
24014 @section Basic Assembler Syntax
24015
24016 @noindent
24017 The assembler used by GNAT and gcc is based not on the Intel assembly
24018 language, but rather on a language that descends from the AT&T Unix
24019 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
24020 The following table summarizes the main features of @emph{as} syntax
24021 and points out the differences from the Intel conventions.
24022 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
24023 pre-processor) documentation for further information.
24024
24025 @table @asis
24026 @item Register names
24027 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
24028 @*
24029 Intel: No extra punctuation; for example @code{eax}
24030
24031 @item Immediate operand
24032 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
24033 @*
24034 Intel: No extra punctuation; for example @code{4}
24035
24036 @item Address
24037 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
24038 @*
24039 Intel: No extra punctuation; for example @code{loc}
24040
24041 @item Memory contents
24042 gcc / @emph{as}: No extra punctuation; for example @code{loc}
24043 @*
24044 Intel: Square brackets; for example @code{[loc]}
24045
24046 @item Register contents
24047 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
24048 @*
24049 Intel: Square brackets; for example @code{[eax]}
24050
24051 @item Hexadecimal numbers
24052 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
24053 @*
24054 Intel: Trailing ``h''; for example @code{A0h}
24055
24056 @item Operand size
24057 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
24058 a 16-bit word
24059 @*
24060 Intel: Implicit, deduced by assembler; for example @code{mov}
24061
24062 @item Instruction repetition
24063 gcc / @emph{as}: Split into two lines; for example
24064 @*
24065 @code{rep}
24066 @*
24067 @code{stosl}
24068 @*
24069 Intel: Keep on one line; for example @code{rep stosl}
24070
24071 @item Order of operands
24072 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
24073 @*
24074 Intel: Destination first; for example @code{mov eax, 4}
24075 @end table
24076
24077 @c ---------------------------------------------------------------------------
24078 @node A Simple Example of Inline Assembler
24079 @section A Simple Example of Inline Assembler
24080
24081 @noindent
24082 The following example will generate a single assembly language statement,
24083 @code{nop}, which does nothing.  Despite its lack of run-time effect,
24084 the example will be useful in illustrating the basics of
24085 the Inline Assembler facility.
24086
24087 @smallexample @c ada
24088 @group
24089 with System.Machine_Code; use System.Machine_Code;
24090 procedure Nothing is
24091 begin
24092    Asm ("nop");
24093 end Nothing;
24094 @end group
24095 @end smallexample
24096
24097 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
24098 here it takes one parameter, a @emph{template string} that must be a static
24099 expression and that will form the generated instruction.
24100 @code{Asm} may be regarded as a compile-time procedure that parses
24101 the template string and additional parameters (none here),
24102 from which it generates a sequence of assembly language instructions.
24103
24104 The examples in this chapter will illustrate several of the forms
24105 for invoking @code{Asm}; a complete specification of the syntax
24106 is found in the @cite{GNAT Reference Manual}.
24107
24108 Under the standard GNAT conventions, the @code{Nothing} procedure
24109 should be in a file named @file{nothing.adb}.
24110 You can build the executable in the usual way:
24111 @smallexample
24112 gnatmake nothing
24113 @end smallexample
24114 However, the interesting aspect of this example is not its run-time behavior
24115 but rather the generated assembly code.
24116 To see this output, invoke the compiler as follows:
24117 @smallexample
24118    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
24119 @end smallexample
24120 where the options are:
24121
24122 @table @code
24123 @item -c
24124 compile only (no bind or link)
24125 @item -S
24126 generate assembler listing
24127 @item -fomit-frame-pointer
24128 do not set up separate stack frames
24129 @item -gnatp
24130 do not add runtime checks
24131 @end table
24132
24133 This gives a human-readable assembler version of the code. The resulting
24134 file will have the same name as the Ada source file, but with a @code{.s}
24135 extension. In our example, the file @file{nothing.s} has the following
24136 contents:
24137
24138 @smallexample
24139 @group
24140 .file "nothing.adb"
24141 gcc2_compiled.:
24142 ___gnu_compiled_ada:
24143 .text
24144    .align 4
24145 .globl __ada_nothing
24146 __ada_nothing:
24147 #APP
24148    nop
24149 #NO_APP
24150    jmp L1
24151    .align 2,0x90
24152 L1:
24153    ret
24154 @end group
24155 @end smallexample
24156
24157 The assembly code you included is clearly indicated by
24158 the compiler, between the @code{#APP} and @code{#NO_APP}
24159 delimiters. The character before the 'APP' and 'NOAPP'
24160 can differ on different targets. For example, GNU/Linux uses '#APP' while
24161 on NT you will see '/APP'.
24162
24163 If you make a mistake in your assembler code (such as using the
24164 wrong size modifier, or using a wrong operand for the instruction) GNAT
24165 will report this error in a temporary file, which will be deleted when
24166 the compilation is finished.  Generating an assembler file will help
24167 in such cases, since you can assemble this file separately using the
24168 @emph{as} assembler that comes with gcc.
24169
24170 Assembling the file using the command
24171
24172 @smallexample
24173 as @file{nothing.s}
24174 @end smallexample
24175 @noindent
24176 will give you error messages whose lines correspond to the assembler
24177 input file, so you can easily find and correct any mistakes you made.
24178 If there are no errors, @emph{as} will generate an object file
24179 @file{nothing.out}.
24180
24181 @c ---------------------------------------------------------------------------
24182 @node Output Variables in Inline Assembler
24183 @section Output Variables in Inline Assembler
24184
24185 @noindent
24186 The examples in this section, showing how to access the processor flags,
24187 illustrate how to specify the destination operands for assembly language
24188 statements.
24189
24190 @smallexample @c ada
24191 @group
24192 with Interfaces; use Interfaces;
24193 with Ada.Text_IO; use Ada.Text_IO;
24194 with System.Machine_Code; use System.Machine_Code;
24195 procedure Get_Flags is
24196    Flags : Unsigned_32;
24197    use ASCII;
24198 begin
24199    Asm ("pushfl"          & LF & HT & -- push flags on stack
24200         "popl %%eax"      & LF & HT & -- load eax with flags
24201         "movl %%eax, %0",             -- store flags in variable
24202         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24203    Put_Line ("Flags register:" & Flags'Img);
24204 end Get_Flags;
24205 @end group
24206 @end smallexample
24207
24208 In order to have a nicely aligned assembly listing, we have separated
24209 multiple assembler statements in the Asm template string with linefeed
24210 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
24211 The resulting section of the assembly output file is:
24212
24213 @smallexample
24214 @group
24215 #APP
24216    pushfl
24217    popl %eax
24218    movl %eax, -40(%ebp)
24219 #NO_APP
24220 @end group
24221 @end smallexample
24222
24223 It would have been legal to write the Asm invocation as:
24224
24225 @smallexample
24226 Asm ("pushfl popl %%eax movl %%eax, %0")
24227 @end smallexample
24228
24229 but in the generated assembler file, this would come out as:
24230
24231 @smallexample
24232 #APP
24233    pushfl popl %eax movl %eax, -40(%ebp)
24234 #NO_APP
24235 @end smallexample
24236
24237 which is not so convenient for the human reader.
24238
24239 We use Ada comments
24240 at the end of each line to explain what the assembler instructions
24241 actually do.  This is a useful convention.
24242
24243 When writing Inline Assembler instructions, you need to precede each register
24244 and variable name with a percent sign.  Since the assembler already requires
24245 a percent sign at the beginning of a register name, you need two consecutive
24246 percent signs for such names in the Asm template string, thus @code{%%eax}.
24247 In the generated assembly code, one of the percent signs will be stripped off.
24248
24249 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
24250 variables: operands you later define using @code{Input} or @code{Output}
24251 parameters to @code{Asm}.
24252 An output variable is illustrated in
24253 the third statement in the Asm template string:
24254 @smallexample
24255 movl %%eax, %0
24256 @end smallexample
24257 The intent is to store the contents of the eax register in a variable that can
24258 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
24259 necessarily work, since the compiler might optimize by using a register
24260 to hold Flags, and the expansion of the @code{movl} instruction would not be
24261 aware of this optimization.  The solution is not to store the result directly
24262 but rather to advise the compiler to choose the correct operand form;
24263 that is the purpose of the @code{%0} output variable.
24264
24265 Information about the output variable is supplied in the @code{Outputs}
24266 parameter to @code{Asm}:
24267 @smallexample
24268 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24269 @end smallexample
24270
24271 The output is defined by the @code{Asm_Output} attribute of the target type;
24272 the general format is
24273 @smallexample
24274 Type'Asm_Output (constraint_string, variable_name)
24275 @end smallexample
24276
24277 The constraint string directs the compiler how
24278 to store/access the associated variable.  In the example
24279 @smallexample
24280 Unsigned_32'Asm_Output ("=m", Flags);
24281 @end smallexample
24282 the @code{"m"} (memory) constraint tells the compiler that the variable
24283 @code{Flags} should be stored in a memory variable, thus preventing
24284 the optimizer from keeping it in a register.  In contrast,
24285 @smallexample
24286 Unsigned_32'Asm_Output ("=r", Flags);
24287 @end smallexample
24288 uses the @code{"r"} (register) constraint, telling the compiler to
24289 store the variable in a register.
24290
24291 If the constraint is preceded by the equal character (@strong{=}), it tells
24292 the compiler that the variable will be used to store data into it.
24293
24294 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
24295 allowing the optimizer to choose whatever it deems best.
24296
24297 There are a fairly large number of constraints, but the ones that are
24298 most useful (for the Intel x86 processor) are the following:
24299
24300 @table @code
24301 @item =
24302 output constraint
24303 @item g
24304 global (i.e. can be stored anywhere)
24305 @item m
24306 in memory
24307 @item I
24308 a constant
24309 @item a
24310 use eax
24311 @item b
24312 use ebx
24313 @item c
24314 use ecx
24315 @item d
24316 use edx
24317 @item S
24318 use esi
24319 @item D
24320 use edi
24321 @item r
24322 use one of eax, ebx, ecx or edx
24323 @item q
24324 use one of eax, ebx, ecx, edx, esi or edi
24325 @end table
24326
24327 The full set of constraints is described in the gcc and @emph{as}
24328 documentation; note that it is possible to combine certain constraints
24329 in one constraint string.
24330
24331 You specify the association of an output variable with an assembler operand
24332 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
24333 integer.  Thus in
24334 @smallexample @c ada
24335 @group
24336 Asm ("pushfl"          & LF & HT & -- push flags on stack
24337      "popl %%eax"      & LF & HT & -- load eax with flags
24338      "movl %%eax, %0",             -- store flags in variable
24339      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24340 @end group
24341 @end smallexample
24342 @noindent
24343 @code{%0} will be replaced in the expanded code by the appropriate operand,
24344 whatever
24345 the compiler decided for the @code{Flags} variable.
24346
24347 In general, you may have any number of output variables:
24348 @itemize @bullet
24349 @item
24350 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
24351 @item
24352 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
24353 of @code{Asm_Output} attributes
24354 @end itemize
24355
24356 For example:
24357 @smallexample @c ada
24358 @group
24359 Asm ("movl %%eax, %0" & LF & HT &
24360      "movl %%ebx, %1" & LF & HT &
24361      "movl %%ecx, %2",
24362      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
24363                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
24364                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
24365 @end group
24366 @end smallexample
24367 @noindent
24368 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
24369 in the Ada program.
24370
24371 As a variation on the @code{Get_Flags} example, we can use the constraints
24372 string to direct the compiler to store the eax register into the @code{Flags}
24373 variable, instead of including the store instruction explicitly in the
24374 @code{Asm} template string:
24375
24376 @smallexample @c ada
24377 @group
24378 with Interfaces; use Interfaces;
24379 with Ada.Text_IO; use Ada.Text_IO;
24380 with System.Machine_Code; use System.Machine_Code;
24381 procedure Get_Flags_2 is
24382    Flags : Unsigned_32;
24383    use ASCII;
24384 begin
24385    Asm ("pushfl"      & LF & HT & -- push flags on stack
24386         "popl %%eax",             -- save flags in eax
24387         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
24388    Put_Line ("Flags register:" & Flags'Img);
24389 end Get_Flags_2;
24390 @end group
24391 @end smallexample
24392
24393 @noindent
24394 The @code{"a"} constraint tells the compiler that the @code{Flags}
24395 variable will come from the eax register. Here is the resulting code:
24396
24397 @smallexample
24398 @group
24399 #APP
24400    pushfl
24401    popl %eax
24402 #NO_APP
24403    movl %eax,-40(%ebp)
24404 @end group
24405 @end smallexample
24406
24407 @noindent
24408 The compiler generated the store of eax into Flags after
24409 expanding the assembler code.
24410
24411 Actually, there was no need to pop the flags into the eax register;
24412 more simply, we could just pop the flags directly into the program variable:
24413
24414 @smallexample @c ada
24415 @group
24416 with Interfaces; use Interfaces;
24417 with Ada.Text_IO; use Ada.Text_IO;
24418 with System.Machine_Code; use System.Machine_Code;
24419 procedure Get_Flags_3 is
24420    Flags : Unsigned_32;
24421    use ASCII;
24422 begin
24423    Asm ("pushfl"  & LF & HT & -- push flags on stack
24424         "pop %0",             -- save flags in Flags
24425         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24426    Put_Line ("Flags register:" & Flags'Img);
24427 end Get_Flags_3;
24428 @end group
24429 @end smallexample
24430
24431 @c ---------------------------------------------------------------------------
24432 @node Input Variables in Inline Assembler
24433 @section Input Variables in Inline Assembler
24434
24435 @noindent
24436 The example in this section illustrates how to specify the source operands
24437 for assembly language statements.
24438 The program simply increments its input value by 1:
24439
24440 @smallexample @c ada
24441 @group
24442 with Interfaces; use Interfaces;
24443 with Ada.Text_IO; use Ada.Text_IO;
24444 with System.Machine_Code; use System.Machine_Code;
24445 procedure Increment is
24446
24447    function Incr (Value : Unsigned_32) return Unsigned_32 is
24448       Result : Unsigned_32;
24449    begin
24450       Asm ("incl %0",
24451            Inputs  => Unsigned_32'Asm_Input ("a", Value),
24452            Outputs => Unsigned_32'Asm_Output ("=a", Result));
24453       return Result;
24454    end Incr;
24455
24456    Value : Unsigned_32;
24457
24458 begin
24459    Value := 5;
24460    Put_Line ("Value before is" & Value'Img);
24461    Value := Incr (Value);
24462    Put_Line ("Value after is" & Value'Img);
24463 end Increment;
24464 @end group
24465 @end smallexample
24466
24467 The @code{Outputs} parameter to @code{Asm} specifies
24468 that the result will be in the eax register and that it is to be stored
24469 in the @code{Result} variable.
24470
24471 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
24472 but with an @code{Asm_Input} attribute.
24473 The @code{"="} constraint, indicating an output value, is not present.
24474
24475 You can have multiple input variables, in the same way that you can have more
24476 than one output variable.
24477
24478 The parameter count (%0, %1) etc, now starts at the first input
24479 statement, and continues with the output statements.
24480 When both parameters use the same variable, the
24481 compiler will treat them as the same %n operand, which is the case here.
24482
24483 Just as the @code{Outputs} parameter causes the register to be stored into the
24484 target variable after execution of the assembler statements, so does the
24485 @code{Inputs} parameter cause its variable to be loaded into the register
24486 before execution of the assembler statements.
24487
24488 Thus the effect of the @code{Asm} invocation is:
24489 @enumerate
24490 @item load the 32-bit value of @code{Value} into eax
24491 @item execute the @code{incl %eax} instruction
24492 @item store the contents of eax into the @code{Result} variable
24493 @end enumerate
24494
24495 The resulting assembler file (with @option{-O2} optimization) contains:
24496 @smallexample
24497 @group
24498 _increment__incr.1:
24499    subl $4,%esp
24500    movl 8(%esp),%eax
24501 #APP
24502    incl %eax
24503 #NO_APP
24504    movl %eax,%edx
24505    movl %ecx,(%esp)
24506    addl $4,%esp
24507    ret
24508 @end group
24509 @end smallexample
24510
24511 @c ---------------------------------------------------------------------------
24512 @node Inlining Inline Assembler Code
24513 @section Inlining Inline Assembler Code
24514
24515 @noindent
24516 For a short subprogram such as the @code{Incr} function in the previous
24517 section, the overhead of the call and return (creating / deleting the stack
24518 frame) can be significant, compared to the amount of code in the subprogram
24519 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
24520 which directs the compiler to expand invocations of the subprogram at the
24521 point(s) of call, instead of setting up a stack frame for out-of-line calls.
24522 Here is the resulting program:
24523
24524 @smallexample @c ada
24525 @group
24526 with Interfaces; use Interfaces;
24527 with Ada.Text_IO; use Ada.Text_IO;
24528 with System.Machine_Code; use System.Machine_Code;
24529 procedure Increment_2 is
24530
24531    function Incr (Value : Unsigned_32) return Unsigned_32 is
24532       Result : Unsigned_32;
24533    begin
24534       Asm ("incl %0",
24535            Inputs  => Unsigned_32'Asm_Input ("a", Value),
24536            Outputs => Unsigned_32'Asm_Output ("=a", Result));
24537       return Result;
24538    end Incr;
24539    pragma Inline (Increment);
24540
24541    Value : Unsigned_32;
24542
24543 begin
24544    Value := 5;
24545    Put_Line ("Value before is" & Value'Img);
24546    Value := Increment (Value);
24547    Put_Line ("Value after is" & Value'Img);
24548 end Increment_2;
24549 @end group
24550 @end smallexample
24551
24552 Compile the program with both optimization (@option{-O2}) and inlining
24553 enabled (@option{-gnatpn} instead of @option{-gnatp}).
24554
24555 The @code{Incr} function is still compiled as usual, but at the
24556 point in @code{Increment} where our function used to be called:
24557
24558 @smallexample
24559 @group
24560 pushl %edi
24561 call _increment__incr.1
24562 @end group
24563 @end smallexample
24564
24565 @noindent
24566 the code for the function body directly appears:
24567
24568 @smallexample
24569 @group
24570 movl %esi,%eax
24571 #APP
24572    incl %eax
24573 #NO_APP
24574    movl %eax,%edx
24575 @end group
24576 @end smallexample
24577
24578 @noindent
24579 thus saving the overhead of stack frame setup and an out-of-line call.
24580
24581 @c ---------------------------------------------------------------------------
24582 @node Other Asm Functionality
24583 @section Other @code{Asm} Functionality
24584
24585 @noindent
24586 This section describes two important parameters to the @code{Asm}
24587 procedure: @code{Clobber}, which identifies register usage;
24588 and @code{Volatile}, which inhibits unwanted optimizations.
24589
24590 @menu
24591 * The Clobber Parameter::
24592 * The Volatile Parameter::
24593 @end menu
24594
24595 @c ---------------------------------------------------------------------------
24596 @node The Clobber Parameter
24597 @subsection The @code{Clobber} Parameter
24598
24599 @noindent
24600 One of the dangers of intermixing assembly language and a compiled language
24601 such as Ada is that the compiler needs to be aware of which registers are
24602 being used by the assembly code.  In some cases, such as the earlier examples,
24603 the constraint string is sufficient to indicate register usage (e.g.,
24604 @code{"a"} for
24605 the eax register).  But more generally, the compiler needs an explicit
24606 identification of the registers that are used by the Inline Assembly
24607 statements.
24608
24609 Using a register that the compiler doesn't know about
24610 could be a side effect of an instruction (like @code{mull}
24611 storing its result in both eax and edx).
24612 It can also arise from explicit register usage in your
24613 assembly code; for example:
24614 @smallexample
24615 @group
24616 Asm ("movl %0, %%ebx" & LF & HT &
24617      "movl %%ebx, %1",
24618      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
24619      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
24620 @end group
24621 @end smallexample
24622 @noindent
24623 where the compiler (since it does not analyze the @code{Asm} template string)
24624 does not know you are using the ebx register.
24625
24626 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
24627 to identify the registers that will be used by your assembly code:
24628
24629 @smallexample
24630 @group
24631 Asm ("movl %0, %%ebx" & LF & HT &
24632      "movl %%ebx, %1",
24633      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
24634      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
24635      Clobber => "ebx");
24636 @end group
24637 @end smallexample
24638
24639 The Clobber parameter is a static string expression specifying the
24640 register(s) you are using.  Note that register names are @emph{not} prefixed
24641 by a percent sign. Also, if more than one register is used then their names
24642 are separated by commas; e.g., @code{"eax, ebx"}
24643
24644 The @code{Clobber} parameter has several additional uses:
24645 @enumerate
24646 @item Use ``register'' name @code{cc} to indicate that flags might have changed
24647 @item Use ``register'' name @code{memory} if you changed a memory location
24648 @end enumerate
24649
24650 @c ---------------------------------------------------------------------------
24651 @node The Volatile Parameter
24652 @subsection The @code{Volatile} Parameter
24653 @cindex Volatile parameter
24654
24655 @noindent
24656 Compiler optimizations in the presence of Inline Assembler may sometimes have
24657 unwanted effects.  For example, when an @code{Asm} invocation with an input
24658 variable is inside a loop, the compiler might move the loading of the input
24659 variable outside the loop, regarding it as a one-time initialization.
24660
24661 If this effect is not desired, you can disable such optimizations by setting
24662 the @code{Volatile} parameter to @code{True}; for example:
24663
24664 @smallexample @c ada
24665 @group
24666 Asm ("movl %0, %%ebx" & LF & HT &
24667      "movl %%ebx, %1",
24668      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
24669      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
24670      Clobber  => "ebx",
24671      Volatile => True);
24672 @end group
24673 @end smallexample
24674
24675 By default, @code{Volatile} is set to @code{False} unless there is no
24676 @code{Outputs} parameter.
24677
24678 Although setting @code{Volatile} to @code{True} prevents unwanted
24679 optimizations, it will also disable other optimizations that might be
24680 important for efficiency. In general, you should set @code{Volatile}
24681 to @code{True} only if the compiler's optimizations have created
24682 problems.
24683
24684 @c ---------------------------------------------------------------------------
24685 @node A Complete Example
24686 @section A Complete Example
24687
24688 @noindent
24689 This section contains a complete program illustrating a realistic usage
24690 of GNAT's Inline Assembler capabilities.  It comprises a main procedure
24691 @code{Check_CPU} and a package @code{Intel_CPU}.
24692 The package declares a collection of functions that detect the properties
24693 of the 32-bit x86 processor that is running the program.
24694 The main procedure invokes these functions and displays the information.
24695
24696 The Intel_CPU package could be enhanced by adding functions to
24697 detect the type of x386 co-processor, the processor caching options and
24698 special operations such as the SIMD extensions.
24699
24700 Although the Intel_CPU package has been written for 32-bit Intel
24701 compatible CPUs, it is OS neutral. It has been tested on DOS,
24702 Windows/NT and GNU/Linux.
24703
24704 @menu
24705 * Check_CPU Procedure::
24706 * Intel_CPU Package Specification::
24707 * Intel_CPU Package Body::
24708 @end menu
24709
24710 @c ---------------------------------------------------------------------------
24711 @node Check_CPU Procedure
24712 @subsection @code{Check_CPU} Procedure
24713 @cindex Check_CPU procedure
24714
24715 @smallexample @c adanocomment
24716 ---------------------------------------------------------------------
24717 --                                                                 --
24718 --  Uses the Intel_CPU package to identify the CPU the program is  --
24719 --  running on, and some of the features it supports.              --
24720 --                                                                 --
24721 ---------------------------------------------------------------------
24722
24723 with Intel_CPU;                     --  Intel CPU detection functions
24724 with Ada.Text_IO;                   --  Standard text I/O
24725 with Ada.Command_Line;              --  To set the exit status
24726
24727 procedure Check_CPU is
24728
24729    Type_Found : Boolean := False;
24730    --  Flag to indicate that processor was identified
24731
24732    Features   : Intel_CPU.Processor_Features;
24733    --  The processor features
24734
24735    Signature  : Intel_CPU.Processor_Signature;
24736    --  The processor type signature
24737
24738 begin
24739
24740    -----------------------------------
24741    --  Display the program banner.  --
24742    -----------------------------------
24743
24744    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
24745                          ": check Intel CPU version and features, v1.0");
24746    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
24747    Ada.Text_IO.New_Line;
24748
24749    -----------------------------------------------------------------------
24750    --  We can safely start with the assumption that we are on at least  --
24751    --  a x386 processor. If the CPUID instruction is present, then we   --
24752    --  have a later processor type.                                     --
24753    -----------------------------------------------------------------------
24754
24755    if Intel_CPU.Has_CPUID = False then
24756
24757       --  No CPUID instruction, so we assume this is indeed a x386
24758       --  processor. We can still check if it has a FP co-processor.
24759       if Intel_CPU.Has_FPU then
24760          Ada.Text_IO.Put_Line
24761            ("x386-type processor with a FP co-processor");
24762       else
24763          Ada.Text_IO.Put_Line
24764            ("x386-type processor without a FP co-processor");
24765       end if;  --  check for FPU
24766
24767       --  Program done
24768       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24769       return;
24770
24771    end if;  --  check for CPUID
24772
24773    -----------------------------------------------------------------------
24774    --  If CPUID is supported, check if this is a true Intel processor,  --
24775    --  if it is not, display a warning.                                 --
24776    -----------------------------------------------------------------------
24777
24778    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
24779       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
24780       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
24781    end if;  --  check if Intel
24782
24783    ----------------------------------------------------------------------
24784    --  With the CPUID instruction present, we can assume at least a    --
24785    --  x486 processor. If the CPUID support level is < 1 then we have  --
24786    --  to leave it at that.                                            --
24787    ----------------------------------------------------------------------
24788
24789    if Intel_CPU.CPUID_Level < 1 then
24790
24791       --  Ok, this is a x486 processor. we still can get the Vendor ID
24792       Ada.Text_IO.Put_Line ("x486-type processor");
24793       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
24794
24795       --  We can also check if there is a FPU present
24796       if Intel_CPU.Has_FPU then
24797          Ada.Text_IO.Put_Line ("Floating-Point support");
24798       else
24799          Ada.Text_IO.Put_Line ("No Floating-Point support");
24800       end if;  --  check for FPU
24801
24802       --  Program done
24803       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24804       return;
24805
24806    end if;  --  check CPUID level
24807
24808    ---------------------------------------------------------------------
24809    --  With a CPUID level of 1 we can use the processor signature to  --
24810    --  determine it's exact type.                                     --
24811    ---------------------------------------------------------------------
24812
24813    Signature := Intel_CPU.Signature;
24814
24815    ----------------------------------------------------------------------
24816    --  Ok, now we go into a lot of messy comparisons to get the        --
24817    --  processor type. For clarity, no attememt to try to optimize the --
24818    --  comparisons has been made. Note that since Intel_CPU does not   --
24819    --  support getting cache info, we cannot distinguish between P5    --
24820    --  and Celeron types yet.                                          --
24821    ----------------------------------------------------------------------
24822
24823    --  x486SL
24824    if Signature.Processor_Type = 2#00#   and
24825      Signature.Family          = 2#0100# and
24826      Signature.Model           = 2#0100# then
24827       Type_Found := True;
24828       Ada.Text_IO.Put_Line ("x486SL processor");
24829    end if;
24830
24831    --  x486DX2 Write-Back
24832    if Signature.Processor_Type = 2#00#   and
24833      Signature.Family          = 2#0100# and
24834      Signature.Model           = 2#0111# then
24835       Type_Found := True;
24836       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
24837    end if;
24838
24839    --  x486DX4
24840    if Signature.Processor_Type = 2#00#   and
24841      Signature.Family          = 2#0100# and
24842      Signature.Model           = 2#1000# then
24843       Type_Found := True;
24844       Ada.Text_IO.Put_Line ("x486DX4 processor");
24845    end if;
24846
24847    --  x486DX4 Overdrive
24848    if Signature.Processor_Type = 2#01#   and
24849      Signature.Family          = 2#0100# and
24850      Signature.Model           = 2#1000# then
24851       Type_Found := True;
24852       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
24853    end if;
24854
24855    --  Pentium (60, 66)
24856    if Signature.Processor_Type = 2#00#   and
24857      Signature.Family          = 2#0101# and
24858      Signature.Model           = 2#0001# then
24859       Type_Found := True;
24860       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
24861    end if;
24862
24863    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
24864    if Signature.Processor_Type = 2#00#   and
24865      Signature.Family          = 2#0101# and
24866      Signature.Model           = 2#0010# then
24867       Type_Found := True;
24868       Ada.Text_IO.Put_Line
24869         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
24870    end if;
24871
24872    --  Pentium OverDrive (60, 66)
24873    if Signature.Processor_Type = 2#01#   and
24874      Signature.Family          = 2#0101# and
24875      Signature.Model           = 2#0001# then
24876       Type_Found := True;
24877       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
24878    end if;
24879
24880    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
24881    if Signature.Processor_Type = 2#01#   and
24882      Signature.Family          = 2#0101# and
24883      Signature.Model           = 2#0010# then
24884       Type_Found := True;
24885       Ada.Text_IO.Put_Line
24886         ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
24887    end if;
24888
24889    --  Pentium OverDrive processor for x486 processor-based systems
24890    if Signature.Processor_Type = 2#01#   and
24891      Signature.Family          = 2#0101# and
24892      Signature.Model           = 2#0011# then
24893       Type_Found := True;
24894       Ada.Text_IO.Put_Line
24895         ("Pentium OverDrive processor for x486 processor-based systems");
24896    end if;
24897
24898    --  Pentium processor with MMX technology (166, 200)
24899    if Signature.Processor_Type = 2#00#   and
24900      Signature.Family          = 2#0101# and
24901      Signature.Model           = 2#0100# then
24902       Type_Found := True;
24903       Ada.Text_IO.Put_Line
24904         ("Pentium processor with MMX technology (166, 200)");
24905    end if;
24906
24907    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
24908    if Signature.Processor_Type = 2#01#   and
24909      Signature.Family          = 2#0101# and
24910      Signature.Model           = 2#0100# then
24911       Type_Found := True;
24912       Ada.Text_IO.Put_Line
24913         ("Pentium OverDrive processor with MMX " &
24914          "technology for Pentium processor (75, 90, 100, 120, 133)");
24915    end if;
24916
24917    --  Pentium Pro processor
24918    if Signature.Processor_Type = 2#00#   and
24919      Signature.Family          = 2#0110# and
24920      Signature.Model           = 2#0001# then
24921       Type_Found := True;
24922       Ada.Text_IO.Put_Line ("Pentium Pro processor");
24923    end if;
24924
24925    --  Pentium II processor, model 3
24926    if Signature.Processor_Type = 2#00#   and
24927      Signature.Family          = 2#0110# and
24928      Signature.Model           = 2#0011# then
24929       Type_Found := True;
24930       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
24931    end if;
24932
24933    --  Pentium II processor, model 5 or Celeron processor
24934    if Signature.Processor_Type = 2#00#   and
24935      Signature.Family          = 2#0110# and
24936      Signature.Model           = 2#0101# then
24937       Type_Found := True;
24938       Ada.Text_IO.Put_Line
24939         ("Pentium II processor, model 5 or Celeron processor");
24940    end if;
24941
24942    --  Pentium Pro OverDrive processor
24943    if Signature.Processor_Type = 2#01#   and
24944      Signature.Family          = 2#0110# and
24945      Signature.Model           = 2#0011# then
24946       Type_Found := True;
24947       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
24948    end if;
24949
24950    --  If no type recognized, we have an unknown. Display what
24951    --  we _do_ know
24952    if Type_Found = False then
24953       Ada.Text_IO.Put_Line ("Unknown processor");
24954    end if;
24955
24956    -----------------------------------------
24957    --  Display processor stepping level.  --
24958    -----------------------------------------
24959
24960    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
24961
24962    ---------------------------------
24963    --  Display vendor ID string.  --
24964    ---------------------------------
24965
24966    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
24967
24968    ------------------------------------
24969    --  Get the processors features.  --
24970    ------------------------------------
24971
24972    Features := Intel_CPU.Features;
24973
24974    -----------------------------
24975    --  Check for a FPU unit.  --
24976    -----------------------------
24977
24978    if Features.FPU = True then
24979       Ada.Text_IO.Put_Line ("Floating-Point unit available");
24980    else
24981       Ada.Text_IO.Put_Line ("no Floating-Point unit");
24982    end if;  --  check for FPU
24983
24984    --------------------------------
24985    --  List processor features.  --
24986    --------------------------------
24987
24988    Ada.Text_IO.Put_Line ("Supported features: ");
24989
24990    --  Virtual Mode Extension
24991    if Features.VME = True then
24992       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
24993    end if;
24994
24995    --  Debugging Extension
24996    if Features.DE = True then
24997       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
24998    end if;
24999
25000    --  Page Size Extension
25001    if Features.PSE = True then
25002       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
25003    end if;
25004
25005    --  Time Stamp Counter
25006    if Features.TSC = True then
25007       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
25008    end if;
25009
25010    --  Model Specific Registers
25011    if Features.MSR = True then
25012       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
25013    end if;
25014
25015    --  Physical Address Extension
25016    if Features.PAE = True then
25017       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
25018    end if;
25019
25020    --  Machine Check Extension
25021    if Features.MCE = True then
25022       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
25023    end if;
25024
25025    --  CMPXCHG8 instruction supported
25026    if Features.CX8 = True then
25027       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
25028    end if;
25029
25030    --  on-chip APIC hardware support
25031    if Features.APIC = True then
25032       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
25033    end if;
25034
25035    --  Fast System Call
25036    if Features.SEP = True then
25037       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
25038    end if;
25039
25040    --  Memory Type Range Registers
25041    if Features.MTRR = True then
25042       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
25043    end if;
25044
25045    --  Page Global Enable
25046    if Features.PGE = True then
25047       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
25048    end if;
25049
25050    --  Machine Check Architecture
25051    if Features.MCA = True then
25052       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
25053    end if;
25054
25055    --  Conditional Move Instruction Supported
25056    if Features.CMOV = True then
25057       Ada.Text_IO.Put_Line
25058         ("    CMOV   - Conditional Move Instruction Supported");
25059    end if;
25060
25061    --  Page Attribute Table
25062    if Features.PAT = True then
25063       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
25064    end if;
25065
25066    --  36-bit Page Size Extension
25067    if Features.PSE_36 = True then
25068       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
25069    end if;
25070
25071    --  MMX technology supported
25072    if Features.MMX = True then
25073       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
25074    end if;
25075
25076    --  Fast FP Save and Restore
25077    if Features.FXSR = True then
25078       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
25079    end if;
25080
25081    ---------------------
25082    --  Program done.  --
25083    ---------------------
25084
25085    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
25086
25087 exception
25088
25089    when others =>
25090       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
25091       raise;
25092
25093 end Check_CPU;
25094 @end smallexample
25095
25096 @c ---------------------------------------------------------------------------
25097 @node Intel_CPU Package Specification
25098 @subsection @code{Intel_CPU} Package Specification
25099 @cindex Intel_CPU package specification
25100
25101 @smallexample @c adanocomment
25102 -------------------------------------------------------------------------
25103 --                                                                     --
25104 --  file: intel_cpu.ads                                                --
25105 --                                                                     --
25106 --           *********************************************             --
25107 --           * WARNING: for 32-bit Intel processors only *             --
25108 --           *********************************************             --
25109 --                                                                     --
25110 --  This package contains a number of subprograms that are useful in   --
25111 --  determining the Intel x86 CPU (and the features it supports) on    --
25112 --  which the program is running.                                      --
25113 --                                                                     --
25114 --  The package is based upon the information given in the Intel       --
25115 --  Application Note AP-485: "Intel Processor Identification and the   --
25116 --  CPUID Instruction" as of April 1998. This application note can be  --
25117 --  found on www.intel.com.                                            --
25118 --                                                                     --
25119 --  It currently deals with 32-bit processors only, will not detect    --
25120 --  features added after april 1998, and does not guarantee proper     --
25121 --  results on Intel-compatible processors.                            --
25122 --                                                                     --
25123 --  Cache info and x386 fpu type detection are not supported.          --
25124 --                                                                     --
25125 --  This package does not use any privileged instructions, so should   --
25126 --  work on any OS running on a 32-bit Intel processor.                --
25127 --                                                                     --
25128 -------------------------------------------------------------------------
25129
25130 with Interfaces;             use Interfaces;
25131 --  for using unsigned types
25132
25133 with System.Machine_Code;    use System.Machine_Code;
25134 --  for using inline assembler code
25135
25136 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
25137 --  for inserting control characters
25138
25139 package Intel_CPU is
25140
25141    ----------------------
25142    --  Processor bits  --
25143    ----------------------
25144
25145    subtype Num_Bits is Natural range 0 .. 31;
25146    --  the number of processor bits (32)
25147
25148    --------------------------
25149    --  Processor register  --
25150    --------------------------
25151
25152    --  define a processor register type for easy access to
25153    --  the individual bits
25154
25155    type Processor_Register is array (Num_Bits) of Boolean;
25156    pragma Pack (Processor_Register);
25157    for Processor_Register'Size use 32;
25158
25159    -------------------------
25160    --  Unsigned register  --
25161    -------------------------
25162
25163    --  define a processor register type for easy access to
25164    --  the individual bytes
25165
25166    type Unsigned_Register is
25167       record
25168          L1 : Unsigned_8;
25169          H1 : Unsigned_8;
25170          L2 : Unsigned_8;
25171          H2 : Unsigned_8;
25172       end record;
25173
25174    for Unsigned_Register use
25175       record
25176          L1 at 0 range  0 ..  7;
25177          H1 at 0 range  8 .. 15;
25178          L2 at 0 range 16 .. 23;
25179          H2 at 0 range 24 .. 31;
25180       end record;
25181
25182    for Unsigned_Register'Size use 32;
25183
25184    ---------------------------------
25185    --  Intel processor vendor ID  --
25186    ---------------------------------
25187
25188    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
25189    --  indicates an Intel manufactured processor
25190
25191    ------------------------------------
25192    --  Processor signature register  --
25193    ------------------------------------
25194
25195    --  a register type to hold the processor signature
25196
25197    type Processor_Signature is
25198       record
25199          Stepping       : Natural range 0 .. 15;
25200          Model          : Natural range 0 .. 15;
25201          Family         : Natural range 0 .. 15;
25202          Processor_Type : Natural range 0 .. 3;
25203          Reserved       : Natural range 0 .. 262143;
25204       end record;
25205
25206    for Processor_Signature use
25207       record
25208          Stepping       at 0 range  0 ..  3;
25209          Model          at 0 range  4 ..  7;
25210          Family         at 0 range  8 .. 11;
25211          Processor_Type at 0 range 12 .. 13;
25212          Reserved       at 0 range 14 .. 31;
25213       end record;
25214
25215    for Processor_Signature'Size use 32;
25216
25217    -----------------------------------
25218    --  Processor features register  --
25219    -----------------------------------
25220
25221    --  a processor register to hold the processor feature flags
25222
25223    type Processor_Features is
25224       record
25225          FPU    : Boolean;                --  floating point unit on chip
25226          VME    : Boolean;                --  virtual mode extension
25227          DE     : Boolean;                --  debugging extension
25228          PSE    : Boolean;                --  page size extension
25229          TSC    : Boolean;                --  time stamp counter
25230          MSR    : Boolean;                --  model specific registers
25231          PAE    : Boolean;                --  physical address extension
25232          MCE    : Boolean;                --  machine check extension
25233          CX8    : Boolean;                --  cmpxchg8 instruction
25234          APIC   : Boolean;                --  on-chip apic hardware
25235          Res_1  : Boolean;                --  reserved for extensions
25236          SEP    : Boolean;                --  fast system call
25237          MTRR   : Boolean;                --  memory type range registers
25238          PGE    : Boolean;                --  page global enable
25239          MCA    : Boolean;                --  machine check architecture
25240          CMOV   : Boolean;                --  conditional move supported
25241          PAT    : Boolean;                --  page attribute table
25242          PSE_36 : Boolean;                --  36-bit page size extension
25243          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
25244          MMX    : Boolean;                --  MMX technology supported
25245          FXSR   : Boolean;                --  fast FP save and restore
25246          Res_3  : Natural range 0 .. 127; --  reserved for extensions
25247       end record;
25248
25249    for Processor_Features use
25250       record
25251          FPU    at 0 range  0 ..  0;
25252          VME    at 0 range  1 ..  1;
25253          DE     at 0 range  2 ..  2;
25254          PSE    at 0 range  3 ..  3;
25255          TSC    at 0 range  4 ..  4;
25256          MSR    at 0 range  5 ..  5;
25257          PAE    at 0 range  6 ..  6;
25258          MCE    at 0 range  7 ..  7;
25259          CX8    at 0 range  8 ..  8;
25260          APIC   at 0 range  9 ..  9;
25261          Res_1  at 0 range 10 .. 10;
25262          SEP    at 0 range 11 .. 11;
25263          MTRR   at 0 range 12 .. 12;
25264          PGE    at 0 range 13 .. 13;
25265          MCA    at 0 range 14 .. 14;
25266          CMOV   at 0 range 15 .. 15;
25267          PAT    at 0 range 16 .. 16;
25268          PSE_36 at 0 range 17 .. 17;
25269          Res_2  at 0 range 18 .. 22;
25270          MMX    at 0 range 23 .. 23;
25271          FXSR   at 0 range 24 .. 24;
25272          Res_3  at 0 range 25 .. 31;
25273       end record;
25274
25275    for Processor_Features'Size use 32;
25276
25277    -------------------
25278    --  Subprograms  --
25279    -------------------
25280
25281    function Has_FPU return Boolean;
25282    --  return True if a FPU is found
25283    --  use only if CPUID is not supported
25284
25285    function Has_CPUID return Boolean;
25286    --  return True if the processor supports the CPUID instruction
25287
25288    function CPUID_Level return Natural;
25289    --  return the CPUID support level (0, 1 or 2)
25290    --  can only be called if the CPUID instruction is supported
25291
25292    function Vendor_ID return String;
25293    --  return the processor vendor identification string
25294    --  can only be called if the CPUID instruction is supported
25295
25296    function Signature return Processor_Signature;
25297    --  return the processor signature
25298    --  can only be called if the CPUID instruction is supported
25299
25300    function Features return Processor_Features;
25301    --  return the processors features
25302    --  can only be called if the CPUID instruction is supported
25303
25304 private
25305
25306    ------------------------
25307    --  EFLAGS bit names  --
25308    ------------------------
25309
25310    ID_Flag : constant Num_Bits := 21;
25311    --  ID flag bit
25312
25313 end Intel_CPU;
25314 @end smallexample
25315
25316 @c ---------------------------------------------------------------------------
25317 @node Intel_CPU Package Body
25318 @subsection @code{Intel_CPU} Package Body
25319 @cindex Intel_CPU package body
25320
25321 @smallexample @c adanocomment
25322 package body Intel_CPU is
25323
25324    ---------------------------
25325    --  Detect FPU presence  --
25326    ---------------------------
25327
25328    --  There is a FPU present if we can set values to the FPU Status
25329    --  and Control Words.
25330
25331    function Has_FPU return Boolean is
25332
25333       Register : Unsigned_16;
25334       --  processor register to store a word
25335
25336    begin
25337
25338       --  check if we can change the status word
25339       Asm (
25340
25341            --  the assembler code
25342            "finit"              & LF & HT &    --  reset status word
25343            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
25344            "fnstsw %0"          & LF & HT &    --  save status word
25345            "movw %%ax, %0",                    --  store status word
25346
25347            --  output stored in Register
25348            --  register must be a memory location
25349            Outputs => Unsigned_16'Asm_output ("=m", Register),
25350
25351            --  tell compiler that we used eax
25352            Clobber => "eax");
25353
25354       --  if the status word is zero, there is no FPU
25355       if Register = 0 then
25356          return False;   --  no status word
25357       end if;  --  check status word value
25358
25359       --  check if we can get the control word
25360       Asm (
25361
25362            --  the assembler code
25363            "fnstcw %0",   --  save the control word
25364
25365            --  output into Register
25366            --  register must be a memory location
25367            Outputs => Unsigned_16'Asm_output ("=m", Register));
25368
25369       --  check the relevant bits
25370       if (Register and 16#103F#) /= 16#003F# then
25371          return False;   --  no control word
25372       end if;  --  check control word value
25373
25374       --  FPU found
25375       return True;
25376
25377    end Has_FPU;
25378
25379    --------------------------------
25380    --  Detect CPUID instruction  --
25381    --------------------------------
25382
25383    --  The processor supports the CPUID instruction if it is possible
25384    --  to change the value of ID flag bit in the EFLAGS register.
25385
25386    function Has_CPUID return Boolean is
25387
25388       Original_Flags, Modified_Flags : Processor_Register;
25389       --  EFLAG contents before and after changing the ID flag
25390
25391    begin
25392
25393       --  try flipping the ID flag in the EFLAGS register
25394       Asm (
25395
25396            --  the assembler code
25397            "pushfl"               & LF & HT &     --  push EFLAGS on stack
25398            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
25399            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
25400            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
25401            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
25402            "popfl"                & LF & HT &     --  load EFLAGS register
25403            "pushfl"               & LF & HT &     --  push EFLAGS on stack
25404            "pop %1",                              --  save EFLAGS content
25405
25406            --  output values, may be anything
25407            --  Original_Flags is %0
25408            --  Modified_Flags is %1
25409            Outputs =>
25410               (Processor_Register'Asm_output ("=g", Original_Flags),
25411                Processor_Register'Asm_output ("=g", Modified_Flags)),
25412
25413            --  tell compiler eax is destroyed
25414            Clobber => "eax");
25415
25416       --  check if CPUID is supported
25417       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
25418          return True;   --  ID flag was modified
25419       else
25420          return False;  --  ID flag unchanged
25421       end if;  --  check for CPUID
25422
25423    end Has_CPUID;
25424
25425    -------------------------------
25426    --  Get CPUID support level  --
25427    -------------------------------
25428
25429    function CPUID_Level return Natural is
25430
25431       Level : Unsigned_32;
25432       --  returned support level
25433
25434    begin
25435
25436       --  execute CPUID, storing the results in the Level register
25437       Asm (
25438
25439            --  the assembler code
25440            "cpuid",    --  execute CPUID
25441
25442            --  zero is stored in eax
25443            --  returning the support level in eax
25444            Inputs => Unsigned_32'Asm_input ("a", 0),
25445
25446            --  eax is stored in Level
25447            Outputs => Unsigned_32'Asm_output ("=a", Level),
25448
25449            --  tell compiler ebx, ecx and edx registers are destroyed
25450            Clobber => "ebx, ecx, edx");
25451
25452       --  return the support level
25453       return Natural (Level);
25454
25455    end CPUID_Level;
25456
25457    --------------------------------
25458    --  Get CPU Vendor ID String  --
25459    --------------------------------
25460
25461    --  The vendor ID string is returned in the ebx, ecx and edx register
25462    --  after executing the CPUID instruction with eax set to zero.
25463    --  In case of a true Intel processor the string returned is
25464    --  "GenuineIntel"
25465
25466    function Vendor_ID return String is
25467
25468       Ebx, Ecx, Edx : Unsigned_Register;
25469       --  registers containing the vendor ID string
25470
25471       Vendor_ID : String (1 .. 12);
25472       -- the vendor ID string
25473
25474    begin
25475
25476       --  execute CPUID, storing the results in the processor registers
25477       Asm (
25478
25479            --  the assembler code
25480            "cpuid",    --  execute CPUID
25481
25482            --  zero stored in eax
25483            --  vendor ID string returned in ebx, ecx and edx
25484            Inputs => Unsigned_32'Asm_input ("a", 0),
25485
25486            --  ebx is stored in Ebx
25487            --  ecx is stored in Ecx
25488            --  edx is stored in Edx
25489            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
25490                        Unsigned_Register'Asm_output ("=c", Ecx),
25491                        Unsigned_Register'Asm_output ("=d", Edx)));
25492
25493       --  now build the vendor ID string
25494       Vendor_ID( 1) := Character'Val (Ebx.L1);
25495       Vendor_ID( 2) := Character'Val (Ebx.H1);
25496       Vendor_ID( 3) := Character'Val (Ebx.L2);
25497       Vendor_ID( 4) := Character'Val (Ebx.H2);
25498       Vendor_ID( 5) := Character'Val (Edx.L1);
25499       Vendor_ID( 6) := Character'Val (Edx.H1);
25500       Vendor_ID( 7) := Character'Val (Edx.L2);
25501       Vendor_ID( 8) := Character'Val (Edx.H2);
25502       Vendor_ID( 9) := Character'Val (Ecx.L1);
25503       Vendor_ID(10) := Character'Val (Ecx.H1);
25504       Vendor_ID(11) := Character'Val (Ecx.L2);
25505       Vendor_ID(12) := Character'Val (Ecx.H2);
25506
25507       --  return string
25508       return Vendor_ID;
25509
25510    end Vendor_ID;
25511
25512    -------------------------------
25513    --  Get processor signature  --
25514    -------------------------------
25515
25516    function Signature return Processor_Signature is
25517
25518       Result : Processor_Signature;
25519       --  processor signature returned
25520
25521    begin
25522
25523       --  execute CPUID, storing the results in the Result variable
25524       Asm (
25525
25526            --  the assembler code
25527            "cpuid",    --  execute CPUID
25528
25529            --  one is stored in eax
25530            --  processor signature returned in eax
25531            Inputs => Unsigned_32'Asm_input ("a", 1),
25532
25533            --  eax is stored in Result
25534            Outputs => Processor_Signature'Asm_output ("=a", Result),
25535
25536            --  tell compiler that ebx, ecx and edx are also destroyed
25537            Clobber => "ebx, ecx, edx");
25538
25539       --  return processor signature
25540       return Result;
25541
25542    end Signature;
25543
25544    ------------------------------
25545    --  Get processor features  --
25546    ------------------------------
25547
25548    function Features return Processor_Features is
25549
25550       Result : Processor_Features;
25551       --  processor features returned
25552
25553    begin
25554
25555       --  execute CPUID, storing the results in the Result variable
25556       Asm (
25557
25558            --  the assembler code
25559            "cpuid",    --  execute CPUID
25560
25561            --  one stored in eax
25562            --  processor features returned in edx
25563            Inputs => Unsigned_32'Asm_input ("a", 1),
25564
25565            --  edx is stored in Result
25566            Outputs => Processor_Features'Asm_output ("=d", Result),
25567
25568            --  tell compiler that ebx and ecx are also destroyed
25569            Clobber => "ebx, ecx");
25570
25571       --  return processor signature
25572       return Result;
25573
25574    end Features;
25575
25576 end Intel_CPU;
25577 @end smallexample
25578 @c END OF INLINE ASSEMBLER CHAPTER
25579 @c ===============================
25580
25581
25582
25583 @c ***********************************
25584 @c * Compatibility and Porting Guide *
25585 @c ***********************************
25586 @node Compatibility and Porting Guide
25587 @appendix Compatibility and Porting Guide
25588
25589 @noindent
25590 This chapter describes the compatibility issues that may arise between
25591 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
25592 can expedite porting
25593 applications developed in other Ada environments.
25594
25595 @menu
25596 * Compatibility with Ada 83::
25597 * Implementation-dependent characteristics::
25598 * Compatibility with DEC Ada 83::
25599 * Compatibility with Other Ada 95 Systems::
25600 * Representation Clauses::
25601 @end menu
25602
25603 @node Compatibility with Ada 83
25604 @section Compatibility with Ada 83
25605 @cindex Compatibility (between Ada 83 and Ada 95)
25606
25607 @noindent
25608 Ada 95 is designed to be highly upwards compatible with Ada 83.  In
25609 particular, the design intention is that the difficulties associated
25610 with moving from Ada 83 to Ada 95 should be no greater than those
25611 that occur when moving from one Ada 83 system to another.
25612
25613 However, there are a number of points at which there are minor
25614 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25615 full details of these issues,
25616 and should be consulted for a complete treatment.
25617 In practice the
25618 following subsections treat the most likely issues to be encountered.
25619
25620 @menu
25621 * Legal Ada 83 programs that are illegal in Ada 95::
25622 * More deterministic semantics::
25623 * Changed semantics::
25624 * Other language compatibility issues::
25625 @end menu
25626
25627 @node Legal Ada 83 programs that are illegal in Ada 95
25628 @subsection Legal Ada 83 programs that are illegal in Ada 95
25629
25630 @table @asis
25631 @item Character literals
25632 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25633 @code{Wide_Character} as a new predefined character type, some uses of
25634 character literals that were legal in Ada 83 are illegal in Ada 95.
25635 For example:
25636 @smallexample @c ada
25637    for Char in 'A' .. 'Z' loop ... end loop;
25638 @end smallexample
25639 @noindent
25640 The problem is that @code{'A'} and @code{'Z'} could be from either
25641 @code{Character} or @code{Wide_Character}.  The simplest correction
25642 is to make the type explicit; e.g.:
25643 @smallexample @c ada
25644    for Char in Character range 'A' .. 'Z' loop ... end loop;
25645 @end smallexample
25646
25647 @item New reserved words
25648 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25649 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25650 Existing Ada 83 code using any of these identifiers must be edited to
25651 use some alternative name.
25652
25653 @item Freezing rules
25654 The rules in Ada 95 are slightly different with regard to the point at
25655 which entities are frozen, and representation pragmas and clauses are
25656 not permitted past the freeze point.  This shows up most typically in
25657 the form of an error message complaining that a representation item
25658 appears too late, and the appropriate corrective action is to move
25659 the item nearer to the declaration of the entity to which it refers.
25660
25661 A particular case is that representation pragmas
25662 @ifset vms
25663 (including the
25664 extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure})
25665 @end ifset
25666 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25667 declaration must be introduced to which the pragma can be applied.
25668
25669 @item Optional bodies for library packages
25670 In Ada 83, a package that did not require a package body was nevertheless
25671 allowed to have one.  This lead to certain surprises in compiling large
25672 systems (situations in which the body could be unexpectedly ignored by the
25673 binder).  In Ada 95, if a package does not require a body then it is not
25674 permitted to have a body.  To fix this problem, simply remove a redundant
25675 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25676 into the spec that makes the body required.  One approach is to add a private
25677 part to the package declaration (if necessary), and define a parameterless
25678 procedure called @code{Requires_Body}, which must then be given a dummy
25679 procedure body in the package body, which then becomes required.
25680 Another approach (assuming that this does not introduce elaboration
25681 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25682 since one effect of this pragma is to require the presence of a package body.
25683
25684 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25685 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25686 @code{Constraint_Error}.
25687 This means that it is illegal to have separate exception handlers for
25688 the two exceptions.  The fix is simply to remove the handler for the
25689 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25690 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25691
25692 @item Indefinite subtypes in generics
25693 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25694 as the actual for a generic formal private type, but then the instantiation
25695 would be illegal if there were any instances of declarations of variables
25696 of this type in the generic body.  In Ada 95, to avoid this clear violation
25697 of the methodological principle known as the ``contract model'',
25698 the generic declaration explicitly indicates whether
25699 or not such instantiations are permitted.  If a generic formal parameter
25700 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25701 type name, then it can be instantiated with indefinite types, but no
25702 stand-alone variables can be declared of this type.  Any attempt to declare
25703 such a variable will result in an illegality at the time the generic is
25704 declared.  If the @code{(<>)} notation is not used, then it is illegal
25705 to instantiate the generic with an indefinite type.
25706 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25707 It will show up as a compile time error, and
25708 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25709 @end table
25710
25711 @node More deterministic semantics
25712 @subsection More deterministic semantics
25713
25714 @table @asis
25715 @item Conversions
25716 Conversions from real types to integer types round away from 0.  In Ada 83
25717 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
25718 implementation freedom was intended to support unbiased rounding in
25719 statistical applications, but in practice it interfered with portability.
25720 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25721 is required.  Numeric code may be affected by this change in semantics.
25722 Note, though, that this issue is no worse than already existed in Ada 83
25723 when porting code from one vendor to another.
25724
25725 @item Tasking
25726 The Real-Time Annex introduces a set of policies that define the behavior of
25727 features that were implementation dependent in Ada 83, such as the order in
25728 which open select branches are executed.
25729 @end table
25730
25731 @node Changed semantics
25732 @subsection Changed semantics
25733
25734 @noindent
25735 The worst kind of incompatibility is one where a program that is legal in
25736 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25737 possible in Ada 83.  Fortunately this is extremely rare, but the one
25738 situation that you should be alert to is the change in the predefined type
25739 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25740
25741 @table @asis
25742 @item range of @code{Character}
25743 The range of @code{Standard.Character} is now the full 256 characters
25744 of Latin-1, whereas in most Ada 83 implementations it was restricted
25745 to 128 characters. Although some of the effects of
25746 this change will be manifest in compile-time rejection of legal
25747 Ada 83 programs it is possible for a working Ada 83 program to have
25748 a different effect in Ada 95, one that was not permitted in Ada 83.
25749 As an example, the expression
25750 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25751 delivers @code{255} as its value.
25752 In general, you should look at the logic of any
25753 character-processing Ada 83 program and see whether it needs to be adapted
25754 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
25755 character handling package that may be relevant if code needs to be adapted
25756 to account for the additional Latin-1 elements.
25757 The desirable fix is to
25758 modify the program to accommodate the full character set, but in some cases
25759 it may be convenient to define a subtype or derived type of Character that
25760 covers only the restricted range.
25761 @cindex Latin-1
25762 @end table
25763
25764 @node Other language compatibility issues
25765 @subsection Other language compatibility issues
25766 @table @asis
25767 @item @option{-gnat83 switch}
25768 All implementations of GNAT provide a switch that causes GNAT to operate
25769 in Ada 83 mode.  In this mode, some but not all compatibility problems
25770 of the type described above are handled automatically.  For example, the
25771 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
25772 However,
25773 in practice, it is usually advisable to make the necessary modifications
25774 to the program to remove the need for using this switch.
25775 See @ref{Compiling Ada 83 Programs}.
25776
25777 @item Support for removed Ada 83 pragmas and attributes
25778 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
25779 generally because they have been replaced by other mechanisms.  Ada 95
25780 compilers are allowed, but not required, to implement these missing
25781 elements.  In contrast with some other Ada 95 compilers, GNAT implements all
25782 such pragmas and attributes, eliminating this compatibility concern.  These
25783 include @code{pragma Interface} and the floating point type attributes
25784 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25785 @end table
25786
25787
25788 @node Implementation-dependent characteristics
25789 @section Implementation-dependent characteristics
25790 @noindent
25791 Although the Ada language defines the semantics of each construct as
25792 precisely as practical, in some situations (for example for reasons of
25793 efficiency, or where the effect is heavily dependent on the host or target
25794 platform) the implementation is allowed some freedom.  In porting Ada 83
25795 code to GNAT, you need to be aware of whether / how the existing code
25796 exercised such implementation dependencies.  Such characteristics fall into
25797 several categories, and GNAT offers specific support in assisting the
25798 transition from certain Ada 83 compilers.
25799
25800 @menu
25801 * Implementation-defined pragmas::
25802 * Implementation-defined attributes::
25803 * Libraries::
25804 * Elaboration order::
25805 * Target-specific aspects::
25806 @end menu
25807
25808
25809 @node Implementation-defined pragmas
25810 @subsection Implementation-defined pragmas
25811
25812 @noindent
25813 Ada compilers are allowed to supplement the language-defined pragmas, and
25814 these are a potential source of non-portability.  All GNAT-defined pragmas
25815 are described in the GNAT Reference Manual, and these include several that
25816 are specifically intended to correspond to other vendors' Ada 83 pragmas.
25817 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25818 For
25819 compatibility with DEC Ada 83, GNAT supplies the pragmas
25820 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25821 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25822 and @code{Volatile}.
25823 Other relevant pragmas include @code{External} and @code{Link_With}.
25824 Some vendor-specific
25825 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25826 recognized, thus
25827 avoiding compiler rejection of units that contain such pragmas; they are not
25828 relevant in a GNAT context and hence are not otherwise implemented.
25829
25830 @node Implementation-defined attributes
25831 @subsection Implementation-defined attributes
25832
25833 Analogous to pragmas, the set of attributes may be extended by an
25834 implementation.  All GNAT-defined attributes are described in the
25835 @cite{GNAT Reference Manual}, and these include several that are specifically
25836 intended
25837 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
25838 the attribute @code{VADS_Size} may be useful.  For compatibility with DEC
25839 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25840 @code{Type_Class}.
25841
25842 @node Libraries
25843 @subsection Libraries
25844 @noindent
25845 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
25846 code uses vendor-specific libraries then there are several ways to manage
25847 this in Ada 95:
25848 @enumerate
25849 @item
25850 If the source code for the libraries (specifications and bodies) are
25851 available, then the libraries can be migrated in the same way as the
25852 application.
25853 @item
25854 If the source code for the specifications but not the bodies are
25855 available, then you can reimplement the bodies.
25856 @item
25857 Some new Ada 95 features obviate the need for library support.  For
25858 example most Ada 83 vendors supplied a package for unsigned integers.  The
25859 Ada 95 modular type feature is the preferred way to handle this need, so
25860 instead of migrating or reimplementing the unsigned integer package it may
25861 be preferable to retrofit the application using modular types.
25862 @end enumerate
25863
25864 @node Elaboration order
25865 @subsection Elaboration order
25866 @noindent
25867 The implementation can choose any elaboration order consistent with the unit
25868 dependency relationship.  This freedom means that some orders can result in
25869 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25870 to invoke a subprogram its body has been elaborated, or to instantiate a
25871 generic before the generic body has been elaborated.  By default GNAT
25872 attempts to choose a safe order (one that will not encounter access before
25873 elaboration problems) by implicitly inserting Elaborate_All pragmas where
25874 needed.  However, this can lead to the creation of elaboration circularities
25875 and a resulting rejection of the program by gnatbind.  This issue is
25876 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25877 In brief, there are several
25878 ways to deal with this situation:
25879
25880 @itemize @bullet
25881 @item
25882 Modify the program to eliminate the circularities, e.g. by moving
25883 elaboration-time code into explicitly-invoked procedures
25884 @item
25885 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25886 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25887 @code{Elaborate_All}
25888 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25889 (by selectively suppressing elaboration checks via pragma
25890 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25891 @end itemize
25892
25893 @node Target-specific aspects
25894 @subsection Target-specific aspects
25895 @noindent
25896 Low-level applications need to deal with machine addresses, data
25897 representations, interfacing with assembler code, and similar issues.  If
25898 such an Ada 83 application is being ported to different target hardware (for
25899 example where the byte endianness has changed) then you will need to
25900 carefully examine the program logic; the porting effort will heavily depend
25901 on the robustness of the original design.  Moreover, Ada 95 is sometimes
25902 incompatible with typical Ada 83 compiler practices regarding implicit
25903 packing, the meaning of the Size attribute, and the size of access values.
25904 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25905
25906
25907 @node Compatibility with Other Ada 95 Systems
25908 @section Compatibility with Other Ada 95 Systems
25909
25910 @noindent
25911 Providing that programs avoid the use of implementation dependent and
25912 implementation defined features of Ada 95, as documented in the Ada 95
25913 reference manual, there should be a high degree of portability between
25914 GNAT and other Ada 95 systems.  The following are specific items which
25915 have proved troublesome in moving GNAT programs to other Ada 95
25916 compilers, but do not affect porting code to GNAT@.
25917
25918 @table @asis
25919 @item Ada 83 Pragmas and Attributes
25920 Ada 95 compilers are allowed, but not required, to implement the missing
25921 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25922 GNAT implements all such pragmas and attributes, eliminating this as
25923 a compatibility concern, but some other Ada 95 compilers reject these
25924 pragmas and attributes.
25925
25926 @item Special-needs Annexes
25927 GNAT implements the full set of special needs annexes.  At the
25928 current time, it is the only Ada 95 compiler to do so.  This means that
25929 programs making use of these features may not be portable to other Ada
25930 95 compilation systems.
25931
25932 @item Representation Clauses
25933 Some other Ada 95 compilers implement only the minimal set of
25934 representation clauses required by the Ada 95 reference manual.  GNAT goes
25935 far beyond this minimal set, as described in the next section.
25936 @end table
25937
25938 @node Representation Clauses
25939 @section Representation Clauses
25940
25941 @noindent
25942 The Ada 83 reference manual was quite vague in describing both the minimal
25943 required implementation of representation clauses, and also their precise
25944 effects.  The Ada 95 reference manual is much more explicit, but the minimal
25945 set of capabilities required in Ada 95 is quite limited.
25946
25947 GNAT implements the full required set of capabilities described in the
25948 Ada 95 reference manual, but also goes much beyond this, and in particular
25949 an effort has been made to be compatible with existing Ada 83 usage to the
25950 greatest extent possible.
25951
25952 A few cases exist in which Ada 83 compiler behavior is incompatible with
25953 requirements in the Ada 95 reference manual.  These are instances of
25954 intentional or accidental dependence on specific implementation dependent
25955 characteristics of these Ada 83 compilers.  The following is a list of
25956 the cases most likely to arise in existing legacy Ada 83 code.
25957
25958 @table @asis
25959 @item Implicit Packing
25960 Some Ada 83 compilers allowed a Size specification to cause implicit
25961 packing of an array or record.  This could cause expensive implicit
25962 conversions for change of representation in the presence of derived
25963 types, and the Ada design intends to avoid this possibility.
25964 Subsequent AI's were issued to make it clear that such implicit
25965 change of representation in response to a Size clause is inadvisable,
25966 and this recommendation is represented explicitly in the Ada 95 RM
25967 as implementation advice that is followed by GNAT@.
25968 The problem will show up as an error
25969 message rejecting the size clause.  The fix is simply to provide
25970 the explicit pragma @code{Pack}, or for more fine tuned control, provide
25971 a Component_Size clause.
25972
25973 @item Meaning of Size Attribute
25974 The Size attribute in Ada 95 for discrete types is defined as being the
25975 minimal number of bits required to hold values of the type.  For example,
25976 on a 32-bit machine, the size of Natural will typically be 31 and not
25977 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
25978 some 32 in this situation.  This problem will usually show up as a compile
25979 time error, but not always.  It is a good idea to check all uses of the
25980 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
25981 Object_Size can provide a useful way of duplicating the behavior of
25982 some Ada 83 compiler systems.
25983
25984 @item Size of Access Types
25985 A common assumption in Ada 83 code is that an access type is in fact a pointer,
25986 and that therefore it will be the same size as a System.Address value.  This
25987 assumption is true for GNAT in most cases with one exception.  For the case of
25988 a pointer to an unconstrained array type (where the bounds may vary from one
25989 value of the access type to another), the default is to use a ``fat pointer'',
25990 which is represented as two separate pointers, one to the bounds, and one to
25991 the array.  This representation has a number of advantages, including improved
25992 efficiency.  However, it may cause some difficulties in porting existing Ada 83
25993 code which makes the assumption that, for example, pointers fit in 32 bits on
25994 a machine with 32-bit addressing.
25995
25996 To get around this problem, GNAT also permits the use of ``thin pointers'' for
25997 access types in this case (where the designated type is an unconstrained array
25998 type).  These thin pointers are indeed the same size as a System.Address value.
25999 To specify a thin pointer, use a size clause for the type, for example:
26000
26001 @smallexample @c ada
26002 type X is access all String;
26003 for X'Size use Standard'Address_Size;
26004 @end smallexample
26005
26006 @noindent
26007 which will cause the type X to be represented using a single pointer.
26008 When using this representation, the bounds are right behind the array.
26009 This representation is slightly less efficient, and does not allow quite
26010 such flexibility in the use of foreign pointers or in using the
26011 Unrestricted_Access attribute to create pointers to non-aliased objects.
26012 But for any standard portable use of the access type it will work in
26013 a functionally correct manner and allow porting of existing code.
26014 Note that another way of forcing a thin pointer representation
26015 is to use a component size clause for the element size in an array,
26016 or a record representation clause for an access field in a record.
26017 @end table
26018
26019 @node Compatibility with DEC Ada 83
26020 @section Compatibility with DEC Ada 83
26021
26022 @noindent
26023 The VMS version of GNAT fully implements all the pragmas and attributes
26024 provided by DEC Ada 83, as well as providing the standard DEC Ada 83
26025 libraries, including Starlet.  In addition, data layouts and parameter
26026 passing conventions are highly compatible.  This means that porting
26027 existing DEC Ada 83 code to GNAT in VMS systems should be easier than
26028 most other porting efforts.  The following are some of the most
26029 significant differences between GNAT and DEC Ada 83.
26030
26031 @table @asis
26032 @item Default floating-point representation
26033 In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83,
26034 it is VMS format.  GNAT does implement the necessary pragmas
26035 (Long_Float, Float_Representation) for changing this default.
26036
26037 @item System
26038 The package System in GNAT exactly corresponds to the definition in the
26039 Ada 95 reference manual, which means that it excludes many of the
26040 DEC Ada 83 extensions.  However, a separate package Aux_DEC is provided
26041 that contains the additional definitions, and a special pragma,
26042 Extend_System allows this package to be treated transparently as an
26043 extension of package System.
26044
26045 @item To_Address
26046 The definitions provided by Aux_DEC are exactly compatible with those
26047 in the DEC Ada 83 version of System, with one exception.
26048 DEC Ada provides the following declarations:
26049
26050 @smallexample @c ada
26051 TO_ADDRESS (INTEGER)
26052 TO_ADDRESS (UNSIGNED_LONGWORD)
26053 TO_ADDRESS (universal_integer)
26054 @end smallexample
26055
26056 @noindent
26057 The version of TO_ADDRESS taking a universal integer argument is in fact
26058 an extension to Ada 83 not strictly compatible with the reference manual.
26059 In GNAT, we are constrained to be exactly compatible with the standard,
26060 and this means we cannot provide this capability.  In DEC Ada 83, the
26061 point of this definition is to deal with a call like:
26062
26063 @smallexample @c ada
26064 TO_ADDRESS (16#12777#);
26065 @end smallexample
26066
26067 @noindent
26068 Normally, according to the Ada 83 standard, one would expect this to be
26069 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26070 of TO_ADDRESS@.  However, in DEC Ada 83, there is no ambiguity, since the
26071 definition using universal_integer takes precedence.
26072
26073 In GNAT, since the version with universal_integer cannot be supplied, it is
26074 not possible to be 100% compatible.  Since there are many programs using
26075 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26076 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26077 declarations provided in the GNAT version of AUX_Dec are:
26078
26079 @smallexample @c ada
26080 function To_Address (X : Integer) return Address;
26081 pragma Pure_Function (To_Address);
26082
26083 function To_Address_Long (X : Unsigned_Longword)
26084  return Address;
26085 pragma Pure_Function (To_Address_Long);
26086 @end smallexample
26087
26088 @noindent
26089 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26090 change the name to TO_ADDRESS_LONG@.
26091
26092 @item Task_Id values
26093 The Task_Id values assigned will be different in the two systems, and GNAT
26094 does not provide a specified value for the Task_Id of the environment task,
26095 which in GNAT is treated like any other declared task.
26096 @end table
26097
26098 For full details on these and other less significant compatibility issues,
26099 see appendix E of the Digital publication entitled @cite{DEC Ada, Technical
26100 Overview and Comparison on DIGITAL Platforms}.
26101
26102 For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and
26103 attributes are recognized, although only a subset of them can sensibly
26104 be implemented.  The description of pragmas in this reference manual
26105 indicates whether or not they are applicable to non-VMS systems.
26106
26107
26108
26109 @ifset unw
26110 @node Microsoft Windows Topics
26111 @appendix Microsoft Windows Topics
26112 @cindex Windows NT
26113 @cindex Windows 95
26114 @cindex Windows 98
26115
26116 @noindent
26117 This chapter describes topics that are specific to the Microsoft Windows
26118 platforms (NT, 2000, and XP Professional).
26119
26120 @menu
26121 * Using GNAT on Windows::
26122 * Using a network installation of GNAT::
26123 * CONSOLE and WINDOWS subsystems::
26124 * Temporary Files::
26125 * Mixed-Language Programming on Windows::
26126 * Windows Calling Conventions::
26127 * Introduction to Dynamic Link Libraries (DLLs)::
26128 * Using DLLs with GNAT::
26129 * Building DLLs with GNAT::
26130 * Building DLLs with GNAT Project files::
26131 * Building DLLs with gnatdll::
26132 * GNAT and Windows Resources::
26133 * Debugging a DLL::
26134 * GNAT and COM/DCOM Objects::
26135 @end menu
26136
26137 @node Using GNAT on Windows
26138 @section Using GNAT on Windows
26139
26140 @noindent
26141 One of the strengths of the GNAT technology is that its tool set
26142 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
26143 @code{gdb} debugger, etc.) is used in the same way regardless of the
26144 platform.
26145
26146 On Windows this tool set is complemented by a number of Microsoft-specific
26147 tools that have been provided to facilitate interoperability with Windows
26148 when this is required. With these tools:
26149
26150 @itemize @bullet
26151
26152 @item
26153 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26154 subsystems.
26155
26156 @item
26157 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26158 relocatable and non-relocatable DLLs are supported).
26159
26160 @item
26161 You can build Ada DLLs for use in other applications. These applications
26162 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26163 relocatable and non-relocatable Ada DLLs are supported.
26164
26165 @item
26166 You can include Windows resources in your Ada application.
26167
26168 @item
26169 You can use or create COM/DCOM objects.
26170 @end itemize
26171
26172 @noindent
26173 Immediately below are listed all known general GNAT-for-Windows restrictions.
26174 Other restrictions about specific features like Windows Resources and DLLs
26175 are listed in separate sections below.
26176
26177 @itemize @bullet
26178
26179 @item
26180 It is not possible to use @code{GetLastError} and @code{SetLastError}
26181 when tasking, protected records, or exceptions are used. In these
26182 cases, in order to implement Ada semantics, the GNAT run-time system
26183 calls certain Win32 routines that set the last error variable to 0 upon
26184 success. It should be possible to use @code{GetLastError} and
26185 @code{SetLastError} when tasking, protected record, and exception
26186 features are not used, but it is not guaranteed to work.
26187
26188 @item
26189 It is not possible to link against Microsoft libraries except for
26190 import libraries. The library must be built to be compatible with
26191 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
26192 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
26193 not be compatible with the GNAT runtime. Even if the library is
26194 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
26195
26196 @item
26197 When the compilation environment is located on FAT32 drives, users may
26198 experience recompilations of the source files that have not changed if
26199 Daylight Saving Time (DST) state has changed since the last time files
26200 were compiled. NTFS drives do not have this problem.
26201
26202 @item
26203 No components of the GNAT toolset use any entries in the Windows
26204 registry. The only entries that can be created are file associations and
26205 PATH settings, provided the user has chosen to create them at installation
26206 time, as well as some minimal book-keeping information needed to correctly
26207 uninstall or integrate different GNAT products.
26208 @end itemize
26209
26210 @node Using a network installation of GNAT
26211 @section Using a network installation of GNAT
26212
26213 @noindent
26214 Make sure the system on which GNAT is installed is accessible from the
26215 current machine, i.e. the install location is shared over the network.
26216 Shared resources are accessed on Windows by means of UNC paths, which
26217 have the format @code{\\server\sharename\path}
26218
26219 In order to use such a network installation, simply add the UNC path of the
26220 @file{bin} directory of your GNAT installation in front of your PATH. For
26221 example, if GNAT is installed in @file{\GNAT} directory of a share location
26222 called @file{c-drive} on a machine @file{LOKI}, the following command will
26223 make it available:
26224
26225 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26226
26227 Be aware that every compilation using the network installation results in the
26228 transfer of large amounts of data across the network and will likely cause
26229 serious performance penalty.
26230
26231 @node CONSOLE and WINDOWS subsystems
26232 @section CONSOLE and WINDOWS subsystems
26233 @cindex CONSOLE Subsystem
26234 @cindex WINDOWS Subsystem
26235 @cindex -mwindows
26236
26237 @noindent
26238 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26239 (which is the default subsystem) will always create a console when
26240 launching the application. This is not something desirable when the
26241 application has a Windows GUI. To get rid of this console the
26242 application must be using the @code{WINDOWS} subsystem. To do so
26243 the @option{-mwindows} linker option must be specified.
26244
26245 @smallexample
26246 $ gnatmake winprog -largs -mwindows
26247 @end smallexample
26248
26249 @node Temporary Files
26250 @section Temporary Files
26251 @cindex Temporary files
26252
26253 @noindent
26254 It is possible to control where temporary files gets created by setting
26255 the TMP environment variable. The file will be created:
26256
26257 @itemize
26258 @item Under the directory pointed to by the TMP environment variable if
26259 this directory exists.
26260
26261 @item Under c:\temp, if the TMP environment variable is not set (or not
26262 pointing to a directory) and if this directory exists.
26263
26264 @item Under the current working directory otherwise.
26265 @end itemize
26266
26267 @noindent
26268 This allows you to determine exactly where the temporary
26269 file will be created. This is particularly useful in networked
26270 environments where you may not have write access to some
26271 directories.
26272
26273 @node Mixed-Language Programming on Windows
26274 @section Mixed-Language Programming on Windows
26275
26276 @noindent
26277 Developing pure Ada applications on Windows is no different than on
26278 other GNAT-supported platforms. However, when developing or porting an
26279 application that contains a mix of Ada and C/C++, the choice of your
26280 Windows C/C++ development environment conditions your overall
26281 interoperability strategy.
26282
26283 If you use @code{gcc} to compile the non-Ada part of your application,
26284 there are no Windows-specific restrictions that affect the overall
26285 interoperability with your Ada code. If you plan to use
26286 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
26287 the following limitations:
26288
26289 @itemize @bullet
26290 @item
26291 You cannot link your Ada code with an object or library generated with
26292 Microsoft tools if these use the @code{.tls} section (Thread Local
26293 Storage section) since the GNAT linker does not yet support this section.
26294
26295 @item
26296 You cannot link your Ada code with an object or library generated with
26297 Microsoft tools if these use I/O routines other than those provided in
26298 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
26299 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
26300 libraries can cause a conflict with @code{msvcrt.dll} services. For
26301 instance Visual C++ I/O stream routines conflict with those in
26302 @code{msvcrt.dll}.
26303 @end itemize
26304
26305 @noindent
26306 If you do want to use the Microsoft tools for your non-Ada code and hit one
26307 of the above limitations, you have two choices:
26308
26309 @enumerate
26310 @item
26311 Encapsulate your non Ada code in a DLL to be linked with your Ada
26312 application. In this case, use the Microsoft or whatever environment to
26313 build the DLL and use GNAT to build your executable
26314 (@pxref{Using DLLs with GNAT}).
26315
26316 @item
26317 Or you can encapsulate your Ada code in a DLL to be linked with the
26318 other part of your application. In this case, use GNAT to build the DLL
26319 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
26320 environment to build your executable.
26321 @end enumerate
26322
26323 @node Windows Calling Conventions
26324 @section Windows Calling Conventions
26325 @findex Stdcall
26326 @findex APIENTRY
26327
26328 @menu
26329 * C Calling Convention::
26330 * Stdcall Calling Convention::
26331 * DLL Calling Convention::
26332 @end menu
26333
26334 @noindent
26335 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26336 (callee), there are several ways to push @code{G}'s parameters on the
26337 stack and there are several possible scenarios to clean up the stack
26338 upon @code{G}'s return. A calling convention is an agreed upon software
26339 protocol whereby the responsibilities between the caller (@code{F}) and
26340 the callee (@code{G}) are clearly defined. Several calling conventions
26341 are available for Windows:
26342
26343 @itemize @bullet
26344 @item
26345 @code{C} (Microsoft defined)
26346
26347 @item
26348 @code{Stdcall} (Microsoft defined)
26349
26350 @item
26351 @code{DLL} (GNAT specific)
26352 @end itemize
26353
26354 @node C Calling Convention
26355 @subsection @code{C} Calling Convention
26356
26357 @noindent
26358 This is the default calling convention used when interfacing to C/C++
26359 routines compiled with either @code{gcc} or Microsoft Visual C++.
26360
26361 In the @code{C} calling convention subprogram parameters are pushed on the
26362 stack by the caller from right to left. The caller itself is in charge of
26363 cleaning up the stack after the call. In addition, the name of a routine
26364 with @code{C} calling convention is mangled by adding a leading underscore.
26365
26366 The name to use on the Ada side when importing (or exporting) a routine
26367 with @code{C} calling convention is the name of the routine. For
26368 instance the C function:
26369
26370 @smallexample
26371 int get_val (long);
26372 @end smallexample
26373
26374 @noindent
26375 should be imported from Ada as follows:
26376
26377 @smallexample @c ada
26378 @group
26379 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26380 pragma Import (C, Get_Val, External_Name => "get_val");
26381 @end group
26382 @end smallexample
26383
26384 @noindent
26385 Note that in this particular case the @code{External_Name} parameter could
26386 have been omitted since, when missing, this parameter is taken to be the
26387 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26388 is missing, as in the above example, this parameter is set to be the
26389 @code{External_Name} with a leading underscore.
26390
26391 When importing a variable defined in C, you should always use the @code{C}
26392 calling convention unless the object containing the variable is part of a
26393 DLL (in which case you should use the @code{DLL} calling convention,
26394 @pxref{DLL Calling Convention}).
26395
26396 @node Stdcall Calling Convention
26397 @subsection @code{Stdcall} Calling Convention
26398
26399 @noindent
26400 This convention, which was the calling convention used for Pascal
26401 programs, is used by Microsoft for all the routines in the Win32 API for
26402 efficiency reasons. It must be used to import any routine for which this
26403 convention was specified.
26404
26405 In the @code{Stdcall} calling convention subprogram parameters are pushed
26406 on the stack by the caller from right to left. The callee (and not the
26407 caller) is in charge of cleaning the stack on routine exit. In addition,
26408 the name of a routine with @code{Stdcall} calling convention is mangled by
26409 adding a leading underscore (as for the @code{C} calling convention) and a
26410 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
26411 bytes) of the parameters passed to the routine.
26412
26413 The name to use on the Ada side when importing a C routine with a
26414 @code{Stdcall} calling convention is the name of the C routine. The leading
26415 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
26416 the compiler. For instance the Win32 function:
26417
26418 @smallexample
26419 @b{APIENTRY} int get_val (long);
26420 @end smallexample
26421
26422 @noindent
26423 should be imported from Ada as follows:
26424
26425 @smallexample @c ada
26426 @group
26427 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26428 pragma Import (Stdcall, Get_Val);
26429 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26430 @end group
26431 @end smallexample
26432
26433 @noindent
26434 As for the @code{C} calling convention, when the @code{External_Name}
26435 parameter is missing, it is taken to be the name of the Ada entity in lower
26436 case. If instead of writing the above import pragma you write:
26437
26438 @smallexample @c ada
26439 @group
26440 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26441 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26442 @end group
26443 @end smallexample
26444
26445 @noindent
26446 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26447 of specifying the @code{External_Name} parameter you specify the
26448 @code{Link_Name} as in the following example:
26449
26450 @smallexample @c ada
26451 @group
26452 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26453 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26454 @end group
26455 @end smallexample
26456
26457 @noindent
26458 then the imported routine is @code{retrieve_val@@4}, that is, there is no
26459 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
26460 added at the end of the @code{Link_Name} by the compiler.
26461
26462 @noindent
26463 Note, that in some special cases a DLL's entry point name lacks a trailing
26464 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
26465 The @code{gnatdll} tool, which creates the import library for the DLL, is able
26466 to handle those cases (see the description of the switches in
26467 @pxref{Using gnatdll} section).
26468
26469 @node DLL Calling Convention
26470 @subsection @code{DLL} Calling Convention
26471
26472 @noindent
26473 This convention, which is GNAT-specific, must be used when you want to
26474 import in Ada a variables defined in a DLL. For functions and procedures
26475 this convention is equivalent to the @code{Stdcall} convention. As an
26476 example, if a DLL contains a variable defined as:
26477
26478 @smallexample
26479 int my_var;
26480 @end smallexample
26481
26482 @noindent
26483 then, to access this variable from Ada you should write:
26484
26485 @smallexample @c ada
26486 @group
26487 My_Var : Interfaces.C.int;
26488 pragma Import (DLL, My_Var);
26489 @end group
26490 @end smallexample
26491
26492 The remarks concerning the @code{External_Name} and @code{Link_Name}
26493 parameters given in the previous sections equally apply to the @code{DLL}
26494 calling convention.
26495
26496 @node Introduction to Dynamic Link Libraries (DLLs)
26497 @section Introduction to Dynamic Link Libraries (DLLs)
26498 @findex DLL
26499
26500 @noindent
26501 A Dynamically Linked Library (DLL) is a library that can be shared by
26502 several applications running under Windows. A DLL can contain any number of
26503 routines and variables.
26504
26505 One advantage of DLLs is that you can change and enhance them without
26506 forcing all the applications that depend on them to be relinked or
26507 recompiled. However, you should be aware than all calls to DLL routines are
26508 slower since, as you will understand below, such calls are indirect.
26509
26510 To illustrate the remainder of this section, suppose that an application
26511 wants to use the services of a DLL @file{API.dll}. To use the services
26512 provided by @file{API.dll} you must statically link against the DLL or
26513 an import library which contains a jump table with an entry for each
26514 routine and variable exported by the DLL. In the Microsoft world this
26515 import library is called @file{API.lib}. When using GNAT this import
26516 library is called either @file{libAPI.a} or @file{libapi.a} (names are
26517 case insensitive).
26518
26519 After you have linked your application with the DLL or the import library
26520 and you run your application, here is what happens:
26521
26522 @enumerate
26523 @item
26524 Your application is loaded into memory.
26525
26526 @item
26527 The DLL @file{API.dll} is mapped into the address space of your
26528 application. This means that:
26529
26530 @itemize @bullet
26531 @item
26532 The DLL will use the stack of the calling thread.
26533
26534 @item
26535 The DLL will use the virtual address space of the calling process.
26536
26537 @item
26538 The DLL will allocate memory from the virtual address space of the calling
26539 process.
26540
26541 @item
26542 Handles (pointers) can be safely exchanged between routines in the DLL
26543 routines and routines in the application using the DLL.
26544 @end itemize
26545
26546 @item
26547 The entries in the jump table (from the import library @file{libAPI.a}
26548 or @file{API.lib} or automatically created when linking against a DLL)
26549 which is part of your application are initialized with the addresses
26550 of the routines and variables in @file{API.dll}.
26551
26552 @item
26553 If present in @file{API.dll}, routines @code{DllMain} or
26554 @code{DllMainCRTStartup} are invoked. These routines typically contain
26555 the initialization code needed for the well-being of the routines and
26556 variables exported by the DLL.
26557 @end enumerate
26558
26559 @noindent
26560 There is an additional point which is worth mentioning. In the Windows
26561 world there are two kind of DLLs: relocatable and non-relocatable
26562 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
26563 in the target application address space. If the addresses of two
26564 non-relocatable DLLs overlap and these happen to be used by the same
26565 application, a conflict will occur and the application will run
26566 incorrectly. Hence, when possible, it is always preferable to use and
26567 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
26568 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
26569 User's Guide) removes the debugging symbols from the DLL but the DLL can
26570 still be relocated.
26571
26572 As a side note, an interesting difference between Microsoft DLLs and
26573 Unix shared libraries, is the fact that on most Unix systems all public
26574 routines are exported by default in a Unix shared library, while under
26575 Windows it is possible (but not required) to list exported routines in
26576 a definition file (@pxref{The Definition File}).
26577
26578 @node Using DLLs with GNAT
26579 @section Using DLLs with GNAT
26580
26581 @menu
26582 * Creating an Ada Spec for the DLL Services::
26583 * Creating an Import Library::
26584 @end menu
26585
26586 @noindent
26587 To use the services of a DLL, say @file{API.dll}, in your Ada application
26588 you must have:
26589
26590 @enumerate
26591 @item
26592 The Ada spec for the routines and/or variables you want to access in
26593 @file{API.dll}. If not available this Ada spec must be built from the C/C++
26594 header files provided with the DLL.
26595
26596 @item
26597 The import library (@file{libAPI.a} or @file{API.lib}). As previously
26598 mentioned an import library is a statically linked library containing the
26599 import table which will be filled at load time to point to the actual
26600 @file{API.dll} routines. Sometimes you don't have an import library for the
26601 DLL you want to use. The following sections will explain how to build
26602 one. Note that this is optional.
26603
26604 @item
26605 The actual DLL, @file{API.dll}.
26606 @end enumerate
26607
26608 @noindent
26609 Once you have all the above, to compile an Ada application that uses the
26610 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
26611 you simply issue the command
26612
26613 @smallexample
26614 $ gnatmake my_ada_app -largs -lAPI
26615 @end smallexample
26616
26617 @noindent
26618 The argument @option{-largs -lAPI} at the end of the @code{gnatmake} command
26619 tells the GNAT linker to look first for a library named @file{API.lib}
26620 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
26621 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
26622 contains the following pragma
26623
26624 @smallexample @c ada
26625 pragma Linker_Options ("-lAPI");
26626 @end smallexample
26627
26628 @noindent
26629 you do not have to add @option{-largs -lAPI} at the end of the @code{gnatmake}
26630 command.
26631
26632 If any one of the items above is missing you will have to create it
26633 yourself. The following sections explain how to do so using as an
26634 example a fictitious DLL called @file{API.dll}.
26635
26636 @node Creating an Ada Spec for the DLL Services
26637 @subsection Creating an Ada Spec for the DLL Services
26638
26639 @noindent
26640 A DLL typically comes with a C/C++ header file which provides the
26641 definitions of the routines and variables exported by the DLL. The Ada
26642 equivalent of this header file is a package spec that contains definitions
26643 for the imported entities. If the DLL you intend to use does not come with
26644 an Ada spec you have to generate one such spec yourself. For example if
26645 the header file of @file{API.dll} is a file @file{api.h} containing the
26646 following two definitions:
26647
26648 @smallexample
26649 @group
26650 @cartouche
26651 int some_var;
26652 int get (char *);
26653 @end cartouche
26654 @end group
26655 @end smallexample
26656
26657 @noindent
26658 then the equivalent Ada spec could be:
26659
26660 @smallexample @c ada
26661 @group
26662 @cartouche
26663 with Interfaces.C.Strings;
26664 package API is
26665    use Interfaces;
26666
26667    Some_Var : C.int;
26668    function Get (Str : C.Strings.Chars_Ptr) return C.int;
26669
26670 private
26671    pragma Import (C, Get);
26672    pragma Import (DLL, Some_Var);
26673 end API;
26674 @end cartouche
26675 @end group
26676 @end smallexample
26677
26678 @noindent
26679 Note that a variable is @strong{always imported with a DLL convention}. A
26680 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
26681 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
26682 (@pxref{Windows Calling Conventions}).
26683
26684 @node Creating an Import Library
26685 @subsection Creating an Import Library
26686 @cindex Import library
26687
26688 @menu
26689 * The Definition File::
26690 * GNAT-Style Import Library::
26691 * Microsoft-Style Import Library::
26692 @end menu
26693
26694 @noindent
26695 If a Microsoft-style import library @file{API.lib} or a GNAT-style
26696 import library @file{libAPI.a} is available with @file{API.dll} you
26697 can skip this section. You can also skip this section if
26698 @file{API.dll} is built with GNU tools as in this case it is possible
26699 to link directly against the DLL. Otherwise read on.
26700
26701 @node The Definition File
26702 @subsubsection The Definition File
26703 @cindex Definition file
26704 @findex .def
26705
26706 @noindent
26707 As previously mentioned, and unlike Unix systems, the list of symbols
26708 that are exported from a DLL must be provided explicitly in Windows.
26709 The main goal of a definition file is precisely that: list the symbols
26710 exported by a DLL. A definition file (usually a file with a @code{.def}
26711 suffix) has the following structure:
26712
26713 @smallexample
26714 @group
26715 @cartouche
26716 [LIBRARY @i{name}]
26717 [DESCRIPTION @i{string}]
26718 EXPORTS
26719    @i{symbol1}
26720    @i{symbol2}
26721    ...
26722 @end cartouche
26723 @end group
26724 @end smallexample
26725
26726 @table @code
26727 @item LIBRARY @i{name}
26728 This section, which is optional, gives the name of the DLL.
26729
26730 @item DESCRIPTION @i{string}
26731 This section, which is optional, gives a description string that will be
26732 embedded in the import library.
26733
26734 @item EXPORTS
26735 This section gives the list of exported symbols (procedures, functions or
26736 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
26737 section of @file{API.def} looks like:
26738
26739 @smallexample
26740 @group
26741 @cartouche
26742 EXPORTS
26743    some_var
26744    get
26745 @end cartouche
26746 @end group
26747 @end smallexample
26748 @end table
26749
26750 @noindent
26751 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
26752 (@pxref{Windows Calling Conventions}) for a Stdcall
26753 calling convention function in the exported symbols list.
26754
26755 @noindent
26756 There can actually be other sections in a definition file, but these
26757 sections are not relevant to the discussion at hand.
26758
26759 @node GNAT-Style Import Library
26760 @subsubsection GNAT-Style Import Library
26761
26762 @noindent
26763 To create a static import library from @file{API.dll} with the GNAT tools
26764 you should proceed as follows:
26765
26766 @enumerate
26767 @item
26768 Create the definition file @file{API.def} (@pxref{The Definition File}).
26769 For that use the @code{dll2def} tool as follows:
26770
26771 @smallexample
26772 $ dll2def API.dll > API.def
26773 @end smallexample
26774
26775 @noindent
26776 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
26777 to standard output the list of entry points in the DLL. Note that if
26778 some routines in the DLL have the @code{Stdcall} convention
26779 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
26780 suffix then you'll have to edit @file{api.def} to add it, and specify
26781 @code{-k} to @code{gnatdll} when creating the import library.
26782
26783 @noindent
26784 Here are some hints to find the right @code{@@}@i{nn} suffix.
26785
26786 @enumerate
26787 @item
26788 If you have the Microsoft import library (.lib), it is possible to get
26789 the right symbols by using Microsoft @code{dumpbin} tool (see the
26790 corresponding Microsoft documentation for further details).
26791
26792 @smallexample
26793 $ dumpbin /exports api.lib
26794 @end smallexample
26795
26796 @item
26797 If you have a message about a missing symbol at link time the compiler
26798 tells you what symbol is expected. You just have to go back to the
26799 definition file and add the right suffix.
26800 @end enumerate
26801
26802 @item
26803 Build the import library @code{libAPI.a}, using @code{gnatdll}
26804 (@pxref{Using gnatdll}) as follows:
26805
26806 @smallexample
26807 $ gnatdll -e API.def -d API.dll
26808 @end smallexample
26809
26810 @noindent
26811 @code{gnatdll} takes as input a definition file @file{API.def} and the
26812 name of the DLL containing the services listed in the definition file
26813 @file{API.dll}. The name of the static import library generated is
26814 computed from the name of the definition file as follows: if the
26815 definition file name is @i{xyz}@code{.def}, the import library name will
26816 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
26817 @option{-e} could have been removed because the name of the definition
26818 file (before the ``@code{.def}'' suffix) is the same as the name of the
26819 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
26820 @end enumerate
26821
26822 @node Microsoft-Style Import Library
26823 @subsubsection Microsoft-Style Import Library
26824
26825 @noindent
26826 With GNAT you can either use a GNAT-style or Microsoft-style import
26827 library. A Microsoft import library is needed only if you plan to make an
26828 Ada DLL available to applications developed with Microsoft
26829 tools (@pxref{Mixed-Language Programming on Windows}).
26830
26831 To create a Microsoft-style import library for @file{API.dll} you
26832 should proceed as follows:
26833
26834 @enumerate
26835 @item
26836 Create the definition file @file{API.def} from the DLL. For this use either
26837 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
26838 tool (see the corresponding Microsoft documentation for further details).
26839
26840 @item
26841 Build the actual import library using Microsoft's @code{lib} utility:
26842
26843 @smallexample
26844 $ lib -machine:IX86 -def:API.def -out:API.lib
26845 @end smallexample
26846
26847 @noindent
26848 If you use the above command the definition file @file{API.def} must
26849 contain a line giving the name of the DLL:
26850
26851 @smallexample
26852 LIBRARY      "API"
26853 @end smallexample
26854
26855 @noindent
26856 See the Microsoft documentation for further details about the usage of
26857 @code{lib}.
26858 @end enumerate
26859
26860 @node Building DLLs with GNAT
26861 @section Building DLLs with GNAT
26862 @cindex DLLs, building
26863
26864 @noindent
26865 This section explain how to build DLLs using the GNAT built-in DLL
26866 support. With the following procedure it is straight forward to build
26867 and use DLLs with GNAT.
26868
26869 @enumerate
26870
26871 @item building object files
26872
26873 The first step is to build all objects files that are to be included
26874 into the DLL. This is done by using the standard @code{gnatmake} tool.
26875
26876 @item building the DLL
26877
26878 To build the DLL you must use @code{gcc}'s @code{-shared}
26879 option. It is quite simple to use this method:
26880
26881 @smallexample
26882 $ gcc -shared -o api.dll obj1.o obj2.o ...
26883 @end smallexample
26884
26885 It is important to note that in this case all symbols found in the
26886 object files are automatically exported. It is possible to restrict
26887 the set of symbols to export by passing to @code{gcc} a definition
26888 file, @pxref{The Definition File}. For example:
26889
26890 @smallexample
26891 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
26892 @end smallexample
26893
26894 If you use a definition file you must export the elaboration procedures
26895 for every package that required one. Elaboration procedures are named
26896 using the package name followed by "_E".
26897
26898 @item preparing DLL to be used
26899
26900 For the DLL to be used by client programs the bodies must be hidden
26901 from it and the .ali set with read-only attribute. This is very important
26902 otherwise GNAT will recompile all packages and will not actually use
26903 the code in the DLL. For example:
26904
26905 @smallexample
26906 $ mkdir apilib
26907 $ copy *.ads *.ali api.dll apilib
26908 $ attrib +R apilib\*.ali
26909 @end smallexample
26910
26911 @end enumerate
26912
26913 At this point it is possible to use the DLL by directly linking
26914 against it. Note that you must use the GNAT shared runtime when using
26915 GNAT shared libraries. This is achieved by using @code{-shared} binder's
26916 option.
26917
26918 @smallexample
26919 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
26920 @end smallexample
26921
26922 @node Building DLLs with GNAT Project files
26923 @section Building DLLs with GNAT Project files
26924 @cindex DLLs, building
26925
26926 @noindent
26927 There is nothing specific to Windows in this area. @pxref{Library Projects}.
26928
26929 @node Building DLLs with gnatdll
26930 @section Building DLLs with gnatdll
26931 @cindex DLLs, building
26932
26933 @menu
26934 * Limitations When Using Ada DLLs from Ada::
26935 * Exporting Ada Entities::
26936 * Ada DLLs and Elaboration::
26937 * Ada DLLs and Finalization::
26938 * Creating a Spec for Ada DLLs::
26939 * Creating the Definition File::
26940 * Using gnatdll::
26941 @end menu
26942
26943 @noindent
26944 Note that it is prefered to use the built-in GNAT DLL support
26945 (@pxref{Building DLLs with GNAT}) or GNAT Project files
26946 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
26947
26948 This section explains how to build DLLs containing Ada code using
26949 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
26950 remainder of this section.
26951
26952 The steps required to build an Ada DLL that is to be used by Ada as well as
26953 non-Ada applications are as follows:
26954
26955 @enumerate
26956 @item
26957 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
26958 @code{Stdcall} calling convention to avoid any Ada name mangling for the
26959 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
26960 skip this step if you plan to use the Ada DLL only from Ada applications.
26961
26962 @item
26963 Your Ada code must export an initialization routine which calls the routine
26964 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
26965 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
26966 routine exported by the Ada DLL must be invoked by the clients of the DLL
26967 to initialize the DLL.
26968
26969 @item
26970 When useful, the DLL should also export a finalization routine which calls
26971 routine @code{adafinal} generated by @code{gnatbind} to perform the
26972 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
26973 The finalization routine exported by the Ada DLL must be invoked by the
26974 clients of the DLL when the DLL services are no further needed.
26975
26976 @item
26977 You must provide a spec for the services exported by the Ada DLL in each
26978 of the programming languages to which you plan to make the DLL available.
26979
26980 @item
26981 You must provide a definition file listing the exported entities
26982 (@pxref{The Definition File}).
26983
26984 @item
26985 Finally you must use @code{gnatdll} to produce the DLL and the import
26986 library (@pxref{Using gnatdll}).
26987 @end enumerate
26988
26989 @noindent
26990 Note that a relocatable DLL stripped using the @code{strip} binutils
26991 tool will not be relocatable anymore. To build a DLL without debug
26992 information pass @code{-largs -s} to @code{gnatdll}.
26993
26994 @node Limitations When Using Ada DLLs from Ada
26995 @subsection Limitations When Using Ada DLLs from Ada
26996
26997 @noindent
26998 When using Ada DLLs from Ada applications there is a limitation users
26999 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27000 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27001 each Ada DLL includes the services of the GNAT run time that are necessary
27002 to the Ada code inside the DLL. As a result, when an Ada program uses an
27003 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27004 one in the main program.
27005
27006 It is therefore not possible to exchange GNAT run-time objects between the
27007 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27008 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
27009 types, etc.
27010
27011 It is completely safe to exchange plain elementary, array or record types,
27012 Windows object handles, etc.
27013
27014 @node Exporting Ada Entities
27015 @subsection Exporting Ada Entities
27016 @cindex Export table
27017
27018 @noindent
27019 Building a DLL is a way to encapsulate a set of services usable from any
27020 application. As a result, the Ada entities exported by a DLL should be
27021 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27022 any Ada name mangling. Please note that the @code{Stdcall} convention
27023 should only be used for subprograms, not for variables. As an example here
27024 is an Ada package @code{API}, spec and body, exporting two procedures, a
27025 function, and a variable:
27026
27027 @smallexample @c ada
27028 @group
27029 @cartouche
27030 with Interfaces.C; use Interfaces;
27031 package API is
27032    Count : C.int := 0;
27033    function Factorial (Val : C.int) return C.int;
27034
27035    procedure Initialize_API;
27036    procedure Finalize_API;
27037    --  Initialization & Finalization routines. More in the next section.
27038 private
27039    pragma Export (C, Initialize_API);
27040    pragma Export (C, Finalize_API);
27041    pragma Export (C, Count);
27042    pragma Export (C, Factorial);
27043 end API;
27044 @end cartouche
27045 @end group
27046 @end smallexample
27047
27048 @smallexample @c ada
27049 @group
27050 @cartouche
27051 package body API is
27052    function Factorial (Val : C.int) return C.int is
27053       Fact : C.int := 1;
27054    begin
27055       Count := Count + 1;
27056       for K in 1 .. Val loop
27057          Fact := Fact * K;
27058       end loop;
27059       return Fact;
27060    end Factorial;
27061
27062    procedure Initialize_API is
27063       procedure Adainit;
27064       pragma Import (C, Adainit);
27065    begin
27066       Adainit;
27067    end Initialize_API;
27068
27069    procedure Finalize_API is
27070       procedure Adafinal;
27071       pragma Import (C, Adafinal);
27072    begin
27073       Adafinal;
27074    end Finalize_API;
27075 end API;
27076 @end cartouche
27077 @end group
27078 @end smallexample
27079
27080 @noindent
27081 If the Ada DLL you are building will only be used by Ada applications
27082 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27083 convention. As an example, the previous package could be written as
27084 follows:
27085
27086 @smallexample @c ada
27087 @group
27088 @cartouche
27089 package API is
27090    Count : Integer := 0;
27091    function Factorial (Val : Integer) return Integer;
27092
27093    procedure Initialize_API;
27094    procedure Finalize_API;
27095    --  Initialization and Finalization routines.
27096 end API;
27097 @end cartouche
27098 @end group
27099 @end smallexample
27100
27101 @smallexample @c ada
27102 @group
27103 @cartouche
27104 package body API is
27105    function Factorial (Val : Integer) return Integer is
27106       Fact : Integer := 1;
27107    begin
27108       Count := Count + 1;
27109       for K in 1 .. Val loop
27110          Fact := Fact * K;
27111       end loop;
27112       return Fact;
27113    end Factorial;
27114
27115    ...
27116    --  The remainder of this package body is unchanged.
27117 end API;
27118 @end cartouche
27119 @end group
27120 @end smallexample
27121
27122 @noindent
27123 Note that if you do not export the Ada entities with a @code{C} or
27124 @code{Stdcall} convention you will have to provide the mangled Ada names
27125 in the definition file of the Ada DLL
27126 (@pxref{Creating the Definition File}).
27127
27128 @node Ada DLLs and Elaboration
27129 @subsection Ada DLLs and Elaboration
27130 @cindex DLLs and elaboration
27131
27132 @noindent
27133 The DLL that you are building contains your Ada code as well as all the
27134 routines in the Ada library that are needed by it. The first thing a
27135 user of your DLL must do is elaborate the Ada code
27136 (@pxref{Elaboration Order Handling in GNAT}).
27137
27138 To achieve this you must export an initialization routine
27139 (@code{Initialize_API} in the previous example), which must be invoked
27140 before using any of the DLL services. This elaboration routine must call
27141 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27142 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27143 @code{Initialize_Api} for an example. Note that the GNAT binder is
27144 automatically invoked during the DLL build process by the @code{gnatdll}
27145 tool (@pxref{Using gnatdll}).
27146
27147 When a DLL is loaded, Windows systematically invokes a routine called
27148 @code{DllMain}. It would therefore be possible to call @code{adainit}
27149 directly from @code{DllMain} without having to provide an explicit
27150 initialization routine. Unfortunately, it is not possible to call
27151 @code{adainit} from the @code{DllMain} if your program has library level
27152 tasks because access to the @code{DllMain} entry point is serialized by
27153 the system (that is, only a single thread can execute ``through'' it at a
27154 time), which means that the GNAT run time will deadlock waiting for the
27155 newly created task to complete its initialization.
27156
27157 @node Ada DLLs and Finalization
27158 @subsection Ada DLLs and Finalization
27159 @cindex DLLs and finalization
27160
27161 @noindent
27162 When the services of an Ada DLL are no longer needed, the client code should
27163 invoke the DLL finalization routine, if available. The DLL finalization
27164 routine is in charge of releasing all resources acquired by the DLL. In the
27165 case of the Ada code contained in the DLL, this is achieved by calling
27166 routine @code{adafinal} generated by the GNAT binder
27167 (@pxref{Binding with Non-Ada Main Programs}).
27168 See the body of @code{Finalize_Api} for an
27169 example. As already pointed out the GNAT binder is automatically invoked
27170 during the DLL build process by the @code{gnatdll} tool
27171 (@pxref{Using gnatdll}).
27172
27173 @node Creating a Spec for Ada DLLs
27174 @subsection Creating a Spec for Ada DLLs
27175
27176 @noindent
27177 To use the services exported by the Ada DLL from another programming
27178 language (e.g. C), you have to translate the specs of the exported Ada
27179 entities in that language. For instance in the case of @code{API.dll},
27180 the corresponding C header file could look like:
27181
27182 @smallexample
27183 @group
27184 @cartouche
27185 extern int *_imp__count;
27186 #define count (*_imp__count)
27187 int factorial (int);
27188 @end cartouche
27189 @end group
27190 @end smallexample
27191
27192 @noindent
27193 It is important to understand that when building an Ada DLL to be used by
27194 other Ada applications, you need two different specs for the packages
27195 contained in the DLL: one for building the DLL and the other for using
27196 the DLL. This is because the @code{DLL} calling convention is needed to
27197 use a variable defined in a DLL, but when building the DLL, the variable
27198 must have either the @code{Ada} or @code{C} calling convention. As an
27199 example consider a DLL comprising the following package @code{API}:
27200
27201 @smallexample @c ada
27202 @group
27203 @cartouche
27204 package API is
27205    Count : Integer := 0;
27206    ...
27207    --  Remainder of the package omitted.
27208 end API;
27209 @end cartouche
27210 @end group
27211 @end smallexample
27212
27213 @noindent
27214 After producing a DLL containing package @code{API}, the spec that
27215 must be used to import @code{API.Count} from Ada code outside of the
27216 DLL is:
27217
27218 @smallexample @c ada
27219 @group
27220 @cartouche
27221 package API is
27222    Count : Integer;
27223    pragma Import (DLL, Count);
27224 end API;
27225 @end cartouche
27226 @end group
27227 @end smallexample
27228
27229 @node Creating the Definition File
27230 @subsection Creating the Definition File
27231
27232 @noindent
27233 The definition file is the last file needed to build the DLL. It lists
27234 the exported symbols. As an example, the definition file for a DLL
27235 containing only package @code{API} (where all the entities are exported
27236 with a @code{C} calling convention) is:
27237
27238 @smallexample
27239 @group
27240 @cartouche
27241 EXPORTS
27242     count
27243     factorial
27244     finalize_api
27245     initialize_api
27246 @end cartouche
27247 @end group
27248 @end smallexample
27249
27250 @noindent
27251 If the @code{C} calling convention is missing from package @code{API},
27252 then the definition file contains the mangled Ada names of the above
27253 entities, which in this case are:
27254
27255 @smallexample
27256 @group
27257 @cartouche
27258 EXPORTS
27259     api__count
27260     api__factorial
27261     api__finalize_api
27262     api__initialize_api
27263 @end cartouche
27264 @end group
27265 @end smallexample
27266
27267 @node Using gnatdll
27268 @subsection Using @code{gnatdll}
27269 @findex gnatdll
27270
27271 @menu
27272 * gnatdll Example::
27273 * gnatdll behind the Scenes::
27274 * Using dlltool::
27275 @end menu
27276
27277 @noindent
27278 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
27279 and non-Ada sources that make up your DLL have been compiled.
27280 @code{gnatdll} is actually in charge of two distinct tasks: build the
27281 static import library for the DLL and the actual DLL. The form of the
27282 @code{gnatdll} command is
27283
27284 @smallexample
27285 @cartouche
27286 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
27287 @end cartouche
27288 @end smallexample
27289
27290 @noindent
27291 where @i{list-of-files} is a list of ALI and object files. The object
27292 file list must be the exact list of objects corresponding to the non-Ada
27293 sources whose services are to be included in the DLL. The ALI file list
27294 must be the exact list of ALI files for the corresponding Ada sources
27295 whose services are to be included in the DLL. If @i{list-of-files} is
27296 missing, only the static import library is generated.
27297
27298 @noindent
27299 You may specify any of the following switches to @code{gnatdll}:
27300
27301 @table @code
27302 @item -a[@var{address}]
27303 @cindex @option{-a} (@code{gnatdll})
27304 Build a non-relocatable DLL at @var{address}. If @var{address} is not
27305 specified the default address @var{0x11000000} will be used. By default,
27306 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
27307 advise the reader to build relocatable DLL.
27308
27309 @item -b @var{address}
27310 @cindex @option{-b} (@code{gnatdll})
27311 Set the relocatable DLL base address. By default the address is
27312 @var{0x11000000}.
27313
27314 @item -bargs @var{opts}
27315 @cindex @option{-bargs} (@code{gnatdll})
27316 Binder options. Pass @var{opts} to the binder.
27317
27318 @item -d @var{dllfile}
27319 @cindex @option{-d} (@code{gnatdll})
27320 @var{dllfile} is the name of the DLL. This switch must be present for
27321 @code{gnatdll} to do anything. The name of the generated import library is
27322 obtained algorithmically from @var{dllfile} as shown in the following
27323 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
27324 @code{libxyz.a}. The name of the definition file to use (if not specified
27325 by option @option{-e}) is obtained algorithmically from @var{dllfile}
27326 as shown in the following example:
27327 if @var{dllfile} is @code{xyz.dll}, the definition
27328 file used is @code{xyz.def}.
27329
27330 @item -e @var{deffile}
27331 @cindex @option{-e} (@code{gnatdll})
27332 @var{deffile} is the name of the definition file.
27333
27334 @item -g
27335 @cindex @option{-g} (@code{gnatdll})
27336 Generate debugging information. This information is stored in the object
27337 file and copied from there to the final DLL file by the linker,
27338 where it can be read by the debugger. You must use the
27339 @option{-g} switch if you plan on using the debugger or the symbolic
27340 stack traceback.
27341
27342 @item -h
27343 @cindex @option{-h} (@code{gnatdll})
27344 Help mode. Displays @code{gnatdll} switch usage information.
27345
27346 @item -Idir
27347 @cindex @option{-I} (@code{gnatdll})
27348 Direct @code{gnatdll} to search the @var{dir} directory for source and
27349 object files needed to build the DLL.
27350 (@pxref{Search Paths and the Run-Time Library (RTL)}).
27351
27352 @item -k
27353 @cindex @option{-k} (@code{gnatdll})
27354 Removes the @code{@@}@i{nn} suffix from the import library's exported
27355 names, but keeps them for the link names. You must specify this
27356 option if you want to use a @code{Stdcall} function in a DLL for which
27357 the @code{@@}@i{nn} suffix has been removed. This is the case for most
27358 of the Windows NT DLL for example. This option has no effect when
27359 @option{-n} option is specified.
27360
27361 @item -l @var{file}
27362 @cindex @option{-l} (@code{gnatdll})
27363 The list of ALI and object files used to build the DLL are listed in
27364 @var{file}, instead of being given in the command line. Each line in
27365 @var{file} contains the name of an ALI or object file.
27366
27367 @item -n
27368 @cindex @option{-n} (@code{gnatdll})
27369 No Import. Do not create the import library.
27370
27371 @item -q
27372 @cindex @option{-q} (@code{gnatdll})
27373 Quiet mode. Do not display unnecessary messages.
27374
27375 @item -v
27376 @cindex @option{-v} (@code{gnatdll})
27377 Verbose mode. Display extra information.
27378
27379 @item -largs @var{opts}
27380 @cindex @option{-largs} (@code{gnatdll})
27381 Linker options. Pass @var{opts} to the linker.
27382 @end table
27383
27384 @node gnatdll Example
27385 @subsubsection @code{gnatdll} Example
27386
27387 @noindent
27388 As an example the command to build a relocatable DLL from @file{api.adb}
27389 once @file{api.adb} has been compiled and @file{api.def} created is
27390
27391 @smallexample
27392 $ gnatdll -d api.dll api.ali
27393 @end smallexample
27394
27395 @noindent
27396 The above command creates two files: @file{libapi.a} (the import
27397 library) and @file{api.dll} (the actual DLL). If you want to create
27398 only the DLL, just type:
27399
27400 @smallexample
27401 $ gnatdll -d api.dll -n api.ali
27402 @end smallexample
27403
27404 @noindent
27405 Alternatively if you want to create just the import library, type:
27406
27407 @smallexample
27408 $ gnatdll -d api.dll
27409 @end smallexample
27410
27411 @node gnatdll behind the Scenes
27412 @subsubsection @code{gnatdll} behind the Scenes
27413
27414 @noindent
27415 This section details the steps involved in creating a DLL. @code{gnatdll}
27416 does these steps for you. Unless you are interested in understanding what
27417 goes on behind the scenes, you should skip this section.
27418
27419 We use the previous example of a DLL containing the Ada package @code{API},
27420 to illustrate the steps necessary to build a DLL. The starting point is a
27421 set of objects that will make up the DLL and the corresponding ALI
27422 files. In the case of this example this means that @file{api.o} and
27423 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27424 the following:
27425
27426 @enumerate
27427 @item
27428 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27429 the information necessary to generate relocation information for the
27430 DLL.
27431
27432 @smallexample
27433 @group
27434 $ gnatbind -n api
27435 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27436 @end group
27437 @end smallexample
27438
27439 @noindent
27440 In addition to the base file, the @code{gnatlink} command generates an
27441 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27442 asks @code{gnatlink} to generate the routines @code{DllMain} and
27443 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27444 is loaded into memory.
27445
27446 @item
27447 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27448 export table (@file{api.exp}). The export table contains the relocation
27449 information in a form which can be used during the final link to ensure
27450 that the Windows loader is able to place the DLL anywhere in memory.
27451
27452 @smallexample
27453 @group
27454 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27455           --output-exp api.exp
27456 @end group
27457 @end smallexample
27458
27459 @item
27460 @code{gnatdll} builds the base file using the new export table. Note that
27461 @code{gnatbind} must be called once again since the binder generated file
27462 has been deleted during the previous call to @code{gnatlink}.
27463
27464 @smallexample
27465 @group
27466 $ gnatbind -n api
27467 $ gnatlink api -o api.jnk api.exp -mdll
27468       -Wl,--base-file,api.base
27469 @end group
27470 @end smallexample
27471
27472 @item
27473 @code{gnatdll} builds the new export table using the new base file and
27474 generates the DLL import library @file{libAPI.a}.
27475
27476 @smallexample
27477 @group
27478 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27479           --output-exp api.exp --output-lib libAPI.a
27480 @end group
27481 @end smallexample
27482
27483 @item
27484 Finally @code{gnatdll} builds the relocatable DLL using the final export
27485 table.
27486
27487 @smallexample
27488 @group
27489 $ gnatbind -n api
27490 $ gnatlink api api.exp -o api.dll -mdll
27491 @end group
27492 @end smallexample
27493 @end enumerate
27494
27495 @node Using dlltool
27496 @subsubsection Using @code{dlltool}
27497
27498 @noindent
27499 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27500 DLLs and static import libraries. This section summarizes the most
27501 common @code{dlltool} switches. The form of the @code{dlltool} command
27502 is
27503
27504 @smallexample
27505 $ dlltool [@var{switches}]
27506 @end smallexample
27507
27508 @noindent
27509 @code{dlltool} switches include:
27510
27511 @table @option
27512 @item --base-file @var{basefile}
27513 @cindex @option{--base-file} (@command{dlltool})
27514 Read the base file @var{basefile} generated by the linker. This switch
27515 is used to create a relocatable DLL.
27516
27517 @item --def @var{deffile}
27518 @cindex @option{--def} (@command{dlltool})
27519 Read the definition file.
27520
27521 @item --dllname @var{name}
27522 @cindex @option{--dllname} (@command{dlltool})
27523 Gives the name of the DLL. This switch is used to embed the name of the
27524 DLL in the static import library generated by @code{dlltool} with switch
27525 @option{--output-lib}.
27526
27527 @item -k
27528 @cindex @option{-k} (@command{dlltool})
27529 Kill @code{@@}@i{nn} from exported names
27530 (@pxref{Windows Calling Conventions}
27531 for a discussion about @code{Stdcall}-style symbols.
27532
27533 @item --help
27534 @cindex @option{--help} (@command{dlltool})
27535 Prints the @code{dlltool} switches with a concise description.
27536
27537 @item --output-exp @var{exportfile}
27538 @cindex @option{--output-exp} (@command{dlltool})
27539 Generate an export file @var{exportfile}. The export file contains the
27540 export table (list of symbols in the DLL) and is used to create the DLL.
27541
27542 @item --output-lib @i{libfile}
27543 @cindex @option{--output-lib} (@command{dlltool})
27544 Generate a static import library @var{libfile}.
27545
27546 @item -v
27547 @cindex @option{-v} (@command{dlltool})
27548 Verbose mode.
27549
27550 @item --as @i{assembler-name}
27551 @cindex @option{--as} (@command{dlltool})
27552 Use @i{assembler-name} as the assembler. The default is @code{as}.
27553 @end table
27554
27555 @node GNAT and Windows Resources
27556 @section GNAT and Windows Resources
27557 @cindex Resources, windows
27558
27559 @menu
27560 * Building Resources::
27561 * Compiling Resources::
27562 * Using Resources::
27563 @end menu
27564
27565 @noindent
27566 Resources are an easy way to add Windows specific objects to your
27567 application. The objects that can be added as resources include:
27568
27569 @itemize @bullet
27570 @item
27571 menus
27572
27573 @item
27574 accelerators
27575
27576 @item
27577 dialog boxes
27578
27579 @item
27580 string tables
27581
27582 @item
27583 bitmaps
27584
27585 @item
27586 cursors
27587
27588 @item
27589 icons
27590
27591 @item
27592 fonts
27593 @end itemize
27594
27595 @noindent
27596 This section explains how to build, compile and use resources.
27597
27598 @node Building Resources
27599 @subsection Building Resources
27600 @cindex Resources, building
27601
27602 @noindent
27603 A resource file is an ASCII file. By convention resource files have an
27604 @file{.rc} extension.
27605 The easiest way to build a resource file is to use Microsoft tools
27606 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
27607 @code{dlgedit.exe} to build dialogs.
27608 It is always possible to build an @file{.rc} file yourself by writing a
27609 resource script.
27610
27611 It is not our objective to explain how to write a resource file. A
27612 complete description of the resource script language can be found in the
27613 Microsoft documentation.
27614
27615 @node Compiling Resources
27616 @subsection Compiling Resources
27617 @findex rc
27618 @findex windres
27619 @cindex Resources, compiling
27620
27621 @noindent
27622 This section describes how to build a GNAT-compatible (COFF) object file
27623 containing the resources. This is done using the Resource Compiler
27624 @code{windres} as follows:
27625
27626 @smallexample
27627 $ windres -i myres.rc -o myres.o
27628 @end smallexample
27629
27630 @noindent
27631 By default @code{windres} will run @code{gcc} to preprocess the @file{.rc}
27632 file. You can specify an alternate preprocessor (usually named
27633 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
27634 parameter. A list of all possible options may be obtained by entering
27635 the command @code{windres} @option{--help}.
27636
27637 It is also possible to use the Microsoft resource compiler @code{rc.exe}
27638 to produce a @file{.res} file (binary resource file). See the
27639 corresponding Microsoft documentation for further details. In this case
27640 you need to use @code{windres} to translate the @file{.res} file to a
27641 GNAT-compatible object file as follows:
27642
27643 @smallexample
27644 $ windres -i myres.res -o myres.o
27645 @end smallexample
27646
27647 @node Using Resources
27648 @subsection Using Resources
27649 @cindex Resources, using
27650
27651 @noindent
27652 To include the resource file in your program just add the
27653 GNAT-compatible object file for the resource(s) to the linker
27654 arguments. With @code{gnatmake} this is done by using the @option{-largs}
27655 option:
27656
27657 @smallexample
27658 $ gnatmake myprog -largs myres.o
27659 @end smallexample
27660
27661 @node Debugging a DLL
27662 @section Debugging a DLL
27663 @cindex DLL debugging
27664
27665 @menu
27666 * Program and DLL Both Built with GCC/GNAT::
27667 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
27668 @end menu
27669
27670 @noindent
27671 Debugging a DLL is similar to debugging a standard program. But
27672 we have to deal with two different executable parts: the DLL and the
27673 program that uses it. We have the following four possibilities:
27674
27675 @enumerate 1
27676 @item
27677 The program and the DLL are built with @code{GCC/GNAT}.
27678 @item
27679 The program is built with foreign tools and the DLL is built with
27680 @code{GCC/GNAT}.
27681 @item
27682 The program is built with @code{GCC/GNAT} and the DLL is built with
27683 foreign tools.
27684 @item
27685 @end enumerate
27686
27687 @noindent
27688 In this section we address only cases one and two above.
27689 There is no point in trying to debug
27690 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
27691 information in it. To do so you must use a debugger compatible with the
27692 tools suite used to build the DLL.
27693
27694 @node Program and DLL Both Built with GCC/GNAT
27695 @subsection Program and DLL Both Built with GCC/GNAT
27696
27697 @noindent
27698 This is the simplest case. Both the DLL and the program have @code{GDB}
27699 compatible debugging information. It is then possible to break anywhere in
27700 the process. Let's suppose here that the main procedure is named
27701 @code{ada_main} and that in the DLL there is an entry point named
27702 @code{ada_dll}.
27703
27704 @noindent
27705 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
27706 program must have been built with the debugging information (see GNAT -g
27707 switch). Here are the step-by-step instructions for debugging it:
27708
27709 @enumerate 1
27710 @item Launch @code{GDB} on the main program.
27711
27712 @smallexample
27713 $ gdb -nw ada_main
27714 @end smallexample
27715
27716 @item Break on the main procedure and run the program.
27717
27718 @smallexample
27719 (gdb) break ada_main
27720 (gdb) run
27721 @end smallexample
27722
27723 @noindent
27724 This step is required to be able to set a breakpoint inside the DLL. As long
27725 as the program is not run, the DLL is not loaded. This has the
27726 consequence that the DLL debugging information is also not loaded, so it is not
27727 possible to set a breakpoint in the DLL.
27728
27729 @item Set a breakpoint inside the DLL
27730
27731 @smallexample
27732 (gdb) break ada_dll
27733 (gdb) run
27734 @end smallexample
27735
27736 @end enumerate
27737
27738 @noindent
27739 At this stage a breakpoint is set inside the DLL. From there on
27740 you can use the standard approach to debug the whole program
27741 (@pxref{Running and Debugging Ada Programs}).
27742
27743 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
27744 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
27745
27746 @menu
27747 * Debugging the DLL Directly::
27748 * Attaching to a Running Process::
27749 @end menu
27750
27751 @noindent
27752 In this case things are slightly more complex because it is not possible to
27753 start the main program and then break at the beginning to load the DLL and the
27754 associated DLL debugging information. It is not possible to break at the
27755 beginning of the program because there is no @code{GDB} debugging information,
27756 and therefore there is no direct way of getting initial control. This
27757 section addresses this issue by describing some methods that can be used
27758 to break somewhere in the DLL to debug it.
27759
27760 @noindent
27761 First suppose that the main procedure is named @code{main} (this is for
27762 example some C code built with Microsoft Visual C) and that there is a
27763 DLL named @code{test.dll} containing an Ada entry point named
27764 @code{ada_dll}.
27765
27766 @noindent
27767 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
27768 been built with debugging information (see GNAT -g option).
27769
27770 @node Debugging the DLL Directly
27771 @subsubsection Debugging the DLL Directly
27772
27773 @enumerate 1
27774 @item
27775 Launch the debugger on the DLL.
27776
27777 @smallexample
27778 $ gdb -nw test.dll
27779 @end smallexample
27780
27781 @item Set a breakpoint on a DLL subroutine.
27782
27783 @smallexample
27784 (gdb) break ada_dll
27785 @end smallexample
27786
27787 @item
27788 Specify the executable file to @code{GDB}.
27789
27790 @smallexample
27791 (gdb) exec-file main.exe
27792 @end smallexample
27793
27794 @item
27795 Run the program.
27796
27797 @smallexample
27798 (gdb) run
27799 @end smallexample
27800
27801 @noindent
27802 This will run the program until it reaches the breakpoint that has been
27803 set. From that point you can use the standard way to debug a program
27804 as described in (@pxref{Running and Debugging Ada Programs}).
27805
27806 @end enumerate
27807
27808 @noindent
27809 It is also possible to debug the DLL by attaching to a running process.
27810
27811 @node Attaching to a Running Process
27812 @subsubsection Attaching to a Running Process
27813 @cindex DLL debugging, attach to process
27814
27815 @noindent
27816 With @code{GDB} it is always possible to debug a running process by
27817 attaching to it. It is possible to debug a DLL this way. The limitation
27818 of this approach is that the DLL must run long enough to perform the
27819 attach operation. It may be useful for instance to insert a time wasting
27820 loop in the code of the DLL to meet this criterion.
27821
27822 @enumerate 1
27823
27824 @item Launch the main program @file{main.exe}.
27825
27826 @smallexample
27827 $ main
27828 @end smallexample
27829
27830 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
27831 that the process PID for @file{main.exe} is 208.
27832
27833 @item Launch gdb.
27834
27835 @smallexample
27836 $ gdb -nw
27837 @end smallexample
27838
27839 @item Attach to the running process to be debugged.
27840
27841 @smallexample
27842 (gdb) attach 208
27843 @end smallexample
27844
27845 @item Load the process debugging information.
27846
27847 @smallexample
27848 (gdb) symbol-file main.exe
27849 @end smallexample
27850
27851 @item Break somewhere in the DLL.
27852
27853 @smallexample
27854 (gdb) break ada_dll
27855 @end smallexample
27856
27857 @item Continue process execution.
27858
27859 @smallexample
27860 (gdb) continue
27861 @end smallexample
27862
27863 @end enumerate
27864
27865 @noindent
27866 This last step will resume the process execution, and stop at
27867 the breakpoint we have set. From there you can use the standard
27868 approach to debug a program as described in
27869 (@pxref{Running and Debugging Ada Programs}).
27870
27871 @node GNAT and COM/DCOM Objects
27872 @section GNAT and COM/DCOM Objects
27873 @findex COM
27874 @findex DCOM
27875
27876 @noindent
27877 This section is temporarily left blank.
27878
27879 @end ifset
27880
27881
27882 @c **********************************
27883 @c * GNU Free Documentation License *
27884 @c **********************************
27885 @include fdl.texi
27886 @c GNU Free Documentation License
27887
27888 @node Index,,GNU Free Documentation License, Top
27889 @unnumbered Index
27890
27891 @printindex cp
27892
27893 @contents
27894 @c Put table of contents at end, otherwise it precedes the "title page" in
27895 @c the .txt version
27896 @c Edit the pdf file to move the contents to the beginning, after the title
27897 @c page
27898
27899 @bye