OSDN Git Service

2004-05-27 Vincent Celier <celier@gnat.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c          Copyright (C) 1992-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 @ifset vms
89 @settitle GNAT User's Guide for Native Platforms / OpenVMS Alpha
90 @dircategory GNU Ada tools
91 @direntry
92 * GNAT User's Guide (gnat_ugn_vms) for Native Platforms / OpenVMS Alpha
93 @end direntry
94 @end ifset
95
96 @ifset unw
97 @settitle GNAT User's Guide for Native Platforms / Unix and Windows
98 @direntry
99 * GNAT User's Guide (gnat_ugn_unw) for Native Platforms / Unix and Windows
100 @end direntry
101 @end ifset
102
103 @include gcc-common.texi
104
105 @setchapternewpage odd
106 @syncodeindex fn cp
107 @c %**end of header
108
109 @copying
110 Copyright @copyright{} 1995-2004, Free Software Foundation
111
112 Permission is granted to copy, distribute and/or modify this document
113 under the terms of the GNU Free Documentation License, Version 1.2
114 or any later version published by the Free Software Foundation;
115 with the Invariant Sections being ``GNU Free Documentation License'', with the
116 Front-Cover Texts being
117 @ifset vms
118 ``GNAT User's Guide for Native Platforms / OpenVMS Alpha'',
119 @end ifset
120 @ifset unw
121 ``GNAT User's Guide for Native Platforms / Unix and Windows'',
122 @end ifset
123 and with no Back-Cover Texts.
124 A copy of the license is included in the section entitled
125 ``GNU Free Documentation License''.
126 @end copying
127
128 @titlepage
129
130 @title GNAT User's Guide
131 @center @titlefont{for Native Platforms}
132 @sp 1
133
134 @flushright
135 @ifset unw
136 @titlefont{@i{Unix and Windows}}
137 @end ifset
138 @ifset vms
139 @titlefont{@i{OpenVMS Alpha}}
140 @end ifset
141 @end flushright
142 @sp 2
143
144 @subtitle GNAT, The GNU Ada 95 Compiler
145 @subtitle GCC version @value{version-GCC}
146
147 @author Ada Core Technologies, Inc.
148
149 @page
150 @vskip 0pt plus 1filll
151
152 @insertcopying
153
154 @end titlepage
155
156
157 @ifnottex
158 @node Top, About This Guide, (dir), (dir)
159 @top GNAT User's Guide
160
161 @ifset vms
162 @noindent
163 GNAT User's Guide for Native Platforms / OpenVMS Alpha
164 @end ifset
165
166 @ifset unw
167 @noindent
168 GNAT User's Guide for Native Platforms / Unix and Windows
169 @end ifset
170
171 @noindent
172 GNAT, The GNU Ada 95 Compiler@*
173 GCC version @value{version-GCC}@*
174
175 @noindent
176 Ada Core Technologies, Inc.@*
177
178 @menu
179 * About This Guide::
180 * Getting Started with GNAT::
181 * The GNAT Compilation Model::
182 * Compiling Using gcc::
183 * Binding Using gnatbind::
184 * Linking Using gnatlink::
185 * The GNAT Make Program gnatmake::
186 * Improving Performance::
187 * Renaming Files Using gnatchop::
188 * Configuration Pragmas::
189 * Handling Arbitrary File Naming Conventions Using gnatname::
190 * GNAT Project Manager::
191 * The Cross-Referencing Tools gnatxref and gnatfind::
192 * The GNAT Pretty-Printer gnatpp::
193 * File Name Krunching Using gnatkr::
194 * Preprocessing Using gnatprep::
195 @ifset vms
196 * The GNAT Run-Time Library Builder gnatlbr::
197 @end ifset
198 * The GNAT Library Browser gnatls::
199 * Cleaning Up Using gnatclean::
200 @ifclear vms
201 * GNAT and Libraries::
202 * Using the GNU make Utility::
203 @end ifclear
204 * Finding Memory Problems::
205 * Creating Sample Bodies Using gnatstub::
206 * Other Utility Programs::
207 * Running and Debugging Ada Programs::
208 @ifset vms
209 * Compatibility with DEC Ada::
210 @end ifset
211 * Platform-Specific Information for the Run-Time Libraries::
212 * Example of Binder Output File::
213 * Elaboration Order Handling in GNAT::
214 * Inline Assembler::
215 * Compatibility and Porting Guide::
216 @ifset unw
217 * Microsoft Windows Topics::
218 @end ifset
219 * GNU Free Documentation License::
220 * Index::
221
222  --- The Detailed Node Listing ---
223
224 About This Guide
225
226 * What This Guide Contains::
227 * What You Should Know before Reading This Guide::
228 * Related Information::
229 * Conventions::
230
231 Getting Started with GNAT
232
233 * Running GNAT::
234 * Running a Simple Ada Program::
235 * Running a Program with Multiple Units::
236 * Using the gnatmake Utility::
237 @ifset vms
238 * Editing with Emacs::
239 @end ifset
240 @ifclear vms
241 * Introduction to GPS::
242 * Introduction to Glide and GVD::
243 @end ifclear
244
245 The GNAT Compilation Model
246
247 * Source Representation::
248 * Foreign Language Representation::
249 * File Naming Rules::
250 * Using Other File Names::
251 * Alternative File Naming Schemes::
252 * Generating Object Files::
253 * Source Dependencies::
254 * The Ada Library Information Files::
255 * Binding an Ada Program::
256 * Mixed Language Programming::
257 * Building Mixed Ada & C++ Programs::
258 * Comparison between GNAT and C/C++ Compilation Models::
259 * Comparison between GNAT and Conventional Ada Library Models::
260 @ifset vms
261 * Placement of temporary files::
262 @end ifset
263
264 Foreign Language Representation
265
266 * Latin-1::
267 * Other 8-Bit Codes::
268 * Wide Character Encodings::
269
270 Compiling Ada Programs With gcc
271
272 * Compiling Programs::
273 * Switches for gcc::
274 * Search Paths and the Run-Time Library (RTL)::
275 * Order of Compilation Issues::
276 * Examples::
277
278 Switches for gcc
279
280 * Output and Error Message Control::
281 * Warning Message Control::
282 * Debugging and Assertion Control::
283 * Run-Time Checks::
284 * Stack Overflow Checking::
285 * Validity Checking::
286 * Style Checking::
287 * Using gcc for Syntax Checking::
288 * Using gcc for Semantic Checking::
289 * Compiling Ada 83 Programs::
290 * Character Set Control::
291 * File Naming Control::
292 * Subprogram Inlining Control::
293 * Auxiliary Output Control::
294 * Debugging Control::
295 * Exception Handling Control::
296 * Units to Sources Mapping Files::
297 * Integrated Preprocessing::
298 @ifset vms
299 * Return Codes::
300 @end ifset
301
302 Binding Ada Programs With gnatbind
303
304 * Running gnatbind::
305 * Switches for gnatbind::
306 * Command-Line Access::
307 * Search Paths for gnatbind::
308 * Examples of gnatbind Usage::
309
310 Switches for gnatbind
311
312 * Consistency-Checking Modes::
313 * Binder Error Message Control::
314 * Elaboration Control::
315 * Output Control::
316 * Binding with Non-Ada Main Programs::
317 * Binding Programs with No Main Subprogram::
318
319 Linking Using gnatlink
320
321 * Running gnatlink::
322 * Switches for gnatlink::
323 * Setting Stack Size from gnatlink::
324 * Setting Heap Size from gnatlink::
325
326 The GNAT Make Program gnatmake
327
328 * Running gnatmake::
329 * Switches for gnatmake::
330 * Mode Switches for gnatmake::
331 * Notes on the Command Line::
332 * How gnatmake Works::
333 * Examples of gnatmake Usage::
334
335
336 Improving Performance
337 * Performance Considerations::
338 * Reducing the Size of Ada Executables with gnatelim::
339
340 Performance Considerations
341 * Controlling Run-Time Checks::
342 * Use of Restrictions::
343 * Optimization Levels::
344 * Debugging Optimized Code::
345 * Inlining of Subprograms::
346 * Optimization and Strict Aliasing::
347 @ifset vms
348 * Coverage Analysis::
349 @end ifset
350
351 Reducing the Size of Ada Executables with gnatelim
352 * About gnatelim::
353 * Running gnatelim::
354 * Correcting the List of Eliminate Pragmas::
355 * Making Your Executables Smaller::
356 * Summary of the gnatelim Usage Cycle::
357
358 Renaming Files Using gnatchop
359
360 * Handling Files with Multiple Units::
361 * Operating gnatchop in Compilation Mode::
362 * Command Line for gnatchop::
363 * Switches for gnatchop::
364 * Examples of gnatchop Usage::
365
366 Configuration Pragmas
367
368 * Handling of Configuration Pragmas::
369 * The Configuration Pragmas Files::
370
371 Handling Arbitrary File Naming Conventions Using gnatname
372
373 * Arbitrary File Naming Conventions::
374 * Running gnatname::
375 * Switches for gnatname::
376 * Examples of gnatname Usage::
377
378 GNAT Project Manager
379
380 * Introduction::
381 * Examples of Project Files::
382 * Project File Syntax::
383 * Objects and Sources in Project Files::
384 * Importing Projects::
385 * Project Extension::
386 * External References in Project Files::
387 * Packages in Project Files::
388 * Variables from Imported Projects::
389 * Naming Schemes::
390 * Library Projects::
391 * Using Third-Party Libraries through Projects::
392 * Stand-alone Library Projects::
393 * Switches Related to Project Files::
394 * Tools Supporting Project Files::
395 * An Extended Example::
396 * Project File Complete Syntax::
397
398
399 The Cross-Referencing Tools gnatxref and gnatfind
400
401 * gnatxref Switches::
402 * gnatfind Switches::
403 * Project Files for gnatxref and gnatfind::
404 * Regular Expressions in gnatfind and gnatxref::
405 * Examples of gnatxref Usage::
406 * Examples of gnatfind Usage::
407
408
409 The GNAT Pretty-Printer gnatpp
410
411 * Switches for gnatpp::
412 * Formatting Rules::
413
414
415 File Name Krunching Using gnatkr
416
417 * About gnatkr::
418 * Using gnatkr::
419 * Krunching Method::
420 * Examples of gnatkr Usage::
421
422 Preprocessing Using gnatprep
423
424 * Using gnatprep::
425 * Switches for gnatprep::
426 * Form of Definitions File::
427 * Form of Input Text for gnatprep::
428
429 @ifset vms
430 The GNAT Run-Time Library Builder gnatlbr
431
432 * Running gnatlbr::
433 * Switches for gnatlbr::
434 * Examples of gnatlbr Usage::
435 @end ifset
436
437 The GNAT Library Browser gnatls
438
439 * Running gnatls::
440 * Switches for gnatls::
441 * Examples of gnatls Usage::
442
443 Cleaning Up Using gnatclean
444
445 * Running gnatclean::
446 * Switches for gnatclean::
447 * Examples of gnatclean Usage::
448
449 @ifclear vms
450
451 GNAT and Libraries
452
453 * Introduction to Libraries in GNAT::
454 * General Ada Libraries::
455 * Stand-alone Ada Libraries::
456 * Rebuilding the GNAT Run-Time Library::
457
458 Using the GNU make Utility
459
460 * Using gnatmake in a Makefile::
461 * Automatically Creating a List of Directories::
462 * Generating the Command Line Switches::
463 * Overcoming Command Line Length Limits::
464 @end ifclear
465
466 Finding Memory Problems
467
468 @ifclear vms
469 * The gnatmem Tool::
470 @end ifclear
471 * The GNAT Debug Pool Facility::
472
473 @ifclear vms
474 The gnatmem Tool
475
476 * Running gnatmem::
477 * Switches for gnatmem::
478 * Example of gnatmem Usage::
479 @end ifclear
480
481 The GNAT Debug Pool Facility
482
483 Creating Sample Bodies Using gnatstub
484
485 * Running gnatstub::
486 * Switches for gnatstub::
487
488 Other Utility Programs
489
490 * Using Other Utility Programs with GNAT::
491 * The External Symbol Naming Scheme of GNAT::
492 @ifclear vms
493 * Ada Mode for Glide::
494 @end ifclear
495 * Converting Ada Files to html with gnathtml::
496
497 Running and Debugging Ada Programs
498
499 * The GNAT Debugger GDB::
500 * Running GDB::
501 * Introduction to GDB Commands::
502 * Using Ada Expressions::
503 * Calling User-Defined Subprograms::
504 * Using the Next Command in a Function::
505 * Ada Exceptions::
506 * Ada Tasks::
507 * Debugging Generic Units::
508 * GNAT Abnormal Termination or Failure to Terminate::
509 * Naming Conventions for GNAT Source Files::
510 * Getting Internal Debugging Information::
511 * Stack Traceback::
512
513 @ifset vms
514 * LSE::
515 @end ifset
516
517 @ifset vms
518 Compatibility with DEC Ada
519
520 * Ada 95 Compatibility::
521 * Differences in the Definition of Package System::
522 * Language-Related Features::
523 * The Package STANDARD::
524 * The Package SYSTEM::
525 * Tasking and Task-Related Features::
526 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
527 * Pragmas and Pragma-Related Features::
528 * Library of Predefined Units::
529 * Bindings::
530 * Main Program Definition::
531 * Implementation-Defined Attributes::
532 * Compiler and Run-Time Interfacing::
533 * Program Compilation and Library Management::
534 * Input-Output::
535 * Implementation Limits::
536 * Tools::
537
538 Language-Related Features
539
540 * Integer Types and Representations::
541 * Floating-Point Types and Representations::
542 * Pragmas Float_Representation and Long_Float::
543 * Fixed-Point Types and Representations::
544 * Record and Array Component Alignment::
545 * Address Clauses::
546 * Other Representation Clauses::
547
548 Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
549
550 * Assigning Task IDs::
551 * Task IDs and Delays::
552 * Task-Related Pragmas::
553 * Scheduling and Task Priority::
554 * The Task Stack::
555 * External Interrupts::
556
557 Pragmas and Pragma-Related Features
558
559 * Restrictions on the Pragma INLINE::
560 * Restrictions on the Pragma INTERFACE::
561 * Restrictions on the Pragma SYSTEM_NAME::
562
563 Library of Predefined Units
564
565 * Changes to DECLIB::
566
567 Bindings
568
569 * Shared Libraries and Options Files::
570 * Interfaces to C::
571 @end ifset
572
573 Platform-Specific Information for the Run-Time Libraries
574
575 * Summary of Run-Time Configurations::
576 * Specifying a Run-Time Library::
577 * Choosing between Native and FSU Threads Libraries::
578 * Choosing the Scheduling Policy::
579 * Solaris-Specific Considerations::
580 * IRIX-Specific Considerations::
581 * Linux-Specific Considerations::
582 * AIX-Specific Considerations::
583
584 Example of Binder Output File
585
586 Elaboration Order Handling in GNAT
587
588 * Elaboration Code in Ada 95::
589 * Checking the Elaboration Order in Ada 95::
590 * Controlling the Elaboration Order in Ada 95::
591 * Controlling Elaboration in GNAT - Internal Calls::
592 * Controlling Elaboration in GNAT - External Calls::
593 * Default Behavior in GNAT - Ensuring Safety::
594 * Treatment of Pragma Elaborate::
595 * Elaboration Issues for Library Tasks::
596 * Mixing Elaboration Models::
597 * What to Do If the Default Elaboration Behavior Fails::
598 * Elaboration for Access-to-Subprogram Values::
599 * Summary of Procedures for Elaboration Control::
600 * Other Elaboration Order Considerations::
601
602 Inline Assembler
603
604 * Basic Assembler Syntax::
605 * A Simple Example of Inline Assembler::
606 * Output Variables in Inline Assembler::
607 * Input Variables in Inline Assembler::
608 * Inlining Inline Assembler Code::
609 * Other Asm Functionality::
610 * A Complete Example::
611
612 Compatibility and Porting Guide
613
614 * Compatibility with Ada 83::
615 * Implementation-dependent characteristics::
616 * Compatibility with DEC Ada 83::
617 * Compatibility with Other Ada 95 Systems::
618 * Representation Clauses::
619
620 @ifset unw
621 Microsoft Windows Topics
622
623 * Using GNAT on Windows::
624 * CONSOLE and WINDOWS subsystems::
625 * Temporary Files::
626 * Mixed-Language Programming on Windows::
627 * Windows Calling Conventions::
628 * Introduction to Dynamic Link Libraries (DLLs)::
629 * Using DLLs with GNAT::
630 * Building DLLs with GNAT::
631 * GNAT and Windows Resources::
632 * Debugging a DLL::
633 * GNAT and COM/DCOM Objects::
634 @end ifset
635
636
637 * Index::
638 @end menu
639 @end ifnottex
640
641 @node About This Guide
642 @unnumbered About This Guide
643
644 @noindent
645 @ifset vms
646 This guide describes the use of of GNAT, a full language compiler for the Ada
647 95 programming language, implemented on HP OpenVMS Alpha platforms.
648 @end ifset
649 @ifclear vms
650 This guide describes the use of GNAT, a compiler and software development
651 toolset for the full Ada 95 programming language.
652 @end ifclear
653 It describes the features of the compiler and tools, and details
654 how to use them to build Ada 95 applications.
655
656 @menu
657 * What This Guide Contains::
658 * What You Should Know before Reading This Guide::
659 * Related Information::
660 * Conventions::
661 @end menu
662
663 @node What This Guide Contains
664 @unnumberedsec What This Guide Contains
665
666 @noindent
667 This guide contains the following chapters:
668 @itemize @bullet
669
670 @item
671 @ref{Getting Started with GNAT}, describes how to get started compiling
672 and running Ada programs with the GNAT Ada programming environment.
673 @item
674 @ref{The GNAT Compilation Model}, describes the compilation model used
675 by GNAT.
676
677 @item
678 @ref{Compiling Using gcc}, describes how to compile
679 Ada programs with @code{gcc}, the Ada compiler.
680
681 @item
682 @ref{Binding Using gnatbind}, describes how to
683 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
684 utility.
685
686 @item
687 @ref{Linking Using gnatlink},
688 describes @code{gnatlink}, a
689 program that provides for linking using the GNAT run-time library to
690 construct a program. @code{gnatlink} can also incorporate foreign language
691 object units into the executable.
692
693 @item
694 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
695 utility that automatically determines the set of sources
696 needed by an Ada compilation unit, and executes the necessary compilations
697 binding and link.
698
699 @item
700 @ref{Improving Performance}, shows various techniques for making your
701 Ada program run faster or take less space.
702 It discusses the effect of the compiler's optimization switch and
703 also describes the @command{gnatelim} tool.
704
705 @item
706 @ref{Renaming Files Using gnatchop}, describes
707 @code{gnatchop}, a utility that allows you to preprocess a file that
708 contains Ada source code, and split it into one or more new files, one
709 for each compilation unit.
710
711 @item
712 @ref{Configuration Pragmas}, describes the configuration pragmas
713 handled by GNAT.
714
715 @item
716 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
717 shows how to override the default GNAT file naming conventions,
718 either for an individual unit or globally.
719
720 @item
721 @ref{GNAT Project Manager}, describes how to use project files
722 to organize large projects.
723
724 @item
725 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
726 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
727 way to navigate through sources.
728
729 @item
730 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
731 version of an Ada source file with control over casing, indentation,
732 comment placement, and other elements of program presentation style.
733
734
735 @item
736 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
737 file name krunching utility, used to handle shortened
738 file names on operating systems with a limit on the length of names.
739
740 @item
741 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
742 preprocessor utility that allows a single source file to be used to
743 generate multiple or parameterized source files, by means of macro
744 substitution.
745
746 @ifset vms
747 @item
748 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
749 a tool for rebuilding the GNAT run time with user-supplied
750 configuration pragmas.
751 @end ifset
752
753 @item
754 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
755 utility that displays information about compiled units, including dependences
756 on the corresponding sources files, and consistency of compilations.
757
758 @item
759 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
760 to delete files that are produced by the compiler, binder and linker.
761
762 @ifclear vms
763 @item
764 @ref{GNAT and Libraries}, describes the process of creating and using
765 Libraries with GNAT. It also describes how to recompile the GNAT run-time
766 library.
767
768 @item
769 @ref{Using the GNU make Utility}, describes some techniques for using
770 the GNAT toolset in Makefiles.
771 @end ifclear
772
773 @item
774 @ref{Finding Memory Problems}, describes
775 @ifclear vms
776 @command{gnatmem}, a utility that monitors dynamic allocation and deallocation
777 and helps detect ``memory leaks'', and
778 @end ifclear
779 the GNAT Debug Pool facility, which helps detect incorrect memory references.
780
781 @item
782 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
783 a utility that generates empty but compilable bodies for library units.
784
785 @item
786 @ref{Other Utility Programs}, discusses several other GNAT utilities,
787 including @code{gnathtml}.
788
789 @item
790 @ref{Running and Debugging Ada Programs}, describes how to run and debug
791 Ada programs.
792
793 @ifset vms
794 @item
795 @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
796 DEC Ada 83 @footnote{``DEC Ada'' refers to the legacy product originally
797 developed by Digital Equipment Corporation and currently supported by HP.}
798 for OpenVMS Alpha.
799 @end ifset
800
801 @item
802 @ref{Platform-Specific Information for the Run-Time Libraries},
803 describes the various run-time
804 libraries supported by GNAT on various platforms and explains how to
805 choose a particular library.
806
807 @item
808 @ref{Example of Binder Output File}, shows the source code for the binder
809 output file for a sample program.
810
811 @item
812 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
813 you deal with elaboration order issues.
814
815 @item
816 @ref{Inline Assembler}, shows how to use the inline assembly facility
817 in an Ada program.
818
819 @item
820 @ref{Compatibility and Porting Guide}, includes sections on compatibility
821 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
822 in porting code from other environments.
823
824 @ifset unw
825 @item
826 @ref{Microsoft Windows Topics}, presents information relevant to the
827 Microsoft Windows platform.
828 @end ifset
829 @end itemize
830
831
832 @c *************************************************
833 @node What You Should Know before Reading This Guide
834 @c *************************************************
835 @unnumberedsec What You Should Know before Reading This Guide
836
837 @cindex Ada 95 Language Reference Manual
838 @noindent
839 This user's guide assumes that you are familiar with Ada 95 language, as
840 described in the International Standard ANSI/ISO/IEC-8652:1995, January
841 1995.
842
843 @node Related Information
844 @unnumberedsec Related Information
845
846 @noindent
847 For further information about related tools, refer to the following
848 documents:
849
850 @itemize @bullet
851 @item
852 @cite{GNAT Reference Manual}, which contains all reference
853 material for the GNAT implementation of Ada 95.
854
855 @ifset unw
856 @item
857 @cite{Using the GNAT Programming System}, which describes the GPS
858 integrated development environment.
859
860 @item
861 @cite{GNAT Programming System Tutorial}, which introduces the
862 main GPS features through examples.
863 @end ifset
864
865 @item
866 @cite{Ada 95 Language Reference Manual}, which contains all reference
867 material for the Ada 95 programming language.
868
869 @item
870 @cite{Debugging with GDB}
871 @ifset vms
872 , located in the GNU:[DOCS] directory,
873 @end ifset
874 contains all details on the use of the GNU source-level debugger.
875
876 @item
877 @cite{GNU Emacs Manual}
878 @ifset vms
879 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
880 @end ifset
881 contains full information on the extensible editor and programming
882 environment Emacs.
883
884 @end itemize
885
886 @c **************
887 @node Conventions
888 @unnumberedsec Conventions
889 @cindex Conventions
890 @cindex Typographical conventions
891
892 @noindent
893 Following are examples of the typographical and graphic conventions used
894 in this guide:
895
896 @itemize @bullet
897 @item
898 @code{Functions}, @code{utility program names}, @code{standard names},
899 and @code{classes}.
900
901 @item
902 @samp{Option flags}
903
904 @item
905 @file{File Names}, @file{button names}, and @file{field names}.
906
907 @item
908 @var{Variables}.
909
910 @item
911 @emph{Emphasis}.
912
913 @item
914 [optional information or parameters]
915
916 @item
917 Examples are described by text
918 @smallexample
919 and then shown this way.
920 @end smallexample
921 @end itemize
922
923 @noindent
924 Commands that are entered by the user are preceded in this manual by the
925 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
926 uses this sequence as a prompt, then the commands will appear exactly as
927 you see them in the manual. If your system uses some other prompt, then
928 the command will appear with the @code{$} replaced by whatever prompt
929 character you are using.
930
931 @ifset unw
932 Full file names are shown with the ``@code{/}'' character
933 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
934 If you are using GNAT on a Windows platform, please note that
935 the ``@code{\}'' character should be used instead.
936 @end ifset
937
938
939
940 @c ****************************
941 @node Getting Started with GNAT
942 @chapter Getting Started with GNAT
943
944 @noindent
945 This chapter describes some simple ways of using GNAT to build
946 executable Ada programs.
947 @ifset unw
948 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
949 show how to use the command line environment.
950 @ref{Introduction to Glide and GVD}, provides a brief
951 introduction to the visually-oriented IDE for GNAT.
952 Supplementing Glide on some platforms is GPS, the
953 GNAT Programming System, which offers a richer graphical
954 ``look and feel'', enhanced configurability, support for
955 development in other programming language, comprehensive
956 browsing features, and many other capabilities.
957 For information on GPS please refer to
958 @cite{Using the GNAT Programming System}.
959 @end ifset
960
961 @menu
962 * Running GNAT::
963 * Running a Simple Ada Program::
964 * Running a Program with Multiple Units::
965 * Using the gnatmake Utility::
966 @ifset vms
967 * Editing with Emacs::
968 @end ifset
969 @ifclear vms
970 * Introduction to GPS::
971 * Introduction to Glide and GVD::
972 @end ifclear
973 @end menu
974
975 @node Running GNAT
976 @section Running GNAT
977
978 @noindent
979 Three steps are needed to create an executable file from an Ada source
980 file:
981
982 @enumerate
983 @item
984 The source file(s) must be compiled.
985 @item
986 The file(s) must be bound using the GNAT binder.
987 @item
988 All appropriate object files must be linked to produce an executable.
989 @end enumerate
990
991 @noindent
992 All three steps are most commonly handled by using the @code{gnatmake}
993 utility program that, given the name of the main program, automatically
994 performs the necessary compilation, binding and linking steps.
995
996
997 @node Running a Simple Ada Program
998 @section Running a Simple Ada Program
999
1000 @noindent
1001 Any text editor may be used to prepare an Ada program.
1002 @ifclear vms
1003 If @code{Glide} is
1004 used, the optional Ada mode may be helpful in laying out the program.
1005 @end ifclear
1006 The
1007 program text is a normal text file. We will suppose in our initial
1008 example that you have used your editor to prepare the following
1009 standard format text file:
1010
1011 @smallexample @c ada
1012 @cartouche
1013 with Ada.Text_IO; use Ada.Text_IO;
1014 procedure Hello is
1015 begin
1016    Put_Line ("Hello WORLD!");
1017 end Hello;
1018 @end cartouche
1019 @end smallexample
1020
1021 @noindent
1022 This file should be named @file{hello.adb}.
1023 With the normal default file naming conventions, GNAT requires
1024 that each file
1025 contain a single compilation unit whose file name is the
1026 unit name,
1027 with periods replaced by hyphens; the
1028 extension is @file{ads} for a
1029 spec and @file{adb} for a body.
1030 You can override this default file naming convention by use of the
1031 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1032 Alternatively, if you want to rename your files according to this default
1033 convention, which is probably more convenient if you will be using GNAT
1034 for all your compilations, then the @code{gnatchop} utility
1035 can be used to generate correctly-named source files
1036 (@pxref{Renaming Files Using gnatchop}).
1037
1038 You can compile the program using the following command (@code{$} is used
1039 as the command prompt in the examples in this document):
1040
1041 @smallexample
1042 $ gcc -c hello.adb
1043 @end smallexample
1044
1045 @noindent
1046 @code{gcc} is the command used to run the compiler. This compiler is
1047 capable of compiling programs in several languages, including Ada 95 and
1048 C. It assumes that you have given it an Ada program if the file extension is
1049 either @file{.ads} or @file{.adb}, and it will then call
1050 the GNAT compiler to compile the specified file.
1051
1052 @ifclear vms
1053 The @option{-c} switch is required. It tells @command{gcc} to only do a
1054 compilation. (For C programs, @command{gcc} can also do linking, but this
1055 capability is not used directly for Ada programs, so the @option{-c}
1056 switch must always be present.)
1057 @end ifclear
1058
1059 This compile command generates a file
1060 @file{hello.o}, which is the object
1061 file corresponding to your Ada program. It also generates
1062 an ``Ada Library Information'' file @file{hello.ali},
1063 which contains additional information used to check
1064 that an Ada program is consistent.
1065 To build an executable file,
1066 use @code{gnatbind} to bind the program
1067 and @code{gnatlink} to link it. The
1068 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1069 @file{ALI} file, but the default extension of @file{.ali} can
1070 be omitted. This means that in the most common case, the argument
1071 is simply the name of the main program:
1072
1073 @smallexample
1074 $ gnatbind hello
1075 $ gnatlink hello
1076 @end smallexample
1077
1078 @noindent
1079 A simpler method of carrying out these steps is to use
1080 @command{gnatmake},
1081 a master program that invokes all the required
1082 compilation, binding and linking tools in the correct order. In particular,
1083 @command{gnatmake} automatically recompiles any sources that have been
1084 modified since they were last compiled, or sources that depend
1085 on such modified sources, so that ``version skew'' is avoided.
1086 @cindex Version skew (avoided by @command{gnatmake})
1087
1088 @smallexample
1089 $ gnatmake hello.adb
1090 @end smallexample
1091
1092 @noindent
1093 The result is an executable program called @file{hello}, which can be
1094 run by entering:
1095
1096 @c The following should be removed (BMB 2001-01-23)
1097 @c @smallexample
1098 @c $ ^./hello^$ RUN HELLO^
1099 @c @end smallexample
1100
1101 @smallexample
1102 $ hello
1103 @end smallexample
1104
1105 @noindent
1106 assuming that the current directory is on the search path
1107 for executable programs.
1108
1109 @noindent
1110 and, if all has gone well, you will see
1111
1112 @smallexample
1113 Hello WORLD!
1114 @end smallexample
1115
1116 @noindent
1117 appear in response to this command.
1118
1119
1120 @c ****************************************
1121 @node Running a Program with Multiple Units
1122 @section Running a Program with Multiple Units
1123
1124 @noindent
1125 Consider a slightly more complicated example that has three files: a
1126 main program, and the spec and body of a package:
1127
1128 @smallexample @c ada
1129 @cartouche
1130 @group
1131 package Greetings is
1132    procedure Hello;
1133    procedure Goodbye;
1134 end Greetings;
1135
1136 with Ada.Text_IO; use Ada.Text_IO;
1137 package body Greetings is
1138    procedure Hello is
1139    begin
1140       Put_Line ("Hello WORLD!");
1141    end Hello;
1142
1143    procedure Goodbye is
1144    begin
1145       Put_Line ("Goodbye WORLD!");
1146    end Goodbye;
1147 end Greetings;
1148 @end group
1149
1150 @group
1151 with Greetings;
1152 procedure Gmain is
1153 begin
1154    Greetings.Hello;
1155    Greetings.Goodbye;
1156 end Gmain;
1157 @end group
1158 @end cartouche
1159 @end smallexample
1160
1161 @noindent
1162 Following the one-unit-per-file rule, place this program in the
1163 following three separate files:
1164
1165 @table @file
1166 @item greetings.ads
1167 spec of package @code{Greetings}
1168
1169 @item greetings.adb
1170 body of package @code{Greetings}
1171
1172 @item gmain.adb
1173 body of main program
1174 @end table
1175
1176 @noindent
1177 To build an executable version of
1178 this program, we could use four separate steps to compile, bind, and link
1179 the program, as follows:
1180
1181 @smallexample
1182 $ gcc -c gmain.adb
1183 $ gcc -c greetings.adb
1184 $ gnatbind gmain
1185 $ gnatlink gmain
1186 @end smallexample
1187
1188 @noindent
1189 Note that there is no required order of compilation when using GNAT.
1190 In particular it is perfectly fine to compile the main program first.
1191 Also, it is not necessary to compile package specs in the case where
1192 there is an accompanying body; you only need to compile the body. If you want
1193 to submit these files to the compiler for semantic checking and not code
1194 generation, then use the
1195 @option{-gnatc} switch:
1196
1197 @smallexample
1198 $ gcc -c greetings.ads -gnatc
1199 @end smallexample
1200
1201 @noindent
1202 Although the compilation can be done in separate steps as in the
1203 above example, in practice it is almost always more convenient
1204 to use the @code{gnatmake} tool. All you need to know in this case
1205 is the name of the main program's source file. The effect of the above four
1206 commands can be achieved with a single one:
1207
1208 @smallexample
1209 $ gnatmake gmain.adb
1210 @end smallexample
1211
1212 @noindent
1213 In the next section we discuss the advantages of using @code{gnatmake} in
1214 more detail.
1215
1216 @c *****************************
1217 @node Using the gnatmake Utility
1218 @section Using the @command{gnatmake} Utility
1219
1220 @noindent
1221 If you work on a program by compiling single components at a time using
1222 @code{gcc}, you typically keep track of the units you modify. In order to
1223 build a consistent system, you compile not only these units, but also any
1224 units that depend on the units you have modified.
1225 For example, in the preceding case,
1226 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1227 you edit @file{greetings.ads}, you must recompile both
1228 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1229 units that depend on @file{greetings.ads}.
1230
1231 @code{gnatbind} will warn you if you forget one of these compilation
1232 steps, so that it is impossible to generate an inconsistent program as a
1233 result of forgetting to do a compilation. Nevertheless it is tedious and
1234 error-prone to keep track of dependencies among units.
1235 One approach to handle the dependency-bookkeeping is to use a
1236 makefile. However, makefiles present maintenance problems of their own:
1237 if the dependencies change as you change the program, you must make
1238 sure that the makefile is kept up-to-date manually, which is also an
1239 error-prone process.
1240
1241 The @code{gnatmake} utility takes care of these details automatically.
1242 Invoke it using either one of the following forms:
1243
1244 @smallexample
1245 $ gnatmake gmain.adb
1246 $ gnatmake ^gmain^GMAIN^
1247 @end smallexample
1248
1249 @noindent
1250 The argument is the name of the file containing the main program;
1251 you may omit the extension. @code{gnatmake}
1252 examines the environment, automatically recompiles any files that need
1253 recompiling, and binds and links the resulting set of object files,
1254 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1255 In a large program, it
1256 can be extremely helpful to use @code{gnatmake}, because working out by hand
1257 what needs to be recompiled can be difficult.
1258
1259 Note that @code{gnatmake}
1260 takes into account all the Ada 95 rules that
1261 establish dependencies among units. These include dependencies that result
1262 from inlining subprogram bodies, and from
1263 generic instantiation. Unlike some other
1264 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1265 found by the compiler on a previous compilation, which may possibly
1266 be wrong when sources change. @code{gnatmake} determines the exact set of
1267 dependencies from scratch each time it is run.
1268
1269 @ifset vms
1270 @node Editing with Emacs
1271 @section Editing with Emacs
1272 @cindex Emacs
1273
1274 @noindent
1275 Emacs is an extensible self-documenting text editor that is available in a
1276 separate VMSINSTAL kit.
1277
1278 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1279 click on the Emacs Help menu and run the Emacs Tutorial.
1280 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1281 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1282
1283 Documentation on Emacs and other tools is available in Emacs under the
1284 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1285 use the middle mouse button to select a topic (e.g. Emacs).
1286
1287 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1288 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1289 get to the Emacs manual.
1290 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1291 prompt.
1292
1293 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1294 which is sufficiently extensible to provide for a complete programming
1295 environment and shell for the sophisticated user.
1296 @end ifset
1297
1298 @ifclear vms
1299 @node Introduction to GPS
1300 @section Introduction to GPS
1301 @cindex GPS (GNAT Programming System)
1302 @cindex GNAT Programming System (GPS)
1303 @noindent
1304 Although the command line interface (@command{gnatmake}, etc.) alone
1305 is sufficient, a graphical Interactive Development
1306 Environment can make it easier for you to compose, navigate, and debug
1307 programs.  This section describes the main features of GPS
1308 (``GNAT Programming System''), the GNAT graphical IDE.
1309 You will see how to use GPS to build and debug an executable, and
1310 you will also learn some of the basics of the GNAT ``project'' facility.
1311
1312 GPS enables you to do much more than is presented here;
1313 e.g., you can produce a call graph, interface to a third-party
1314 Version Control System, and inspect the generated assembly language
1315 for a program.
1316 Indeed, GPS also supports languages other than Ada.
1317 Such additional information, and an explanation of all of the GPS menu
1318 items. may be found in the on-line help, which includes
1319 a user's guide and a tutorial (these are also accessible from the GNAT
1320 startup menu).
1321
1322 @menu
1323 * Building a New Program with GPS::
1324 * Simple Debugging with GPS::
1325 @end menu
1326
1327
1328 @node Building a New Program with GPS
1329 @subsection Building a New Program with GPS
1330 @noindent
1331 GPS invokes the GNAT compilation tools using information
1332 contained in a @emph{project} (also known as a @emph{project file}):
1333 a collection of properties such
1334 as source directories, identities of main subprograms, tool switches, etc.,
1335 and their associated values.
1336 (See @ref{GNAT Project Manager}, for details.)
1337 In order to run GPS, you will need to either create a new project
1338 or else open an existing one.
1339
1340 This section will explain how you can use GPS to create a project,
1341 to associate Ada source files with a project, and to build and run
1342 programs.
1343
1344 @enumerate
1345 @item @emph{Creating a project}
1346
1347 Invoke GPS, either from the command line or the platform's IDE.
1348 After it starts, GPS will display a ``Welcome'' screen with three
1349 radio buttons:
1350
1351 @itemize @bullet
1352 @item
1353 @code{Start with default project in directory}
1354
1355 @item
1356 @code{Create new project with wizard}
1357
1358 @item
1359 @code{Open existing project}
1360 @end itemize
1361
1362 @noindent
1363 Select @code{Create new project with wizard} and press @code{OK}.
1364 A new window will appear.  In the text box labeled with
1365 @code{Enter the name of the project to create}, type @file{sample}
1366 as the project name.
1367 In the next box, browse to choose the directory in which you
1368 would like to create the project file.
1369 After selecting an appropriate directory, press @code{Forward}.
1370
1371 A window will appear with the title
1372 @code{Version Control System Configuration}.
1373 Simply press @code{Forward}.
1374
1375 A window will appear with the title
1376 @code{Please select the source directories for this project}.
1377 The directory that you specified for the project file will be selected
1378 by default as the one to use for sources; simply press @code{Forward}.
1379
1380 A window will appear with the title
1381 @code{Please select the build directory for this project}.
1382 The directory that you specified for the project file will be selected
1383 by default for object files and executables;
1384 simply press @code{Forward}.
1385
1386 A window will appear with the title
1387 @code{Please select the main units for this project}.
1388 You will supply this information later, after creating the source file.
1389 Simply press @code{Forward} for now.
1390
1391 A window will appear with the title
1392 @code{Please select the switches to build the project}.
1393 Press @code{Apply}.  This will create a project file named
1394 @file{sample.prj} in the directory that you had specified.
1395
1396 @item @emph{Creating and saving the source file}
1397
1398 After you create the new project, a GPS window will appear, which is
1399 partitioned into two main sections:
1400
1401 @itemize @bullet
1402 @item
1403 A @emph{Workspace area}, initially greyed out, which you will use for
1404 creating and editing source files
1405
1406 @item
1407 Directly below, a @emph{Messages area}, which initially displays a
1408 ``Welcome'' message.
1409 (If the Messages area is not visible, drag its border upward to expand it.)
1410 @end itemize
1411
1412 @noindent
1413 Select @code{File} on the menu bar, and then the @code{New} command.
1414 The Workspace area will become white, and you can now
1415 enter the source program explicitly.
1416 Type the following text
1417
1418 @smallexample @c ada
1419 @group
1420 with Ada.Text_IO; use Ada.Text_IO;
1421 procedure Hello is
1422 begin
1423   Put_Line("Hello from GPS!");
1424 end Hello;
1425 @end group
1426 @end smallexample
1427
1428 @noindent
1429 Select @code{File}, then @code{Save As}, and enter the source file name
1430 @file{hello.adb}.
1431 The file will be saved in the same directory you specified as the
1432 location of the default project file.
1433
1434
1435 @item @emph{Updating the project file}
1436
1437 You need to add the new source file to the project.
1438 To do this, select
1439 the @code{Project} menu and then @code{Edit project properties}.
1440 Click the @code{Main files} tab on the left, and then the
1441 @code{Add} button.
1442 Choose @file{hello.adb} from the list, and press @code{Open}.
1443 The project settings window will reflect this action.
1444 Click @code{OK}.
1445
1446 @item @emph{Building and running the program}
1447
1448 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1449 and select @file{hello.adb}.
1450 The Messages window will display the resulting invocations of @command{gcc},
1451 @command{gnatbind}, and @command{gnatlink}
1452 (reflecting the default switch settings from the
1453 project file that you created) and then a ``successful compilation/build''
1454 message.
1455
1456 To run the program, choose the @code{Build} menu, then @code{Run}, and
1457 select @command{hello}.
1458 An @emph{Arguments Selection} window will appear.
1459 There are no command line arguments, so just click @code{OK}.
1460
1461 The Messages window will now display the program's output (the string
1462 @code{Hello from GPS}), and at the bottom of the GPS window a status
1463 update is displayed (@code{Run: hello}).
1464 Close the GPS window (or select @code{File}, then @code{Exit}) to
1465 terminate this GPS session.
1466 @end enumerate
1467
1468
1469
1470 @node Simple Debugging with GPS
1471 @subsection Simple Debugging with GPS
1472 @noindent
1473 This section illustrates basic debugging techniques (setting breakpoints,
1474 examining/modifying variables, single stepping).
1475
1476 @enumerate
1477 @item @emph{Opening a project}
1478
1479 Start GPS and select @code{Open existing project}; browse to
1480 specify the project file @file{sample.prj} that you had created in the
1481 earlier example.
1482
1483 @item @emph{Creating a source file}
1484
1485 Select @code{File}, then @code{New}, and type in the following program:
1486
1487 @smallexample @c ada
1488 @group
1489 with Ada.Text_IO; use Ada.Text_IO;
1490 procedure Example is
1491    Line : String (1..80);
1492    N    : Natural;
1493 begin
1494    Put_Line("Type a line of text at each prompt; an empty line to exit");
1495    loop
1496       Put(": ");
1497       Get_Line (Line, N);
1498       Put_Line (Line (1..N) );
1499       exit when N=0;
1500    end loop;
1501 end Example;
1502 @end group
1503 @end smallexample
1504
1505 @noindent
1506 Select @code{File}, then @code{Save as}, and enter the file name
1507 @file{example.adb}.
1508
1509 @item @emph{Updating the project file}
1510
1511 Add @code{Example} as a new main unit for the project:
1512 @enumerate a
1513 @item
1514 Select @code{Project}, then @code{Edit Project Properties}.
1515
1516 @item
1517 Select the @code{Main files} tab, click @code{Add}, then
1518 select the file @file{example.adb} from the list, and
1519 click @code{Open}.
1520 You will see the file name appear in the list of main units
1521
1522 @item
1523 Click @code{OK}
1524 @end enumerate
1525
1526 @item @emph{Building/running the executable}
1527
1528 To build the executable
1529 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1530
1531 Run the program to see its effect (in the Messages area).
1532 Each line that you enter is displayed; an empty line will
1533 cause the loop to exit and the program to terminate.
1534
1535 @item @emph{Debugging the program}
1536
1537 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1538 which are required for debugging, are on by default when you create
1539 a new project.
1540 Thus unless you intentionally remove these settings, you will be able
1541 to debug any program that you develop using GPS.
1542
1543 @enumerate a
1544 @item @emph{Initializing}
1545
1546 Select @code{Debug}, then @code{Initialize}, then @file{example}
1547
1548 @item @emph{Setting a breakpoint}
1549
1550 After performing the initialization step, you will observe a small
1551 icon to the right of each line number.
1552 This serves as a toggle for breakpoints; clicking the icon will
1553 set a breakpoint at the corresponding line (the icon will change to
1554 a red circle with an ``x''), and clicking it again
1555 will remove the breakpoint / reset the icon.
1556
1557 For purposes of this example, set a breakpoint at line 10 (the
1558 statement @code{Put_Line@ (Line@ (1..N));}
1559
1560 @item @emph{Starting program execution}
1561
1562 Select @code{Debug}, then @code{Run}.  When the
1563 @code{Program Arguments} window appears, click @code{OK}.
1564 A console window will appear; enter some line of text,
1565 e.g. @code{abcde}, at the prompt.
1566 The program will pause execution when it gets to the
1567 breakpoint, and the corresponding line is highlighted.
1568
1569 @item @emph{Examining a variable}
1570
1571 Move the mouse over one of the occurrences of the variable @code{N}.
1572 You will see the value (5) displayed, in ``tool tip'' fashion.
1573 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1574 You will see information about @code{N} appear in the @code{Debugger Data}
1575 pane, showing the value as 5.
1576
1577
1578 @item @emph{Assigning a new value to a variable}
1579
1580 Right click on the @code{N} in the @code{Debugger Data} pane, and
1581 select @code{Set value of N}.
1582 When the input window appears, enter the value @code{4} and click
1583 @code{OK}.
1584 This value does not automatically appear in the @code{Debugger Data}
1585 pane; to see it, right click again on the @code{N} in the
1586 @code{Debugger Data} pane and select @code{Update value}.
1587 The new value, 4, will appear in red.
1588
1589 @item @emph{Single stepping}
1590
1591 Select @code{Debug}, then @code{Next}.
1592 This will cause the next statement to be executed, in this case the
1593 call of @code{Put_Line} with the string slice.
1594 Notice in the console window that the displayed string is simply
1595 @code{abcd} and not @code{abcde} which you had entered.
1596 This is because the upper bound of the slice is now 4 rather than 5.
1597
1598 @item @emph{Removing a breakpoint}
1599
1600 Toggle the breakpoint icon at line 10.
1601
1602 @item @emph{Resuming execution from a breakpoint}
1603
1604 Select @code{Debug}, then @code{Continue}.
1605 The program will reach the next iteration of the loop, and
1606 wait for input after displaying the prompt.
1607 This time, just hit the @kbd{Enter} key.
1608 The value of @code{N} will be 0, and the program will terminate.
1609 The console window will disappear.
1610 @end enumerate
1611 @end enumerate
1612
1613
1614 @node Introduction to Glide and GVD
1615 @section Introduction to Glide and GVD
1616 @cindex Glide
1617 @cindex GVD
1618 @noindent
1619 This section describes the main features of Glide,
1620 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1621 the GNU Visual Debugger.
1622 These tools may be present in addition to, or in place of, GPS on some
1623 platforms.
1624 Additional information on Glide and GVD may be found
1625 in the on-line help for these tools.
1626
1627 @menu
1628 * Building a New Program with Glide::
1629 * Simple Debugging with GVD::
1630 * Other Glide Features::
1631 @end menu
1632
1633 @node Building a New Program with Glide
1634 @subsection Building a New Program with Glide
1635 @noindent
1636 The simplest way to invoke Glide is to enter @command{glide}
1637 at the command prompt.  It will generally be useful to issue this
1638 as a background command, thus allowing you to continue using
1639 your command window for other purposes while Glide is running:
1640
1641 @smallexample
1642 $ glide&
1643 @end smallexample
1644
1645 @noindent
1646 Glide will start up with an initial screen displaying the top-level menu items
1647 as well as some other information.  The menu selections are as follows
1648 @itemize @bullet
1649 @item @code{Buffers}
1650 @item @code{Files}
1651 @item @code{Tools}
1652 @item @code{Edit}
1653 @item @code{Search}
1654 @item @code{Mule}
1655 @item @code{Glide}
1656 @item @code{Help}
1657 @end itemize
1658
1659 @noindent
1660 For this introductory example, you will need to create a new Ada source file.
1661 First, select the @code{Files} menu.  This will pop open a menu with around
1662 a dozen or so items.  To create a file, select the @code{Open file...} choice.
1663 Depending on the platform, you may see a pop-up window where you can browse
1664 to an appropriate directory and then enter the file name, or else simply
1665 see a line at the bottom of the Glide window where you can likewise enter
1666 the file name.  Note that in Glide, when you attempt to open a non-existent
1667 file, the effect is to create a file with that name.  For this example enter
1668 @file{hello.adb} as the name of the file.
1669
1670 A new buffer will now appear, occupying the entire Glide window,
1671 with the file name at the top.  The menu selections are slightly different
1672 from the ones you saw on the opening screen; there is an @code{Entities} item,
1673 and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses
1674 the file extension to identify the source language, so @file{adb} indicates
1675 an Ada source file.
1676
1677 You will enter some of the source program lines explicitly,
1678 and use the syntax-oriented template mechanism to enter other lines.
1679 First, type the following text:
1680 @smallexample
1681 with Ada.Text_IO; use Ada.Text_IO;
1682 procedure Hello is
1683 begin
1684 @end smallexample
1685
1686 @noindent
1687 Observe that Glide uses different colors to distinguish reserved words from
1688 identifiers.  Also, after the @code{procedure Hello is} line, the cursor is
1689 automatically indented in anticipation of declarations.  When you enter
1690 @code{begin}, Glide recognizes that there are no declarations and thus places
1691 @code{begin} flush left.  But after the @code{begin} line the cursor is again
1692 indented, where the statement(s) will be placed.
1693
1694 The main part of the program will be a @code{for} loop.  Instead of entering
1695 the text explicitly, however, use a statement template.  Select the @code{Ada}
1696 item on the top menu bar, move the mouse to the @code{Statements} item,
1697 and you will see a large selection of alternatives.  Choose @code{for loop}.
1698 You will be prompted (at the bottom of the buffer) for a loop name;
1699 simply press the @key{Enter} key since a loop name is not needed.
1700 You should see the beginning of a @code{for} loop appear in the source
1701 program window.  You will now be prompted for the name of the loop variable;
1702 enter a line with the identifier @code{ind} (lower case).  Note that,
1703 by default, Glide capitalizes the name (you can override such behavior
1704 if you wish, although this is outside the scope of this introduction).
1705 Next, Glide prompts you for the loop range; enter a line containing
1706 @code{1..5} and you will see this also appear in the source program,
1707 together with the remaining elements of the @code{for} loop syntax.
1708
1709 Next enter the statement (with an intentional error, a missing semicolon)
1710 that will form the body of the loop:
1711 @smallexample
1712 Put_Line("Hello, World" & Integer'Image(I))
1713 @end smallexample
1714
1715 @noindent
1716 Finally, type @code{end Hello;} as the last line in the program.
1717 Now save the file: choose the @code{File} menu item, and then the
1718 @code{Save buffer} selection.  You will see a message at the bottom
1719 of the buffer confirming that the file has been saved.
1720
1721 You are now ready to attempt to build the program.  Select the @code{Ada}
1722 item from the top menu bar.  Although we could choose simply to compile
1723 the file, we will instead attempt to do a build (which invokes
1724 @command{gnatmake}) since, if the compile is successful, we want to build
1725 an executable.  Thus select @code{Ada build}.  This will fail because of the
1726 compilation error, and you will notice that the Glide window has been split:
1727 the top window contains the source file, and the bottom window contains the
1728 output from the GNAT tools. Glide allows you to navigate from a compilation
1729 error to the source file position corresponding to the error: click the
1730 middle mouse button (or simultaneously press the left and right buttons,
1731 on a two-button mouse) on the diagnostic line in the tool window.  The
1732 focus will shift to the source window, and the cursor will be positioned
1733 on the character at which the error was detected.
1734
1735 Correct the error: type in a semicolon to terminate the statement.
1736 Although you can again save the file explicitly, you can also simply invoke
1737 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1738 This time the build will succeed; the tool output window shows you the
1739 options that are supplied by default.  The GNAT tools' output (e.g.
1740 object and ALI files, executable) will go in the directory from which
1741 Glide was launched.
1742
1743 To execute the program, choose @code{Ada} and then @code{Run}.
1744 You should see the program's output displayed in the bottom window:
1745
1746 @smallexample
1747 Hello, world 1
1748 Hello, world 2
1749 Hello, world 3
1750 Hello, world 4
1751 Hello, world 5
1752 @end smallexample
1753
1754 @node Simple Debugging with GVD
1755 @subsection Simple Debugging with GVD
1756
1757 @noindent
1758 This section describes how to set breakpoints, examine/modify variables,
1759 and step through execution.
1760
1761 In order to enable debugging, you need to pass the @option{-g} switch
1762 to both the compiler and to @command{gnatlink}.  If you are using
1763 the command line, passing @option{-g} to @command{gnatmake} will have
1764 this effect.  You can then launch GVD, e.g. on the @code{hello} program,
1765 by issuing the command:
1766
1767 @smallexample
1768 $ gvd hello
1769 @end smallexample
1770
1771 @noindent
1772 If you are using Glide, then @option{-g} is passed to the relevant tools
1773 by default when you do a build.  Start the debugger by selecting the
1774 @code{Ada} menu item, and then @code{Debug}.
1775
1776 GVD comes up in a multi-part window.  One pane shows the names of files
1777 comprising your executable; another pane shows the source code of the current
1778 unit (initially your main subprogram), another pane shows the debugger output
1779 and user interactions, and the fourth pane (the data canvas at the top
1780 of the window) displays data objects that you have selected.
1781
1782 To the left of the source file pane, you will notice green dots adjacent
1783 to some lines.  These are lines for which object code exists and where
1784 breakpoints can thus be set.  You set/reset a breakpoint by clicking
1785 the green dot.  When a breakpoint is set, the dot is replaced by an @code{X}
1786 in a red circle.  Clicking the circle toggles the breakpoint off,
1787 and the red circle is replaced by the green dot.
1788
1789 For this example, set a breakpoint at the statement where @code{Put_Line}
1790 is invoked.
1791
1792 Start program execution by selecting the @code{Run} button on the top menu bar.
1793 (The @code{Start} button will also start your program, but it will
1794 cause program execution to break at the entry to your main subprogram.)
1795 Evidence of reaching the breakpoint will appear: the source file line will be
1796 highlighted, and the debugger interactions pane will display
1797 a relevant message.
1798
1799 You can examine the values of variables in several ways.  Move the mouse
1800 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1801 the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind}
1802 and select @code{Display Ind}; a box showing the variable's name and value
1803 will appear in the data canvas.
1804
1805 Although a loop index is a constant with respect to Ada semantics,
1806 you can change its value in the debugger.  Right-click in the box
1807 for @code{Ind}, and select the @code{Set Value of Ind} item.
1808 Enter @code{2} as the new value, and press @command{OK}.
1809 The box for @code{Ind} shows the update.
1810
1811 Press the @code{Step} button on the top menu bar; this will step through
1812 one line of program text (the invocation of @code{Put_Line}), and you can
1813 observe the effect of having modified @code{Ind} since the value displayed
1814 is @code{2}.
1815
1816 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1817 button.  You will see the remaining output lines displayed in the debugger
1818 interaction window, along with a message confirming normal program
1819 termination.
1820
1821 @node Other Glide Features
1822 @subsection Other Glide Features
1823
1824 @noindent
1825 You may have observed that some of the menu selections contain abbreviations;
1826 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1827 These are @emph{shortcut keys} that you can use instead of selecting
1828 menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1829 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1830 of selecting @code{Files} and then @code{Open file...}.
1831
1832 To abort a Glide command, type @key{Ctrl-g}.
1833
1834 If you want Glide to start with an existing source file, you can either
1835 launch Glide as above and then open the file via @code{Files} @result{}
1836 @code{Open file...}, or else simply pass the name of the source file
1837 on the command line:
1838
1839 @smallexample
1840 $ glide hello.adb&
1841 @end smallexample
1842
1843 @noindent
1844 While you are using Glide, a number of @emph{buffers} exist.
1845 You create some explicitly; e.g., when you open/create a file.
1846 Others arise as an effect of the commands that you issue; e.g., the buffer
1847 containing the output of the tools invoked during a build.  If a buffer
1848 is hidden, you can bring it into a visible window by first opening
1849 the @code{Buffers} menu and then selecting the desired entry.
1850
1851 If a buffer occupies only part of the Glide screen and you want to expand it
1852 to fill the entire screen, then click in the buffer and then select
1853 @code{Files} @result{} @code{One Window}.
1854
1855 If a window is occupied by one buffer and you want to split the window
1856 to bring up a second buffer, perform the following steps:
1857 @itemize @bullet
1858 @item Select @code{Files} @result{} @code{Split Window};
1859 this will produce two windows each of which holds the original buffer
1860 (these are not copies, but rather different views of the same buffer contents)
1861
1862 @item With the focus in one of the windows,
1863 select the desired buffer from the @code{Buffers} menu
1864 @end itemize
1865
1866 @noindent
1867 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1868 @end ifclear
1869
1870 @node The GNAT Compilation Model
1871 @chapter The GNAT Compilation Model
1872 @cindex GNAT compilation model
1873 @cindex Compilation model
1874
1875 @menu
1876 * Source Representation::
1877 * Foreign Language Representation::
1878 * File Naming Rules::
1879 * Using Other File Names::
1880 * Alternative File Naming Schemes::
1881 * Generating Object Files::
1882 * Source Dependencies::
1883 * The Ada Library Information Files::
1884 * Binding an Ada Program::
1885 * Mixed Language Programming::
1886 * Building Mixed Ada & C++ Programs::
1887 * Comparison between GNAT and C/C++ Compilation Models::
1888 * Comparison between GNAT and Conventional Ada Library Models::
1889 @ifset vms
1890 * Placement of temporary files::
1891 @end ifset
1892 @end menu
1893
1894 @noindent
1895 This chapter describes the compilation model used by GNAT. Although
1896 similar to that used by other languages, such as C and C++, this model
1897 is substantially different from the traditional Ada compilation models,
1898 which are based on a library. The model is initially described without
1899 reference to the library-based model. If you have not previously used an
1900 Ada compiler, you need only read the first part of this chapter. The
1901 last section describes and discusses the differences between the GNAT
1902 model and the traditional Ada compiler models. If you have used other
1903 Ada compilers, this section will help you to understand those
1904 differences, and the advantages of the GNAT model.
1905
1906 @node Source Representation
1907 @section Source Representation
1908 @cindex Latin-1
1909
1910 @noindent
1911 Ada source programs are represented in standard text files, using
1912 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1913 7-bit ASCII set, plus additional characters used for
1914 representing foreign languages (@pxref{Foreign Language Representation}
1915 for support of non-USA character sets). The format effector characters
1916 are represented using their standard ASCII encodings, as follows:
1917
1918 @table @code
1919 @item VT
1920 @findex VT
1921 Vertical tab, @code{16#0B#}
1922
1923 @item HT
1924 @findex HT
1925 Horizontal tab, @code{16#09#}
1926
1927 @item CR
1928 @findex CR
1929 Carriage return, @code{16#0D#}
1930
1931 @item LF
1932 @findex LF
1933 Line feed, @code{16#0A#}
1934
1935 @item FF
1936 @findex FF
1937 Form feed, @code{16#0C#}
1938 @end table
1939
1940 @noindent
1941 Source files are in standard text file format. In addition, GNAT will
1942 recognize a wide variety of stream formats, in which the end of physical
1943 physical lines is marked by any of the following sequences:
1944 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1945 in accommodating files that are imported from other operating systems.
1946
1947 @cindex End of source file
1948 @cindex Source file, end
1949 @findex SUB
1950 The end of a source file is normally represented by the physical end of
1951 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1952 recognized as signalling the end of the source file. Again, this is
1953 provided for compatibility with other operating systems where this
1954 code is used to represent the end of file.
1955
1956 Each file contains a single Ada compilation unit, including any pragmas
1957 associated with the unit. For example, this means you must place a
1958 package declaration (a package @dfn{spec}) and the corresponding body in
1959 separate files. An Ada @dfn{compilation} (which is a sequence of
1960 compilation units) is represented using a sequence of files. Similarly,
1961 you will place each subunit or child unit in a separate file.
1962
1963 @node Foreign Language Representation
1964 @section Foreign Language Representation
1965
1966 @noindent
1967 GNAT supports the standard character sets defined in Ada 95 as well as
1968 several other non-standard character sets for use in localized versions
1969 of the compiler (@pxref{Character Set Control}).
1970 @menu
1971 * Latin-1::
1972 * Other 8-Bit Codes::
1973 * Wide Character Encodings::
1974 @end menu
1975
1976 @node Latin-1
1977 @subsection Latin-1
1978 @cindex Latin-1
1979
1980 @noindent
1981 The basic character set is Latin-1. This character set is defined by ISO
1982 standard 8859, part 1. The lower half (character codes @code{16#00#}
1983 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1984 is used to represent additional characters. These include extended letters
1985 used by European languages, such as French accents, the vowels with umlauts
1986 used in German, and the extra letter A-ring used in Swedish.
1987
1988 @findex Ada.Characters.Latin_1
1989 For a complete list of Latin-1 codes and their encodings, see the source
1990 file of library unit @code{Ada.Characters.Latin_1} in file
1991 @file{a-chlat1.ads}.
1992 You may use any of these extended characters freely in character or
1993 string literals. In addition, the extended characters that represent
1994 letters can be used in identifiers.
1995
1996 @node Other 8-Bit Codes
1997 @subsection Other 8-Bit Codes
1998
1999 @noindent
2000 GNAT also supports several other 8-bit coding schemes:
2001
2002 @table @asis
2003 @item ISO 8859-2 (Latin-2)
2004 @cindex Latin-2
2005 @cindex ISO 8859-2
2006 Latin-2 letters allowed in identifiers, with uppercase and lowercase
2007 equivalence.
2008
2009 @item ISO 8859-3 (Latin-3)
2010 @cindex Latin-3
2011 @cindex ISO 8859-3
2012 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2013 equivalence.
2014
2015 @item ISO 8859-4 (Latin-4)
2016 @cindex Latin-4
2017 @cindex ISO 8859-4
2018 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2019 equivalence.
2020
2021 @item ISO 8859-5 (Cyrillic)
2022 @cindex ISO 8859-5
2023 @cindex Cyrillic
2024 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2025 lowercase equivalence.
2026
2027 @item ISO 8859-15 (Latin-9)
2028 @cindex ISO 8859-15
2029 @cindex Latin-9
2030 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2031 lowercase equivalence
2032
2033 @item IBM PC (code page 437)
2034 @cindex code page 437
2035 This code page is the normal default for PCs in the U.S. It corresponds
2036 to the original IBM PC character set. This set has some, but not all, of
2037 the extended Latin-1 letters, but these letters do not have the same
2038 encoding as Latin-1. In this mode, these letters are allowed in
2039 identifiers with uppercase and lowercase equivalence.
2040
2041 @item IBM PC (code page 850)
2042 @cindex code page 850
2043 This code page is a modification of 437 extended to include all the
2044 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2045 mode, all these letters are allowed in identifiers with uppercase and
2046 lowercase equivalence.
2047
2048 @item Full Upper 8-bit
2049 Any character in the range 80-FF allowed in identifiers, and all are
2050 considered distinct. In other words, there are no uppercase and lowercase
2051 equivalences in this range. This is useful in conjunction with
2052 certain encoding schemes used for some foreign character sets (e.g.
2053 the typical method of representing Chinese characters on the PC).
2054
2055 @item No Upper-Half
2056 No upper-half characters in the range 80-FF are allowed in identifiers.
2057 This gives Ada 83 compatibility for identifier names.
2058 @end table
2059
2060 @noindent
2061 For precise data on the encodings permitted, and the uppercase and lowercase
2062 equivalences that are recognized, see the file @file{csets.adb} in
2063 the GNAT compiler sources. You will need to obtain a full source release
2064 of GNAT to obtain this file.
2065
2066 @node Wide Character Encodings
2067 @subsection Wide Character Encodings
2068
2069 @noindent
2070 GNAT allows wide character codes to appear in character and string
2071 literals, and also optionally in identifiers, by means of the following
2072 possible encoding schemes:
2073
2074 @table @asis
2075
2076 @item Hex Coding
2077 In this encoding, a wide character is represented by the following five
2078 character sequence:
2079
2080 @smallexample
2081 ESC a b c d
2082 @end smallexample
2083
2084 @noindent
2085 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2086 characters (using uppercase letters) of the wide character code. For
2087 example, ESC A345 is used to represent the wide character with code
2088 @code{16#A345#}.
2089 This scheme is compatible with use of the full Wide_Character set.
2090
2091 @item Upper-Half Coding
2092 @cindex Upper-Half Coding
2093 The wide character with encoding @code{16#abcd#} where the upper bit is on
2094 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2095 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2096 character, but is not required to be in the upper half. This method can
2097 be also used for shift-JIS or EUC, where the internal coding matches the
2098 external coding.
2099
2100 @item Shift JIS Coding
2101 @cindex Shift JIS Coding
2102 A wide character is represented by a two-character sequence,
2103 @code{16#ab#} and
2104 @code{16#cd#}, with the restrictions described for upper-half encoding as
2105 described above. The internal character code is the corresponding JIS
2106 character according to the standard algorithm for Shift-JIS
2107 conversion. Only characters defined in the JIS code set table can be
2108 used with this encoding method.
2109
2110 @item EUC Coding
2111 @cindex EUC Coding
2112 A wide character is represented by a two-character sequence
2113 @code{16#ab#} and
2114 @code{16#cd#}, with both characters being in the upper half. The internal
2115 character code is the corresponding JIS character according to the EUC
2116 encoding algorithm. Only characters defined in the JIS code set table
2117 can be used with this encoding method.
2118
2119 @item UTF-8 Coding
2120 A wide character is represented using
2121 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2122 10646-1/Am.2. Depending on the character value, the representation
2123 is a one, two, or three byte sequence:
2124 @smallexample
2125 @iftex
2126 @leftskip=.7cm
2127 @end iftex
2128 16#0000#-16#007f#: 2#0xxxxxxx#
2129 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2130 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2131
2132 @end smallexample
2133
2134 @noindent
2135 where the xxx bits correspond to the left-padded bits of the
2136 16-bit character value. Note that all lower half ASCII characters
2137 are represented as ASCII bytes and all upper half characters and
2138 other wide characters are represented as sequences of upper-half
2139 (The full UTF-8 scheme allows for encoding 31-bit characters as
2140 6-byte sequences, but in this implementation, all UTF-8 sequences
2141 of four or more bytes length will be treated as illegal).
2142 @item Brackets Coding
2143 In this encoding, a wide character is represented by the following eight
2144 character sequence:
2145
2146 @smallexample
2147 [ " a b c d " ]
2148 @end smallexample
2149
2150 @noindent
2151 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2152 characters (using uppercase letters) of the wide character code. For
2153 example, [``A345''] is used to represent the wide character with code
2154 @code{16#A345#}. It is also possible (though not required) to use the
2155 Brackets coding for upper half characters. For example, the code
2156 @code{16#A3#} can be represented as @code{[``A3'']}.
2157
2158 This scheme is compatible with use of the full Wide_Character set,
2159 and is also the method used for wide character encoding in the standard
2160 ACVC (Ada Compiler Validation Capability) test suite distributions.
2161
2162 @end table
2163
2164 @noindent
2165 Note: Some of these coding schemes do not permit the full use of the
2166 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2167 use of the upper half of the Latin-1 set.
2168
2169 @node File Naming Rules
2170 @section File Naming Rules
2171
2172 @noindent
2173 The default file name is determined by the name of the unit that the
2174 file contains. The name is formed by taking the full expanded name of
2175 the unit and replacing the separating dots with hyphens and using
2176 ^lowercase^uppercase^ for all letters.
2177
2178 An exception arises if the file name generated by the above rules starts
2179 with one of the characters
2180 @ifset vms
2181 A,G,I, or S,
2182 @end ifset
2183 @ifclear vms
2184 a,g,i, or s,
2185 @end ifclear
2186 and the second character is a
2187 minus. In this case, the character ^tilde^dollar sign^ is used in place
2188 of the minus. The reason for this special rule is to avoid clashes with
2189 the standard names for child units of the packages System, Ada,
2190 Interfaces, and GNAT, which use the prefixes
2191 @ifset vms
2192 S- A- I- and G-
2193 @end ifset
2194 @ifclear vms
2195 s- a- i- and g-
2196 @end ifclear
2197 respectively.
2198
2199 The file extension is @file{.ads} for a spec and
2200 @file{.adb} for a body. The following list shows some
2201 examples of these rules.
2202
2203 @table @file
2204 @item main.ads
2205 Main (spec)
2206 @item main.adb
2207 Main (body)
2208 @item arith_functions.ads
2209 Arith_Functions (package spec)
2210 @item arith_functions.adb
2211 Arith_Functions (package body)
2212 @item func-spec.ads
2213 Func.Spec (child package spec)
2214 @item func-spec.adb
2215 Func.Spec (child package body)
2216 @item main-sub.adb
2217 Sub (subunit of Main)
2218 @item ^a~bad.adb^A$BAD.ADB^
2219 A.Bad (child package body)
2220 @end table
2221
2222 @noindent
2223 Following these rules can result in excessively long
2224 file names if corresponding
2225 unit names are long (for example, if child units or subunits are
2226 heavily nested). An option is available to shorten such long file names
2227 (called file name ``krunching''). This may be particularly useful when
2228 programs being developed with GNAT are to be used on operating systems
2229 with limited file name lengths. @xref{Using gnatkr}.
2230
2231 Of course, no file shortening algorithm can guarantee uniqueness over
2232 all possible unit names; if file name krunching is used, it is your
2233 responsibility to ensure no name clashes occur. Alternatively you
2234 can specify the exact file names that you want used, as described
2235 in the next section. Finally, if your Ada programs are migrating from a
2236 compiler with a different naming convention, you can use the gnatchop
2237 utility to produce source files that follow the GNAT naming conventions.
2238 (For details @pxref{Renaming Files Using gnatchop}.)
2239
2240 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2241 systems, case is not significant. So for example on @code{Windows XP}
2242 if the canonical name is @code{main-sub.adb}, you can use the file name
2243 @code{Main-Sub.adb} instead. However, case is significant for other
2244 operating systems, so for example, if you want to use other than
2245 canonically cased file names on a Unix system, you need to follow
2246 the procedures described in the next section.
2247
2248 @node Using Other File Names
2249 @section Using Other File Names
2250 @cindex File names
2251
2252 @noindent
2253 In the previous section, we have described the default rules used by
2254 GNAT to determine the file name in which a given unit resides. It is
2255 often convenient to follow these default rules, and if you follow them,
2256 the compiler knows without being explicitly told where to find all
2257 the files it needs.
2258
2259 However, in some cases, particularly when a program is imported from
2260 another Ada compiler environment, it may be more convenient for the
2261 programmer to specify which file names contain which units. GNAT allows
2262 arbitrary file names to be used by means of the Source_File_Name pragma.
2263 The form of this pragma is as shown in the following examples:
2264 @cindex Source_File_Name pragma
2265
2266 @smallexample @c ada
2267 @cartouche
2268 pragma Source_File_Name (My_Utilities.Stacks,
2269   Spec_File_Name => "myutilst_a.ada");
2270 pragma Source_File_name (My_Utilities.Stacks,
2271   Body_File_Name => "myutilst.ada");
2272 @end cartouche
2273 @end smallexample
2274
2275 @noindent
2276 As shown in this example, the first argument for the pragma is the unit
2277 name (in this example a child unit). The second argument has the form
2278 of a named association. The identifier
2279 indicates whether the file name is for a spec or a body;
2280 the file name itself is given by a string literal.
2281
2282 The source file name pragma is a configuration pragma, which means that
2283 normally it will be placed in the @file{gnat.adc}
2284 file used to hold configuration
2285 pragmas that apply to a complete compilation environment.
2286 For more details on how the @file{gnat.adc} file is created and used
2287 @pxref{Handling of Configuration Pragmas}
2288 @cindex @file{gnat.adc}
2289
2290 @ifclear vms
2291 GNAT allows completely arbitrary file names to be specified using the
2292 source file name pragma. However, if the file name specified has an
2293 extension other than @file{.ads} or @file{.adb} it is necessary to use
2294 a special syntax when compiling the file. The name in this case must be
2295 preceded by the special sequence @code{-x} followed by a space and the name
2296 of the language, here @code{ada}, as in:
2297
2298 @smallexample
2299 $ gcc -c -x ada peculiar_file_name.sim
2300 @end smallexample
2301 @end ifclear
2302
2303 @noindent
2304 @code{gnatmake} handles non-standard file names in the usual manner (the
2305 non-standard file name for the main program is simply used as the
2306 argument to gnatmake). Note that if the extension is also non-standard,
2307 then it must be included in the gnatmake command, it may not be omitted.
2308
2309 @node Alternative File Naming Schemes
2310 @section Alternative File Naming Schemes
2311 @cindex File naming schemes, alternative
2312 @cindex File names
2313
2314 In the previous section, we described the use of the @code{Source_File_Name}
2315 pragma to allow arbitrary names to be assigned to individual source files.
2316 However, this approach requires one pragma for each file, and especially in
2317 large systems can result in very long @file{gnat.adc} files, and also create
2318 a maintenance problem.
2319
2320 GNAT also provides a facility for specifying systematic file naming schemes
2321 other than the standard default naming scheme previously described. An
2322 alternative scheme for naming is specified by the use of
2323 @code{Source_File_Name} pragmas having the following format:
2324 @cindex Source_File_Name pragma
2325
2326 @smallexample @c ada
2327 pragma Source_File_Name (
2328    Spec_File_Name  => FILE_NAME_PATTERN
2329  [,Casing          => CASING_SPEC]
2330  [,Dot_Replacement => STRING_LITERAL]);
2331
2332 pragma Source_File_Name (
2333    Body_File_Name  => FILE_NAME_PATTERN
2334  [,Casing          => CASING_SPEC]
2335  [,Dot_Replacement => STRING_LITERAL]);
2336
2337 pragma Source_File_Name (
2338    Subunit_File_Name  => FILE_NAME_PATTERN
2339  [,Casing             => CASING_SPEC]
2340  [,Dot_Replacement    => STRING_LITERAL]);
2341
2342 FILE_NAME_PATTERN ::= STRING_LITERAL
2343 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2344 @end smallexample
2345
2346 @noindent
2347 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2348 It contains a single asterisk character, and the unit name is substituted
2349 systematically for this asterisk. The optional parameter
2350 @code{Casing} indicates
2351 whether the unit name is to be all upper-case letters, all lower-case letters,
2352 or mixed-case. If no
2353 @code{Casing} parameter is used, then the default is all
2354 ^lower-case^upper-case^.
2355
2356 The optional @code{Dot_Replacement} string is used to replace any periods
2357 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2358 argument is used then separating dots appear unchanged in the resulting
2359 file name.
2360 Although the above syntax indicates that the
2361 @code{Casing} argument must appear
2362 before the @code{Dot_Replacement} argument, but it
2363 is also permissible to write these arguments in the opposite order.
2364
2365 As indicated, it is possible to specify different naming schemes for
2366 bodies, specs, and subunits. Quite often the rule for subunits is the
2367 same as the rule for bodies, in which case, there is no need to give
2368 a separate @code{Subunit_File_Name} rule, and in this case the
2369 @code{Body_File_name} rule is used for subunits as well.
2370
2371 The separate rule for subunits can also be used to implement the rather
2372 unusual case of a compilation environment (e.g. a single directory) which
2373 contains a subunit and a child unit with the same unit name. Although
2374 both units cannot appear in the same partition, the Ada Reference Manual
2375 allows (but does not require) the possibility of the two units coexisting
2376 in the same environment.
2377
2378 The file name translation works in the following steps:
2379
2380 @itemize @bullet
2381
2382 @item
2383 If there is a specific @code{Source_File_Name} pragma for the given unit,
2384 then this is always used, and any general pattern rules are ignored.
2385
2386 @item
2387 If there is a pattern type @code{Source_File_Name} pragma that applies to
2388 the unit, then the resulting file name will be used if the file exists. If
2389 more than one pattern matches, the latest one will be tried first, and the
2390 first attempt resulting in a reference to a file that exists will be used.
2391
2392 @item
2393 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2394 for which the corresponding file exists, then the standard GNAT default
2395 naming rules are used.
2396
2397 @end itemize
2398
2399 @noindent
2400 As an example of the use of this mechanism, consider a commonly used scheme
2401 in which file names are all lower case, with separating periods copied
2402 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2403 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2404 two pragmas appear:
2405
2406 @smallexample @c ada
2407 pragma Source_File_Name
2408   (Spec_File_Name => "*.1.ada");
2409 pragma Source_File_Name
2410   (Body_File_Name => "*.2.ada");
2411 @end smallexample
2412
2413 @noindent
2414 The default GNAT scheme is actually implemented by providing the following
2415 default pragmas internally:
2416
2417 @smallexample @c ada
2418 pragma Source_File_Name
2419   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2420 pragma Source_File_Name
2421   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2422 @end smallexample
2423
2424 @noindent
2425 Our final example implements a scheme typically used with one of the
2426 Ada 83 compilers, where the separator character for subunits was ``__''
2427 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2428 by adding @file{.ADA}, and subunits by
2429 adding @file{.SEP}. All file names were
2430 upper case. Child units were not present of course since this was an
2431 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2432 the same double underscore separator for child units.
2433
2434 @smallexample @c ada
2435 pragma Source_File_Name
2436   (Spec_File_Name => "*_.ADA",
2437    Dot_Replacement => "__",
2438    Casing = Uppercase);
2439 pragma Source_File_Name
2440   (Body_File_Name => "*.ADA",
2441    Dot_Replacement => "__",
2442    Casing = Uppercase);
2443 pragma Source_File_Name
2444   (Subunit_File_Name => "*.SEP",
2445    Dot_Replacement => "__",
2446    Casing = Uppercase);
2447 @end smallexample
2448
2449 @node Generating Object Files
2450 @section Generating Object Files
2451
2452 @noindent
2453 An Ada program consists of a set of source files, and the first step in
2454 compiling the program is to generate the corresponding object files.
2455 These are generated by compiling a subset of these source files.
2456 The files you need to compile are the following:
2457
2458 @itemize @bullet
2459 @item
2460 If a package spec has no body, compile the package spec to produce the
2461 object file for the package.
2462
2463 @item
2464 If a package has both a spec and a body, compile the body to produce the
2465 object file for the package. The source file for the package spec need
2466 not be compiled in this case because there is only one object file, which
2467 contains the code for both the spec and body of the package.
2468
2469 @item
2470 For a subprogram, compile the subprogram body to produce the object file
2471 for the subprogram. The spec, if one is present, is as usual in a
2472 separate file, and need not be compiled.
2473
2474 @item
2475 @cindex Subunits
2476 In the case of subunits, only compile the parent unit. A single object
2477 file is generated for the entire subunit tree, which includes all the
2478 subunits.
2479
2480 @item
2481 Compile child units independently of their parent units
2482 (though, of course, the spec of all the ancestor unit must be present in order
2483 to compile a child unit).
2484
2485 @item
2486 @cindex Generics
2487 Compile generic units in the same manner as any other units. The object
2488 files in this case are small dummy files that contain at most the
2489 flag used for elaboration checking. This is because GNAT always handles generic
2490 instantiation by means of macro expansion. However, it is still necessary to
2491 compile generic units, for dependency checking and elaboration purposes.
2492 @end itemize
2493
2494 @noindent
2495 The preceding rules describe the set of files that must be compiled to
2496 generate the object files for a program. Each object file has the same
2497 name as the corresponding source file, except that the extension is
2498 @file{.o} as usual.
2499
2500 You may wish to compile other files for the purpose of checking their
2501 syntactic and semantic correctness. For example, in the case where a
2502 package has a separate spec and body, you would not normally compile the
2503 spec. However, it is convenient in practice to compile the spec to make
2504 sure it is error-free before compiling clients of this spec, because such
2505 compilations will fail if there is an error in the spec.
2506
2507 GNAT provides an option for compiling such files purely for the
2508 purposes of checking correctness; such compilations are not required as
2509 part of the process of building a program. To compile a file in this
2510 checking mode, use the @option{-gnatc} switch.
2511
2512 @node Source Dependencies
2513 @section Source Dependencies
2514
2515 @noindent
2516 A given object file clearly depends on the source file which is compiled
2517 to produce it. Here we are using @dfn{depends} in the sense of a typical
2518 @code{make} utility; in other words, an object file depends on a source
2519 file if changes to the source file require the object file to be
2520 recompiled.
2521 In addition to this basic dependency, a given object may depend on
2522 additional source files as follows:
2523
2524 @itemize @bullet
2525 @item
2526 If a file being compiled @code{with}'s a unit @var{X}, the object file
2527 depends on the file containing the spec of unit @var{X}. This includes
2528 files that are @code{with}'ed implicitly either because they are parents
2529 of @code{with}'ed child units or they are run-time units required by the
2530 language constructs used in a particular unit.
2531
2532 @item
2533 If a file being compiled instantiates a library level generic unit, the
2534 object file depends on both the spec and body files for this generic
2535 unit.
2536
2537 @item
2538 If a file being compiled instantiates a generic unit defined within a
2539 package, the object file depends on the body file for the package as
2540 well as the spec file.
2541
2542 @item
2543 @findex Inline
2544 @cindex @option{-gnatn} switch
2545 If a file being compiled contains a call to a subprogram for which
2546 pragma @code{Inline} applies and inlining is activated with the
2547 @option{-gnatn} switch, the object file depends on the file containing the
2548 body of this subprogram as well as on the file containing the spec. Note
2549 that for inlining to actually occur as a result of the use of this switch,
2550 it is necessary to compile in optimizing mode.
2551
2552 @cindex @option{-gnatN} switch
2553 The use of @option{-gnatN} activates a more extensive inlining optimization
2554 that is performed by the front end of the compiler. This inlining does
2555 not require that the code generation be optimized. Like @option{-gnatn},
2556 the use of this switch generates additional dependencies.
2557 Note that
2558 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2559 to specify both options.
2560
2561 @item
2562 If an object file O  depends on the proper body of a subunit through inlining
2563 or instantiation, it depends on the parent unit of the subunit. This means that
2564 any modification of the parent unit or one of its subunits affects the
2565 compilation of O.
2566
2567 @item
2568 The object file for a parent unit depends on all its subunit body files.
2569
2570 @item
2571 The previous two rules meant that for purposes of computing dependencies and
2572 recompilation, a body and all its subunits are treated as an indivisible whole.
2573
2574 @noindent
2575 These rules are applied transitively: if unit @code{A} @code{with}'s
2576 unit @code{B}, whose elaboration calls an inlined procedure in package
2577 @code{C}, the object file for unit @code{A} will depend on the body of
2578 @code{C}, in file @file{c.adb}.
2579
2580 The set of dependent files described by these rules includes all the
2581 files on which the unit is semantically dependent, as described in the
2582 Ada 95 Language Reference Manual. However, it is a superset of what the
2583 ARM describes, because it includes generic, inline, and subunit dependencies.
2584
2585 An object file must be recreated by recompiling the corresponding source
2586 file if any of the source files on which it depends are modified. For
2587 example, if the @code{make} utility is used to control compilation,
2588 the rule for an Ada object file must mention all the source files on
2589 which the object file depends, according to the above definition.
2590 The determination of the necessary
2591 recompilations is done automatically when one uses @code{gnatmake}.
2592 @end itemize
2593
2594 @node The Ada Library Information Files
2595 @section The Ada Library Information Files
2596 @cindex Ada Library Information files
2597 @cindex @file{ALI} files
2598
2599 @noindent
2600 Each compilation actually generates two output files. The first of these
2601 is the normal object file that has a @file{.o} extension. The second is a
2602 text file containing full dependency information. It has the same
2603 name as the source file, but an @file{.ali} extension.
2604 This file is known as the Ada Library Information (@file{ALI}) file.
2605 The following information is contained in the @file{ALI} file.
2606
2607 @itemize @bullet
2608 @item
2609 Version information (indicates which version of GNAT was used to compile
2610 the unit(s) in question)
2611
2612 @item
2613 Main program information (including priority and time slice settings,
2614 as well as the wide character encoding used during compilation).
2615
2616 @item
2617 List of arguments used in the @code{gcc} command for the compilation
2618
2619 @item
2620 Attributes of the unit, including configuration pragmas used, an indication
2621 of whether the compilation was successful, exception model used etc.
2622
2623 @item
2624 A list of relevant restrictions applying to the unit (used for consistency)
2625 checking.
2626
2627 @item
2628 Categorization information (e.g. use of pragma @code{Pure}).
2629
2630 @item
2631 Information on all @code{with}'ed units, including presence of
2632 @code{Elaborate} or @code{Elaborate_All} pragmas.
2633
2634 @item
2635 Information from any @code{Linker_Options} pragmas used in the unit
2636
2637 @item
2638 Information on the use of @code{Body_Version} or @code{Version}
2639 attributes in the unit.
2640
2641 @item
2642 Dependency information. This is a list of files, together with
2643 time stamp and checksum information. These are files on which
2644 the unit depends in the sense that recompilation is required
2645 if any of these units are modified.
2646
2647 @item
2648 Cross-reference data. Contains information on all entities referenced
2649 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2650 provide cross-reference information.
2651
2652 @end itemize
2653
2654 @noindent
2655 For a full detailed description of the format of the @file{ALI} file,
2656 see the source of the body of unit @code{Lib.Writ}, contained in file
2657 @file{lib-writ.adb} in the GNAT compiler sources.
2658
2659 @node Binding an Ada Program
2660 @section Binding an Ada Program
2661
2662 @noindent
2663 When using languages such as C and C++, once the source files have been
2664 compiled the only remaining step in building an executable program
2665 is linking the object modules together. This means that it is possible to
2666 link an inconsistent version of a program, in which two units have
2667 included different versions of the same header.
2668
2669 The rules of Ada do not permit such an inconsistent program to be built.
2670 For example, if two clients have different versions of the same package,
2671 it is illegal to build a program containing these two clients.
2672 These rules are enforced by the GNAT binder, which also determines an
2673 elaboration order consistent with the Ada rules.
2674
2675 The GNAT binder is run after all the object files for a program have
2676 been created. It is given the name of the main program unit, and from
2677 this it determines the set of units required by the program, by reading the
2678 corresponding ALI files. It generates error messages if the program is
2679 inconsistent or if no valid order of elaboration exists.
2680
2681 If no errors are detected, the binder produces a main program, in Ada by
2682 default, that contains calls to the elaboration procedures of those
2683 compilation unit that require them, followed by
2684 a call to the main program. This Ada program is compiled to generate the
2685 object file for the main program. The name of
2686 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2687 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2688 main program unit.
2689
2690 Finally, the linker is used to build the resulting executable program,
2691 using the object from the main program from the bind step as well as the
2692 object files for the Ada units of the program.
2693
2694 @node Mixed Language Programming
2695 @section Mixed Language Programming
2696 @cindex Mixed Language Programming
2697
2698 @noindent
2699 This section describes how to develop a mixed-language program,
2700 specifically one that comprises units in both Ada and C.
2701
2702 @menu
2703 * Interfacing to C::
2704 * Calling Conventions::
2705 @end menu
2706
2707 @node Interfacing to C
2708 @subsection Interfacing to C
2709 @noindent
2710 Interfacing Ada with a foreign language such as C involves using
2711 compiler directives to import and/or export entity definitions in each
2712 language---using @code{extern} statements in C, for instance, and the
2713 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.  For
2714 a full treatment of these topics, read Appendix B, section 1 of the Ada
2715 95 Language Reference Manual.
2716
2717 There are two ways to build a program using GNAT that contains some Ada
2718 sources and some foreign language sources, depending on whether or not
2719 the main subprogram is written in Ada.  Here is a source example with
2720 the main subprogram in Ada:
2721
2722 @smallexample
2723 /* file1.c */
2724 #include <stdio.h>
2725
2726 void print_num (int num)
2727 @{
2728   printf ("num is %d.\n", num);
2729   return;
2730 @}
2731
2732 /* file2.c */
2733
2734 /* num_from_Ada is declared in my_main.adb */
2735 extern int num_from_Ada;
2736
2737 int get_num (void)
2738 @{
2739   return num_from_Ada;
2740 @}
2741 @end smallexample
2742
2743 @smallexample @c ada
2744 --  my_main.adb
2745 procedure My_Main is
2746
2747    --  Declare then export an Integer entity called num_from_Ada
2748    My_Num : Integer := 10;
2749    pragma Export (C, My_Num, "num_from_Ada");
2750
2751    --  Declare an Ada function spec for Get_Num, then use
2752    --  C function get_num for the implementation.
2753    function Get_Num return Integer;
2754    pragma Import (C, Get_Num, "get_num");
2755
2756    --  Declare an Ada procedure spec for Print_Num, then use
2757    --  C function print_num for the implementation.
2758    procedure Print_Num (Num : Integer);
2759    pragma Import (C, Print_Num, "print_num");
2760
2761 begin
2762    Print_Num (Get_Num);
2763 end My_Main;
2764 @end smallexample
2765
2766 @enumerate
2767 @item
2768 To build this example, first compile the foreign language files to
2769 generate object files:
2770 @smallexample
2771 gcc -c file1.c
2772 gcc -c file2.c
2773 @end smallexample
2774
2775 @item
2776 Then, compile the Ada units to produce a set of object files and ALI
2777 files:
2778 @smallexample
2779 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2780 @end smallexample
2781
2782 @item
2783 Run the Ada binder on the Ada main program:
2784 @smallexample
2785 gnatbind my_main.ali
2786 @end smallexample
2787
2788 @item
2789 Link the Ada main program, the Ada objects and the other language
2790 objects:
2791 @smallexample
2792 gnatlink my_main.ali file1.o file2.o
2793 @end smallexample
2794 @end enumerate
2795
2796 The last three steps can be grouped in a single command:
2797 @smallexample
2798 gnatmake my_main.adb -largs file1.o file2.o
2799 @end smallexample
2800
2801 @cindex Binder output file
2802 @noindent
2803 If the main program is in a language other than Ada, then you may have
2804 more than one entry point into the Ada subsystem. You must use a special
2805 binder option to generate callable routines that initialize and
2806 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2807 Calls to the initialization and finalization routines must be inserted
2808 in the main program, or some other appropriate point in the code. The
2809 call to initialize the Ada units must occur before the first Ada
2810 subprogram is called, and the call to finalize the Ada units must occur
2811 after the last Ada subprogram returns. The binder will place the
2812 initialization and finalization subprograms into the
2813 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2814 sources.  To illustrate, we have the following example:
2815
2816 @smallexample
2817 /* main.c */
2818 extern void adainit (void);
2819 extern void adafinal (void);
2820 extern int add (int, int);
2821 extern int sub (int, int);
2822
2823 int main (int argc, char *argv[])
2824 @{
2825   int a = 21, b = 7;
2826
2827   adainit();
2828
2829   /* Should print "21 + 7 = 28" */
2830   printf ("%d + %d = %d\n", a, b, add (a, b));
2831   /* Should print "21 - 7 = 14" */
2832   printf ("%d - %d = %d\n", a, b, sub (a, b));
2833
2834   adafinal();
2835 @}
2836 @end smallexample
2837
2838 @smallexample @c ada
2839 --  unit1.ads
2840 package Unit1 is
2841    function Add (A, B : Integer) return Integer;
2842    pragma Export (C, Add, "add");
2843 end Unit1;
2844
2845 --  unit1.adb
2846 package body Unit1 is
2847    function Add (A, B : Integer) return Integer is
2848    begin
2849       return A + B;
2850    end Add;
2851 end Unit1;
2852
2853 --  unit2.ads
2854 package Unit2 is
2855    function Sub (A, B : Integer) return Integer;
2856    pragma Export (C, Sub, "sub");
2857 end Unit2;
2858
2859 --  unit2.adb
2860 package body Unit2 is
2861    function Sub (A, B : Integer) return Integer is
2862    begin
2863       return A - B;
2864    end Sub;
2865 end Unit2;
2866 @end smallexample
2867
2868 @enumerate
2869 @item
2870 The build procedure for this application is similar to the last
2871 example's.  First, compile the foreign language files to generate object
2872 files:
2873 @smallexample
2874 gcc -c main.c
2875 @end smallexample
2876
2877 @item
2878 Next, compile the Ada units to produce a set of object files and ALI
2879 files:
2880 @smallexample
2881 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2882 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2883 @end smallexample
2884
2885 @item
2886 Run the Ada binder on every generated ALI file.  Make sure to use the
2887 @option{-n} option to specify a foreign main program:
2888 @smallexample
2889 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2890 @end smallexample
2891
2892 @item
2893 Link the Ada main program, the Ada objects and the foreign language
2894 objects. You need only list the last ALI file here:
2895 @smallexample
2896 gnatlink unit2.ali main.o -o exec_file
2897 @end smallexample
2898
2899 This procedure yields a binary executable called @file{exec_file}.
2900 @end enumerate
2901
2902 @node Calling Conventions
2903 @subsection Calling Conventions
2904 @cindex Foreign Languages
2905 @cindex Calling Conventions
2906 GNAT follows standard calling sequence conventions and will thus interface
2907 to any other language that also follows these conventions. The following
2908 Convention identifiers are recognized by GNAT:
2909
2910 @table @code
2911 @cindex Interfacing to Ada
2912 @cindex Other Ada compilers
2913 @cindex Convention Ada
2914 @item Ada
2915 This indicates that the standard Ada calling sequence will be
2916 used and all Ada data items may be passed without any limitations in the
2917 case where GNAT is used to generate both the caller and callee. It is also
2918 possible to mix GNAT generated code and code generated by another Ada
2919 compiler. In this case, the data types should be restricted to simple
2920 cases, including primitive types. Whether complex data types can be passed
2921 depends on the situation. Probably it is safe to pass simple arrays, such
2922 as arrays of integers or floats. Records may or may not work, depending
2923 on whether both compilers lay them out identically. Complex structures
2924 involving variant records, access parameters, tasks, or protected types,
2925 are unlikely to be able to be passed.
2926
2927 Note that in the case of GNAT running
2928 on a platform that supports DEC Ada 83, a higher degree of compatibility
2929 can be guaranteed, and in particular records are layed out in an identical
2930 manner in the two compilers. Note also that if output from two different
2931 compilers is mixed, the program is responsible for dealing with elaboration
2932 issues. Probably the safest approach is to write the main program in the
2933 version of Ada other than GNAT, so that it takes care of its own elaboration
2934 requirements, and then call the GNAT-generated adainit procedure to ensure
2935 elaboration of the GNAT components. Consult the documentation of the other
2936 Ada compiler for further details on elaboration.
2937
2938 However, it is not possible to mix the tasking run time of GNAT and
2939 DEC Ada 83, All the tasking operations must either be entirely within
2940 GNAT compiled sections of the program, or entirely within DEC Ada 83
2941 compiled sections of the program.
2942
2943 @cindex Interfacing to Assembly
2944 @cindex Convention Assembler
2945 @item Assembler
2946 Specifies assembler as the convention. In practice this has the
2947 same effect as convention Ada (but is not equivalent in the sense of being
2948 considered the same convention).
2949
2950 @cindex Convention Asm
2951 @findex Asm
2952 @item Asm
2953 Equivalent to Assembler.
2954
2955 @cindex Interfacing to COBOL
2956 @cindex Convention COBOL
2957 @findex COBOL
2958 @item COBOL
2959 Data will be passed according to the conventions described
2960 in section B.4 of the Ada 95 Reference Manual.
2961
2962 @findex C
2963 @cindex Interfacing to C
2964 @cindex Convention C
2965 @item C
2966 Data will be passed according to the conventions described
2967 in section B.3 of the Ada 95 Reference Manual.
2968
2969 @findex C varargs function
2970 @cindex Intefacing to C varargs function
2971 @cindex varargs function intefacs
2972 @item C varargs function
2973 In C, @code{varargs} allows a function to take a variable number of
2974 arguments. There is no direct equivalent in this to Ada. One
2975 approach that can be used is to create a C wrapper for each
2976 different profile and then interface to this C wrapper. For
2977 example, to print an @code{int} value using @code{printf},
2978 create a C function @code{printfi} that takes two arguments, a
2979 pointer to a string and an int, and calls @code{printf}.
2980 Then in the Ada program, use pragma @code{Import} to
2981 interface to printfi.
2982
2983 It may work on some platforms to directly interface to
2984 a @code{varargs} function by providing a specific Ada profile
2985 for a a particular call. However, this does not work on
2986 all platforms, since there is no guarantee that the
2987 calling sequence for a two argument normal C function
2988 is the same as for calling a @code{varargs} C function with
2989 the same two arguments.
2990
2991 @cindex Convention Default
2992 @findex Default
2993 @item Default
2994 Equivalent to C.
2995
2996 @cindex Convention External
2997 @findex External
2998 @item External
2999 Equivalent to C.
3000
3001 @findex C++
3002 @cindex Interfacing to C++
3003 @cindex Convention C++
3004 @item CPP
3005 This stands for C++. For most purposes this is identical to C.
3006 See the separate description of the specialized GNAT pragmas relating to
3007 C++ interfacing for further details.
3008
3009 @findex Fortran
3010 @cindex Interfacing to Fortran
3011 @cindex Convention Fortran
3012 @item Fortran
3013 Data will be passed according to the conventions described
3014 in section B.5 of the Ada 95 Reference Manual.
3015
3016 @item Intrinsic
3017 This applies to an intrinsic operation, as defined in the Ada 95
3018 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
3019 this means that the body of the subprogram is provided by the compiler itself,
3020 usually by means of an efficient code sequence, and that the user does not
3021 supply an explicit body for it. In an application program, the pragma can
3022 only be applied to the following two sets of names, which the GNAT compiler
3023 recognizes.
3024
3025 @itemize @bullet
3026 @item
3027 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
3028 Arithmetic.  The corresponding subprogram declaration must have
3029 two formal parameters. The
3030 first one must be a signed integer type or a modular type with a binary
3031 modulus, and the second parameter must be of type Natural.
3032 The return type must be the same as the type of the first argument. The size
3033 of this type can only be 8, 16, 32, or 64.
3034 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3035 The corresponding operator declaration must have parameters and result type
3036 that have the same root numeric type (for example, all three are long_float
3037 types). This simplifies the definition of operations that use type checking
3038 to perform dimensional checks:
3039
3040 @smallexample @c ada
3041 type Distance is new Long_Float;
3042 type Time     is new Long_Float;
3043 type Velocity is new Long_Float;
3044 function "/" (D : Distance; T : Time)
3045   return Velocity;
3046 pragma Import (Intrinsic, "/");
3047 @end smallexample
3048
3049 @noindent
3050 This common idiom is often programmed with a generic definition and an
3051 explicit body. The pragma makes it simpler to introduce such declarations.
3052 It incurs no overhead in compilation time or code size, because it is
3053 implemented as a single machine instruction.
3054 @end itemize
3055 @noindent
3056
3057 @ifset unw
3058 @findex Stdcall
3059 @cindex Convention Stdcall
3060 @item Stdcall
3061 This is relevant only to NT/Win95 implementations of GNAT,
3062 and specifies that the Stdcall calling sequence will be used, as defined
3063 by the NT API.
3064
3065 @findex DLL
3066 @cindex Convention DLL
3067 @item DLL
3068 This is equivalent to Stdcall.
3069
3070 @findex Win32
3071 @cindex Convention Win32
3072 @item Win32
3073 This is equivalent to Stdcall.
3074 @end ifset
3075
3076 @findex Stubbed
3077 @cindex Convention Stubbed
3078 @item Stubbed
3079 This is a special convention that indicates that the compiler
3080 should provide a stub body that raises @code{Program_Error}.
3081 @end table
3082
3083 @noindent
3084 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3085 that can be used to parametrize conventions and allow additional synonyms
3086 to be specified. For example if you have legacy code in which the convention
3087 identifier Fortran77 was used for Fortran, you can use the configuration
3088 pragma:
3089
3090 @smallexample @c ada
3091 pragma Convention_Identifier (Fortran77, Fortran);
3092 @end smallexample
3093
3094 @noindent
3095 And from now on the identifier Fortran77 may be used as a convention
3096 identifier (for example in an @code{Import} pragma) with the same
3097 meaning as Fortran.
3098
3099 @node Building Mixed Ada & C++ Programs
3100 @section Building Mixed Ada & C++ Programs
3101
3102 @noindent
3103 A programmer inexperienced with mixed-language development may find that
3104 building an application containing both Ada and C++ code can be a
3105 challenge. As a matter of fact, interfacing with C++ has not been
3106 standardized in the Ada 95 Reference Manual due to the immaturity of --
3107 and lack of standards for -- C++ at the time. This section gives a few
3108 hints that should make this task easier. The first section addresses
3109 the differences regarding interfacing with C. The second section
3110 looks into the delicate problem of linking the complete application from
3111 its Ada and C++ parts. The last section gives some hints on how the GNAT
3112 run time can be adapted in order to allow inter-language dispatching
3113 with a new C++ compiler.
3114
3115 @menu
3116 * Interfacing to C++::
3117 * Linking a Mixed C++ & Ada Program::
3118 * A Simple Example::
3119 * Adapting the Run Time to a New C++ Compiler::
3120 @end menu
3121
3122 @node Interfacing to C++
3123 @subsection Interfacing to C++
3124
3125 @noindent
3126 GNAT supports interfacing with C++ compilers generating code that is
3127 compatible with the standard Application Binary Interface of the given
3128 platform.
3129
3130 @noindent
3131 Interfacing can be done at 3 levels: simple data, subprograms, and
3132 classes. In the first two cases, GNAT offers a specific @var{Convention
3133 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3134 the names of subprograms, and currently, GNAT does not provide any help
3135 to solve the demangling problem. This problem can be addressed in two
3136 ways:
3137 @itemize @bullet
3138 @item
3139 by modifying the C++ code in order to force a C convention using
3140 the @code{extern "C"} syntax.
3141
3142 @item
3143 by figuring out the mangled name and use it as the Link_Name argument of
3144 the pragma import.
3145 @end itemize
3146
3147 @noindent
3148 Interfacing at the class level can be achieved by using the GNAT specific
3149 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3150 Reference Manual for additional information.
3151
3152 @node Linking a Mixed C++ & Ada Program
3153 @subsection Linking a Mixed C++ & Ada Program
3154
3155 @noindent
3156 Usually the linker of the C++ development system must be used to link
3157 mixed applications because most C++ systems will resolve elaboration
3158 issues (such as calling constructors on global class instances)
3159 transparently during the link phase. GNAT has been adapted to ease the
3160 use of a foreign linker for the last phase. Three cases can be
3161 considered:
3162 @enumerate
3163
3164 @item
3165 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3166 The C++ linker can simply be called by using the C++ specific driver
3167 called @code{c++}. Note that this setup is not very common because it
3168 may involve recompiling the whole GCC tree from sources, which makes it
3169 harder to upgrade the compilation system for one language without
3170 destabilizing the other.
3171
3172 @smallexample
3173 $ c++ -c file1.C
3174 $ c++ -c file2.C
3175 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3176 @end smallexample
3177
3178 @item
3179 Using GNAT and G++ from two different GCC installations: If both
3180 compilers are on the PATH, the previous method may be used. It is
3181 important to note that environment variables such as C_INCLUDE_PATH,
3182 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3183 at the same time and may make one of the two compilers operate
3184 improperly if set during invocation of the wrong compiler.  It is also
3185 very important that the linker uses the proper @file{libgcc.a} GCC
3186 library -- that is, the one from the C++ compiler installation. The
3187 implicit link command as suggested in the gnatmake command from the
3188 former example can be replaced by an explicit link command with the
3189 full-verbosity option in order to verify which library is used:
3190 @smallexample
3191 $ gnatbind ada_unit
3192 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3193 @end smallexample
3194 If there is a problem due to interfering environment variables, it can
3195 be worked around by using an intermediate script. The following example
3196 shows the proper script to use when GNAT has not been installed at its
3197 default location and g++ has been installed at its default location:
3198
3199 @smallexample
3200 $ cat ./my_script
3201 #!/bin/sh
3202 unset BINUTILS_ROOT
3203 unset GCC_ROOT
3204 c++ $*
3205 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3206 @end smallexample
3207
3208 @item
3209 Using a non-GNU C++ compiler: The commands previously described can be
3210 used to insure that the C++ linker is used. Nonetheless, you need to add
3211 the path to libgcc explicitly, since some libraries needed by GNAT are
3212 located in this directory:
3213
3214 @smallexample
3215 $ cat ./my_script
3216 #!/bin/sh
3217 CC $* `gcc -print-libgcc-file-name`
3218 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3219 @end smallexample
3220
3221 Where CC is the name of the non-GNU C++ compiler.
3222
3223 @end enumerate
3224
3225 @node A Simple Example
3226 @subsection  A Simple Example
3227 @noindent
3228 The following example, provided as part of the GNAT examples, shows how
3229 to achieve procedural interfacing between Ada and C++ in both
3230 directions. The C++ class A has two methods. The first method is exported
3231 to Ada by the means of an extern C wrapper function. The second method
3232 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3233 a limited record with a layout comparable to the C++ class. The Ada
3234 subprogram, in turn, calls the C++ method. So, starting from the C++
3235 main program, the process passes back and forth between the two
3236 languages.
3237
3238 @noindent
3239 Here are the compilation commands:
3240 @smallexample
3241 $ gnatmake -c simple_cpp_interface
3242 $ c++ -c cpp_main.C
3243 $ c++ -c ex7.C
3244 $ gnatbind -n simple_cpp_interface
3245 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3246       -lstdc++ ex7.o cpp_main.o
3247 @end smallexample
3248
3249 @noindent
3250 Here are the corresponding sources:
3251 @smallexample
3252
3253 //cpp_main.C
3254
3255 #include "ex7.h"
3256
3257 extern "C" @{
3258   void adainit (void);
3259   void adafinal (void);
3260   void method1 (A *t);
3261 @}
3262
3263 void method1 (A *t)
3264 @{
3265   t->method1 ();
3266 @}
3267
3268 int main ()
3269 @{
3270   A obj;
3271   adainit ();
3272   obj.method2 (3030);
3273   adafinal ();
3274 @}
3275
3276 //ex7.h
3277
3278 class Origin @{
3279  public:
3280   int o_value;
3281 @};
3282 class A : public Origin @{
3283  public:
3284   void method1 (void);
3285   virtual void method2 (int v);
3286   A();
3287   int   a_value;
3288 @};
3289
3290 //ex7.C
3291
3292 #include "ex7.h"
3293 #include <stdio.h>
3294
3295 extern "C" @{ void ada_method2 (A *t, int v);@}
3296
3297 void A::method1 (void)
3298 @{
3299   a_value = 2020;
3300   printf ("in A::method1, a_value = %d \n",a_value);
3301
3302 @}
3303
3304 void A::method2 (int v)
3305 @{
3306    ada_method2 (this, v);
3307    printf ("in A::method2, a_value = %d \n",a_value);
3308
3309 @}
3310
3311 A::A(void)
3312 @{
3313    a_value = 1010;
3314   printf ("in A::A, a_value = %d \n",a_value);
3315 @}
3316
3317 -- Ada sources
3318 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3319
3320    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3321    @b{begin}
3322       Method1 (This);
3323       This.A_Value := V;
3324    @b{end} Ada_Method2;
3325
3326 @b{end} Simple_Cpp_Interface;
3327
3328 @b{package} Simple_Cpp_Interface @b{is}
3329    @b{type} A @b{is} @b{limited}
3330       @b{record}
3331          O_Value : Integer;
3332          A_Value : Integer;
3333       @b{end} @b{record};
3334    @b{pragma} Convention (C, A);
3335
3336    @b{procedure} Method1 (This : @b{in} @b{out} A);
3337    @b{pragma} Import (C, Method1);
3338
3339    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3340    @b{pragma} Export (C, Ada_Method2);
3341
3342 @b{end} Simple_Cpp_Interface;
3343 @end smallexample
3344
3345 @node Adapting the Run Time to a New C++ Compiler
3346 @subsection Adapting the Run Time to a New C++ Compiler
3347 @noindent
3348 GNAT offers the capability to derive Ada 95 tagged types directly from
3349 preexisting C++ classes and . See ``Interfacing with C++'' in the
3350 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3351 such a goal
3352 has been made user configurable through a GNAT library unit
3353 @code{Interfaces.CPP}. The default version of this file is adapted to
3354 the GNU C++ compiler. Internal knowledge of the virtual
3355 table layout used by the new C++ compiler is needed to configure
3356 properly this unit. The Interface of this unit is known by the compiler
3357 and cannot be changed except for the value of the constants defining the
3358 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3359 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3360 of this unit for more details.
3361
3362 @node Comparison between GNAT and C/C++ Compilation Models
3363 @section Comparison between GNAT and C/C++ Compilation Models
3364
3365 @noindent
3366 The GNAT model of compilation is close to the C and C++ models. You can
3367 think of Ada specs as corresponding to header files in C. As in C, you
3368 don't need to compile specs; they are compiled when they are used. The
3369 Ada @code{with} is similar in effect to the @code{#include} of a C
3370 header.
3371
3372 One notable difference is that, in Ada, you may compile specs separately
3373 to check them for semantic and syntactic accuracy. This is not always
3374 possible with C headers because they are fragments of programs that have
3375 less specific syntactic or semantic rules.
3376
3377 The other major difference is the requirement for running the binder,
3378 which performs two important functions. First, it checks for
3379 consistency. In C or C++, the only defense against assembling
3380 inconsistent programs lies outside the compiler, in a makefile, for
3381 example. The binder satisfies the Ada requirement that it be impossible
3382 to construct an inconsistent program when the compiler is used in normal
3383 mode.
3384
3385 @cindex Elaboration order control
3386 The other important function of the binder is to deal with elaboration
3387 issues. There are also elaboration issues in C++ that are handled
3388 automatically. This automatic handling has the advantage of being
3389 simpler to use, but the C++ programmer has no control over elaboration.
3390 Where @code{gnatbind} might complain there was no valid order of
3391 elaboration, a C++ compiler would simply construct a program that
3392 malfunctioned at run time.
3393
3394 @node Comparison between GNAT and Conventional Ada Library Models
3395 @section Comparison between GNAT and Conventional Ada Library Models
3396
3397 @noindent
3398 This section is intended to be useful to Ada programmers who have
3399 previously used an Ada compiler implementing the traditional Ada library
3400 model, as described in the Ada 95 Language Reference Manual. If you
3401 have not used such a system, please go on to the next section.
3402
3403 @cindex GNAT library
3404 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
3405 source files themselves acts as the library. Compiling Ada programs does
3406 not generate any centralized information, but rather an object file and
3407 a ALI file, which are of interest only to the binder and linker.
3408 In a traditional system, the compiler reads information not only from
3409 the source file being compiled, but also from the centralized library.
3410 This means that the effect of a compilation depends on what has been
3411 previously compiled. In particular:
3412
3413 @itemize @bullet
3414 @item
3415 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3416 to the version of the unit most recently compiled into the library.
3417
3418 @item
3419 Inlining is effective only if the necessary body has already been
3420 compiled into the library.
3421
3422 @item
3423 Compiling a unit may obsolete other units in the library.
3424 @end itemize
3425
3426 @noindent
3427 In GNAT, compiling one unit never affects the compilation of any other
3428 units because the compiler reads only source files. Only changes to source
3429 files can affect the results of a compilation. In particular:
3430
3431 @itemize @bullet
3432 @item
3433 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3434 to the source version of the unit that is currently accessible to the
3435 compiler.
3436
3437 @item
3438 @cindex Inlining
3439 Inlining requires the appropriate source files for the package or
3440 subprogram bodies to be available to the compiler. Inlining is always
3441 effective, independent of the order in which units are complied.
3442
3443 @item
3444 Compiling a unit never affects any other compilations. The editing of
3445 sources may cause previous compilations to be out of date if they
3446 depended on the source file being modified.
3447 @end itemize
3448
3449 @noindent
3450 The most important result of these differences is that order of compilation
3451 is never significant in GNAT. There is no situation in which one is
3452 required to do one compilation before another. What shows up as order of
3453 compilation requirements in the traditional Ada library becomes, in
3454 GNAT, simple source dependencies; in other words, there is only a set
3455 of rules saying what source files must be present when a file is
3456 compiled.
3457
3458 @ifset vms
3459 @node Placement of temporary files
3460 @section Placement of temporary files
3461 @cindex Temporary files (user control over placement)
3462
3463 @noindent
3464 GNAT creates temporary files in the directory designated by the environment
3465 variable @env{TMPDIR}.
3466 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3467 for detailed information on how environment variables are resolved.
3468 For most users the easiest way to make use of this feature is to simply
3469 define @env{TMPDIR} as a job level logical name).
3470 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3471 for compiler temporary files, then you can include something like the
3472 following command in your @file{LOGIN.COM} file:
3473
3474 @smallexample
3475 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3476 @end smallexample
3477
3478 @noindent
3479 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3480 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3481 designated by @env{TEMP}.
3482 If none of these environment variables are defined then GNAT uses the
3483 directory designated by the logical name @code{SYS$SCRATCH:}
3484 (by default the user's home directory). If all else fails
3485 GNAT uses the current directory for temporary files.
3486 @end ifset
3487
3488
3489 @c *************************
3490 @node Compiling Using gcc
3491 @chapter Compiling Using @code{gcc}
3492
3493 @noindent
3494 This chapter discusses how to compile Ada programs using the @code{gcc}
3495 command. It also describes the set of switches
3496 that can be used to control the behavior of the compiler.
3497 @menu
3498 * Compiling Programs::
3499 * Switches for gcc::
3500 * Search Paths and the Run-Time Library (RTL)::
3501 * Order of Compilation Issues::
3502 * Examples::
3503 @end menu
3504
3505 @node Compiling Programs
3506 @section Compiling Programs
3507
3508 @noindent
3509 The first step in creating an executable program is to compile the units
3510 of the program using the @code{gcc} command. You must compile the
3511 following files:
3512
3513 @itemize @bullet
3514 @item
3515 the body file (@file{.adb}) for a library level subprogram or generic
3516 subprogram
3517
3518 @item
3519 the spec file (@file{.ads}) for a library level package or generic
3520 package that has no body
3521
3522 @item
3523 the body file (@file{.adb}) for a library level package
3524 or generic package that has a body
3525
3526 @end itemize
3527
3528 @noindent
3529 You need @emph{not} compile the following files
3530
3531 @itemize @bullet
3532
3533 @item
3534 the spec of a library unit which has a body
3535
3536 @item
3537 subunits
3538 @end itemize
3539
3540 @noindent
3541 because they are compiled as part of compiling related units. GNAT
3542 package specs
3543 when the corresponding body is compiled, and subunits when the parent is
3544 compiled.
3545
3546 @cindex cannot generate code
3547 If you attempt to compile any of these files, you will get one of the
3548 following error messages (where fff is the name of the file you compiled):
3549
3550 @smallexample
3551 cannot generate code for file @var{fff} (package spec)
3552 to check package spec, use -gnatc
3553
3554 cannot generate code for file @var{fff} (missing subunits)
3555 to check parent unit, use -gnatc
3556
3557 cannot generate code for file @var{fff} (subprogram spec)
3558 to check subprogram spec, use -gnatc
3559
3560 cannot generate code for file @var{fff} (subunit)
3561 to check subunit, use -gnatc
3562 @end smallexample
3563
3564 @noindent
3565 As indicated by the above error messages, if you want to submit
3566 one of these files to the compiler to check for correct semantics
3567 without generating code, then use the @option{-gnatc} switch.
3568
3569 The basic command for compiling a file containing an Ada unit is
3570
3571 @smallexample
3572 $ gcc -c [@var{switches}] @file{file name}
3573 @end smallexample
3574
3575 @noindent
3576 where @var{file name} is the name of the Ada file (usually
3577 having an extension
3578 @file{.ads} for a spec or @file{.adb} for a body).
3579 @ifclear vms
3580 You specify the
3581 @option{-c} switch to tell @code{gcc} to compile, but not link, the file.
3582 @end ifclear
3583 The result of a successful compilation is an object file, which has the
3584 same name as the source file but an extension of @file{.o} and an Ada
3585 Library Information (ALI) file, which also has the same name as the
3586 source file, but with @file{.ali} as the extension. GNAT creates these
3587 two output files in the current directory, but you may specify a source
3588 file in any directory using an absolute or relative path specification
3589 containing the directory information.
3590
3591 @findex gnat1
3592 @code{gcc} is actually a driver program that looks at the extensions of
3593 the file arguments and loads the appropriate compiler. For example, the
3594 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3595 These programs are in directories known to the driver program (in some
3596 configurations via environment variables you set), but need not be in
3597 your path. The @code{gcc} driver also calls the assembler and any other
3598 utilities needed to complete the generation of the required object
3599 files.
3600
3601 It is possible to supply several file names on the same @code{gcc}
3602 command. This causes @code{gcc} to call the appropriate compiler for
3603 each file. For example, the following command lists three separate
3604 files to be compiled:
3605
3606 @smallexample
3607 $ gcc -c x.adb y.adb z.c
3608 @end smallexample
3609
3610 @noindent
3611 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3612 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3613 The compiler generates three object files @file{x.o}, @file{y.o} and
3614 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3615 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3616 @ifclear vms
3617 except for
3618 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3619 @end ifclear
3620
3621 @node Switches for gcc
3622 @section Switches for @code{gcc}
3623
3624 @noindent
3625 The @code{gcc} command accepts switches that control the
3626 compilation process. These switches are fully described in this section.
3627 First we briefly list all the switches, in alphabetical order, then we
3628 describe the switches in more detail in functionally grouped sections.
3629
3630 @menu
3631 * Output and Error Message Control::
3632 * Warning Message Control::
3633 * Debugging and Assertion Control::
3634 * Run-Time Checks::
3635 * Stack Overflow Checking::
3636 * Validity Checking::
3637 * Style Checking::
3638 * Using gcc for Syntax Checking::
3639 * Using gcc for Semantic Checking::
3640 * Compiling Ada 83 Programs::
3641 * Character Set Control::
3642 * File Naming Control::
3643 * Subprogram Inlining Control::
3644 * Auxiliary Output Control::
3645 * Debugging Control::
3646 * Exception Handling Control::
3647 * Units to Sources Mapping Files::
3648 * Integrated Preprocessing::
3649 * Code Generation Control::
3650 @ifset vms
3651 * Return Codes::
3652 @end ifset
3653 @end menu
3654
3655 @table @option
3656 @c !sort!
3657 @ifclear vms
3658 @cindex @option{-b} (@code{gcc})
3659 @item -b @var{target}
3660 Compile your program to run on @var{target}, which is the name of a
3661 system configuration. You must have a GNAT cross-compiler built if
3662 @var{target} is not the same as your host system.
3663
3664 @item -B@var{dir}
3665 @cindex @option{-B} (@code{gcc})
3666 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3667 from @var{dir} instead of the default location. Only use this switch
3668 when multiple versions of the GNAT compiler are available. See the
3669 @code{gcc} manual page for further details. You would normally use the
3670 @option{-b} or @option{-V} switch instead.
3671
3672 @item -c
3673 @cindex @option{-c} (@code{gcc})
3674 Compile. Always use this switch when compiling Ada programs.
3675
3676 Note: for some other languages when using @code{gcc}, notably in
3677 the case of C and C++, it is possible to use
3678 use @code{gcc} without a @option{-c} switch to
3679 compile and link in one step. In the case of GNAT, you
3680 cannot use this approach, because the binder must be run
3681 and @code{gcc} cannot be used to run the GNAT binder.
3682 @end ifclear
3683
3684 @item -fno-inline
3685 @cindex @option{-fno-inline} (@code{gcc})
3686 Suppresses all back-end inlining, even if other optimization or inlining
3687 switches are set.
3688 This includes suppression of inlining that results
3689 from the use of the pragma @code{Inline_Always}.
3690 See also @option{-gnatn} and @option{-gnatN}.
3691
3692 @item -fno-strict-aliasing
3693 @cindex @option{-fno-strict-aliasing} (@code{gcc})
3694 Causes the compiler to avoid assumptions regarding non-aliasing
3695 of objects of different types. See section
3696 @pxref{Optimization and Strict Aliasing} for details.
3697
3698 @item -fstack-check
3699 @cindex @option{-fstack-check} (@code{gcc})
3700 Activates stack checking.
3701 See @ref{Stack Overflow Checking} for details of the use of this option.
3702
3703 @item ^-g^/DEBUG^
3704 @cindex @option{^-g^/DEBUG^} (@code{gcc})
3705 Generate debugging information. This information is stored in the object
3706 file and copied from there to the final executable file by the linker,
3707 where it can be read by the debugger. You must use the
3708 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3709
3710 @item -gnat83
3711 @cindex @option{-gnat83} (@code{gcc})
3712 Enforce Ada 83 restrictions.
3713
3714 @item -gnata
3715 @cindex @option{-gnata} (@code{gcc})
3716 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3717 activated.
3718
3719 @item -gnatA
3720 @cindex @option{-gnatA} (@code{gcc})
3721 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3722 it will be ignored.
3723
3724 @item -gnatb
3725 @cindex @option{-gnatb} (@code{gcc})
3726 Generate brief messages to @file{stderr} even if verbose mode set.
3727
3728 @item -gnatc
3729 @cindex @option{-gnatc} (@code{gcc})
3730 Check syntax and semantics only (no code generation attempted).
3731
3732 @item -gnatd
3733 @cindex @option{-gnatd} (@code{gcc})
3734 Specify debug options for the compiler. The string of characters after
3735 the @option{-gnatd} specify the specific debug options. The possible
3736 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3737 compiler source file @file{debug.adb} for details of the implemented
3738 debug options. Certain debug options are relevant to applications
3739 programmers, and these are documented at appropriate points in this
3740 users guide.
3741
3742 @item -gnatD
3743 @cindex @option{-gnatD} (@code{gcc})
3744 Create expanded source files for source level debugging. This switch
3745 also suppress generation of cross-reference information
3746 (see @option{-gnatx}).
3747
3748 @item -gnatec=@var{path}
3749 @cindex @option{-gnatec} (@code{gcc})
3750 Specify a configuration pragma file
3751 @ifclear vms
3752 (the equal sign is optional)
3753 @end ifclear
3754 (see @ref{The Configuration Pragmas Files}).
3755
3756 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3757 @cindex @option{-gnateD} (@code{gcc})
3758 Defines a symbol, associated with value, for preprocessing.
3759 (see @ref{Integrated Preprocessing})
3760
3761 @item -gnatef
3762 @cindex @option{-gnatef} (@code{gcc})
3763 Display full source path name in brief error messages.
3764
3765 @item -gnatem=@var{path}
3766 @cindex @option{-gnatem} (@code{gcc})
3767 Specify a mapping file
3768 @ifclear vms
3769 (the equal sign is optional)
3770 @end ifclear
3771 (see @ref{Units to Sources Mapping Files}).
3772
3773 @item -gnatep=@var{file}
3774 @cindex @option{-gnatep} (@code{gcc})
3775 Specify a preprocessing data file
3776 @ifclear vms
3777 (the equal sign is optional)
3778 @end ifclear
3779 (see @ref{Integrated Preprocessing}).
3780
3781 @item -gnatE
3782 @cindex @option{-gnatE} (@code{gcc})
3783 Full dynamic elaboration checks.
3784
3785 @item -gnatf
3786 @cindex @option{-gnatf} (@code{gcc})
3787 Full errors. Multiple errors per line, all undefined references, do not
3788 attempt to suppress cascaded errors.
3789
3790 @item -gnatF
3791 @cindex @option{-gnatF} (@code{gcc})
3792 Externals names are folded to all uppercase.
3793
3794 @item -gnatg
3795 @cindex @option{-gnatg} (@code{gcc})
3796 Internal GNAT implementation mode. This should not be used for
3797 applications programs, it is intended only for use by the compiler
3798 and its run-time library. For documentation, see the GNAT sources.
3799 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3800 are generated on unreferenced entities, and all warnings are treated
3801 as errors.
3802
3803 @item -gnatG
3804 @cindex @option{-gnatG} (@code{gcc})
3805 List generated expanded code in source form.
3806
3807 @item ^-gnath^/HELP^
3808 @cindex @option{^-gnath^/HELP^} (@code{gcc})
3809 Output usage information. The output is written to @file{stdout}.
3810
3811 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3812 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
3813 Identifier character set
3814 @ifclear vms
3815 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3816 @end ifclear
3817 @ifset vms
3818 For details of the possible selections for @var{c},
3819 see @xref{Character Set Control}.
3820 @end ifset
3821
3822 @item -gnatk=@var{n}
3823 @cindex @option{-gnatk} (@code{gcc})
3824 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3825
3826 @item -gnatl
3827 @cindex @option{-gnatl} (@code{gcc})
3828 Output full source listing with embedded error messages.
3829
3830 @item -gnatL
3831 @cindex @option{-gnatL} (@code{gcc})
3832 Use the longjmp/setjmp method for exception handling
3833
3834 @item -gnatm=@var{n}
3835 @cindex @option{-gnatm} (@code{gcc})
3836 Limit number of detected error or warning messages to @var{n}
3837 where @var{n} is in the range 1..999_999. The default setting if
3838 no switch is given is 9999. Compilation is terminated if this
3839 limit is exceeded.
3840
3841 @item -gnatn
3842 @cindex @option{-gnatn} (@code{gcc})
3843 Activate inlining for subprograms for which
3844 pragma @code{inline} is specified. This inlining is performed
3845 by the GCC back-end.
3846
3847 @item -gnatN
3848 @cindex @option{-gnatN} (@code{gcc})
3849 Activate front end inlining for subprograms for which
3850 pragma @code{Inline} is specified. This inlining is performed
3851 by the front end and will be visible in the
3852 @option{-gnatG} output.
3853 In some cases, this has proved more effective than the back end
3854 inlining resulting from the use of
3855 @option{-gnatn}.
3856 Note that
3857 @option{-gnatN} automatically implies
3858 @option{-gnatn} so it is not necessary
3859 to specify both options. There are a few cases that the back-end inlining
3860 catches that cannot be dealt with in the front-end.
3861
3862 @item -gnato
3863 @cindex @option{-gnato} (@code{gcc})
3864 Enable numeric overflow checking (which is not normally enabled by
3865 default). Not that division by zero is a separate check that is not
3866 controlled by this switch (division by zero checking is on by default).
3867
3868 @item -gnatp
3869 @cindex @option{-gnatp} (@code{gcc})
3870 Suppress all checks.
3871
3872 @item -gnatP
3873 @cindex @option{-gnatP} (@code{gcc})
3874 Enable polling. This is required on some systems (notably Windows NT) to
3875 obtain asynchronous abort and asynchronous transfer of control capability.
3876 See the description of pragma Polling in the GNAT Reference Manual for
3877 full details.
3878
3879 @item -gnatq
3880 @cindex @option{-gnatq} (@code{gcc})
3881 Don't quit; try semantics, even if parse errors.
3882
3883 @item -gnatQ
3884 @cindex @option{-gnatQ} (@code{gcc})
3885 Don't quit; generate @file{ALI} and tree files even if illegalities.
3886
3887 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3888 @cindex @option{-gnatR} (@code{gcc})
3889 Output representation information for declared types and objects.
3890
3891 @item -gnats
3892 @cindex @option{-gnats} (@code{gcc})
3893 Syntax check only.
3894
3895 @item -gnatS
3896 @cindex @option{-gnatS} (@code{gcc})
3897 Print package Standard.
3898
3899 @item -gnatt
3900 @cindex @option{-gnatt} (@code{gcc})
3901 Generate tree output file.
3902
3903 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3904 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@code{gcc})
3905 All compiler tables start at @var{nnn} times usual starting size.
3906
3907 @item -gnatu
3908 @cindex @option{-gnatu} (@code{gcc})
3909 List units for this compilation.
3910
3911 @item -gnatU
3912 @cindex @option{-gnatU} (@code{gcc})
3913 Tag all error messages with the unique string ``error:''
3914
3915 @item -gnatv
3916 @cindex @option{-gnatv} (@code{gcc})
3917 Verbose mode. Full error output with source lines to @file{stdout}.
3918
3919 @item -gnatV
3920 @cindex @option{-gnatV} (@code{gcc})
3921 Control level of validity checking. See separate section describing
3922 this feature.
3923
3924 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
3925 @cindex @option{^-gnatw^/WARNINGS^} (@code{gcc})
3926 Warning mode where
3927 ^@var{xxx} is a string of option letters that^the list of options^ denotes
3928 the exact warnings that
3929 are enabled or disabled. (see @ref{Warning Message Control})
3930
3931 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3932 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
3933 Wide character encoding method
3934 @ifclear vms
3935 (@var{e}=n/h/u/s/e/8).
3936 @end ifclear
3937 @ifset vms
3938 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3939 @end ifset
3940
3941 @item -gnatx
3942 @cindex @option{-gnatx} (@code{gcc})
3943 Suppress generation of cross-reference information.
3944
3945 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3946 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@code{gcc})
3947 Enable built-in style checks. (see @ref{Style Checking})
3948
3949 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3950 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@code{gcc})
3951 Distribution stub generation and compilation
3952 @ifclear vms
3953 (@var{m}=r/c for receiver/caller stubs).
3954 @end ifclear
3955 @ifset vms
3956 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3957 to be generated and compiled).
3958 @end ifset
3959
3960 @item -gnatZ
3961 Use the zero cost method for exception handling
3962
3963 @item ^-I^/SEARCH=^@var{dir}
3964 @cindex @option{^-I^/SEARCH^} (@code{gcc})
3965 @cindex RTL
3966 Direct GNAT to search the @var{dir} directory for source files needed by
3967 the current compilation
3968 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3969
3970 @item ^-I-^/NOCURRENT_DIRECTORY^
3971 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gcc})
3972 @cindex RTL
3973 Except for the source file named in the command line, do not look for source
3974 files in the directory containing the source file named in the command line
3975 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3976
3977 @ifclear vms
3978 @item -mbig-switch
3979 @cindex @option{-mbig-switch} (@command{gcc})
3980 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
3981 This standard gcc switch causes the compiler to use larger offsets in its
3982 jump table representation for @code{case} statements.
3983 This may result in less efficient code, but is sometimes necessary
3984 (for example on HP-UX targets)
3985 @cindex HP-UX and @option{-mbig-switch} option
3986 in order to compile large and/or nested @code{case} statements.
3987
3988 @item -o @var{file}
3989 @cindex @option{-o} (@code{gcc})
3990 This switch is used in @code{gcc} to redirect the generated object file
3991 and its associated ALI file. Beware of this switch with GNAT, because it may
3992 cause the object file and ALI file to have different names which in turn
3993 may confuse the binder and the linker.
3994 @end ifclear
3995
3996 @item -nostdinc
3997 @cindex @option{-nostdinc} (@command{gcc})
3998 Inhibit the search of the default location for the GNAT Run Time
3999 Library (RTL) source files.
4000
4001 @item -nostdlib
4002 @cindex @option{-nostdlib} (@command{gcc})
4003 Inhibit the search of the default location for the GNAT Run Time
4004 Library (RTL) ALI files.
4005
4006 @ifclear vms
4007 @item -O[@var{n}]
4008 @cindex @option{-O} (@code{gcc})
4009 @var{n} controls the optimization level.
4010
4011 @table @asis
4012 @item n = 0
4013 No optimization, the default setting if no @option{-O} appears
4014
4015 @item n = 1
4016 Normal optimization, the default if you specify @option{-O} without
4017 an operand.
4018
4019 @item n = 2
4020 Extensive optimization
4021
4022 @item n = 3
4023 Extensive optimization with automatic inlining of subprograms not
4024 specified by pragma @code{Inline}. This applies only to
4025 inlining within a unit. For details on control of inlining
4026 see @xref{Subprogram Inlining Control}.
4027 @end table
4028 @end ifclear
4029
4030 @ifset vms
4031 @item  /NOOPTIMIZE
4032 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4033 Equivalent to @option{/OPTIMIZE=NONE}.
4034 This is the default behavior in the absence of an @option{/OPTMIZE}
4035 qualifier.
4036
4037 @item /OPTIMIZE[=(keyword[,...])]
4038 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4039 Selects the level of optimization for your program. The supported
4040 keywords are as follows:
4041 @table @code
4042 @item   ALL
4043 Perform most optimizations, including those that
4044 are expensive.
4045 This is the default if the @option{/OPTMIZE} qualifier is supplied
4046 without keyword options.
4047
4048 @item   NONE
4049 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4050
4051 @item SOME
4052 Perform some optimizations, but omit ones that are costly.
4053
4054 @item   DEVELOPMENT
4055 Same as @code{SOME}.
4056
4057 @item   INLINING
4058 Full optimization, and also attempt automatic inlining of small
4059 subprograms within a unit even when pragma @code{Inline}
4060 is not specified (@pxref{Inlining of Subprograms}).
4061
4062 @item   UNROLL_LOOPS
4063 Try to unroll loops. This keyword may be specified together with
4064 any keyword above other than @code{NONE}. Loop unrolling
4065 usually, but not always, improves the performance of programs.
4066 @end table
4067 @end ifset
4068
4069 @ifclear vms
4070 @item -pass-exit-codes
4071 @cindex @option{-pass-exit-codes} (@code{gcc})
4072 Catch exit codes from the compiler and use the most meaningful as
4073 exit status.
4074 @end ifclear
4075
4076 @item --RTS=@var{rts-path}
4077 @cindex @option{--RTS} (@code{gcc})
4078 Specifies the default location of the runtime library. Same meaning as the
4079 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
4080
4081 @item ^-S^/ASM^
4082 @cindex @option{^-S^/ASM^} (@code{gcc})
4083 ^Used in place of @option{-c} to^Used to^
4084 cause the assembler source file to be
4085 generated, using @file{^.s^.S^} as the extension,
4086 instead of the object file.
4087 This may be useful if you need to examine the generated assembly code.
4088
4089 @item ^-v^/VERBOSE^
4090 @cindex @option{^-v^/VERBOSE^} (@code{gcc})
4091 Show commands generated by the @code{gcc} driver. Normally used only for
4092 debugging purposes or if you need to be sure what version of the
4093 compiler you are executing.
4094
4095 @ifclear vms
4096 @item -V @var{ver}
4097 @cindex @option{-V} (@code{gcc})
4098 Execute @var{ver} version of the compiler. This is the @code{gcc}
4099 version, not the GNAT version.
4100 @end ifclear
4101
4102 @end table
4103
4104 @ifclear vms
4105 You may combine a sequence of GNAT switches into a single switch. For
4106 example, the combined switch
4107
4108 @cindex Combining GNAT switches
4109 @smallexample
4110 -gnatofi3
4111 @end smallexample
4112
4113 @noindent
4114 is equivalent to specifying the following sequence of switches:
4115
4116 @smallexample
4117 -gnato -gnatf -gnati3
4118 @end smallexample
4119 @end ifclear
4120
4121
4122 @c NEED TO CHECK THIS FOR VMS
4123
4124 @noindent
4125 The following restrictions apply to the combination of switches
4126 in this manner:
4127
4128 @itemize @bullet
4129 @item
4130 The switch @option{-gnatc} if combined with other switches must come
4131 first in the string.
4132
4133 @item
4134 The switch @option{-gnats} if combined with other switches must come
4135 first in the string.
4136
4137 @item
4138 The switches
4139 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4140 may not be combined with any other switches.
4141
4142 @ifclear vms
4143 @item
4144 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4145 switch), then all further characters in the switch are interpreted
4146 as style modifiers (see description of @option{-gnaty}).
4147
4148 @item
4149 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4150 switch), then all further characters in the switch are interpreted
4151 as debug flags (see description of @option{-gnatd}).
4152
4153 @item
4154 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4155 switch), then all further characters in the switch are interpreted
4156 as warning mode modifiers (see description of @option{-gnatw}).
4157
4158 @item
4159 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4160 switch), then all further characters in the switch are interpreted
4161 as validity checking options (see description of @option{-gnatV}).
4162 @end ifclear
4163 @end itemize
4164
4165
4166 @node Output and Error Message Control
4167 @subsection Output and Error Message Control
4168 @findex stderr
4169
4170 @noindent
4171 The standard default format for error messages is called ``brief format''.
4172 Brief format messages are written to @file{stderr} (the standard error
4173 file) and have the following form:
4174
4175 @smallexample
4176 e.adb:3:04: Incorrect spelling of keyword "function"
4177 e.adb:4:20: ";" should be "is"
4178 @end smallexample
4179
4180 @noindent
4181 The first integer after the file name is the line number in the file,
4182 and the second integer is the column number within the line.
4183 @code{glide} can parse the error messages
4184 and point to the referenced character.
4185 The following switches provide control over the error message
4186 format:
4187
4188 @table @option
4189 @c !sort!
4190 @item -gnatv
4191 @cindex @option{-gnatv} (@code{gcc})
4192 @findex stdout
4193 @ifclear vms
4194 The v stands for verbose.
4195 @end ifclear
4196 The effect of this setting is to write long-format error
4197 messages to @file{stdout} (the standard output file.
4198 The same program compiled with the
4199 @option{-gnatv} switch would generate:
4200
4201 @smallexample
4202 @cartouche
4203 3. funcion X (Q : Integer)
4204    |
4205 >>> Incorrect spelling of keyword "function"
4206 4. return Integer;
4207                  |
4208 >>> ";" should be "is"
4209 @end cartouche
4210 @end smallexample
4211
4212 @noindent
4213 The vertical bar indicates the location of the error, and the @samp{>>>}
4214 prefix can be used to search for error messages. When this switch is
4215 used the only source lines output are those with errors.
4216
4217 @item -gnatl
4218 @cindex @option{-gnatl} (@code{gcc})
4219 @ifclear vms
4220 The @code{l} stands for list.
4221 @end ifclear
4222 This switch causes a full listing of
4223 the file to be generated. The output might look as follows:
4224
4225 @smallexample
4226 @cartouche
4227  1. procedure E is
4228  2.    V : Integer;
4229  3.    funcion X (Q : Integer)
4230        |
4231     >>> Incorrect spelling of keyword "function"
4232  4.     return Integer;
4233                       |
4234     >>> ";" should be "is"
4235  5.    begin
4236  6.       return Q + Q;
4237  7.    end;
4238  8. begin
4239  9.    V := X + X;
4240 10.end E;
4241 @end cartouche
4242 @end smallexample
4243
4244 @noindent
4245 @findex stderr
4246 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4247 standard output is redirected, a brief summary is written to
4248 @file{stderr} (standard error) giving the number of error messages and
4249 warning messages generated.
4250
4251 @item -gnatU
4252 @cindex @option{-gnatU} (@code{gcc})
4253 This switch forces all error messages to be preceded by the unique
4254 string ``error:''. This means that error messages take a few more
4255 characters in space, but allows easy searching for and identification
4256 of error messages.
4257
4258 @item -gnatb
4259 @cindex @option{-gnatb} (@code{gcc})
4260 @ifclear vms
4261 The @code{b} stands for brief.
4262 @end ifclear
4263 This switch causes GNAT to generate the
4264 brief format error messages to @file{stderr} (the standard error
4265 file) as well as the verbose
4266 format message or full listing (which as usual is written to
4267 @file{stdout} (the standard output file).
4268
4269 @item -gnatm^^=^@var{n}
4270 @cindex @option{-gnatm} (@code{gcc})
4271 @ifclear vms
4272 The @code{m} stands for maximum.
4273 @end ifclear
4274 @var{n} is a decimal integer in the
4275 range of 1 to 999 and limits the number of error messages to be
4276 generated. For example, using @option{-gnatm2} might yield
4277
4278 @smallexample
4279 e.adb:3:04: Incorrect spelling of keyword "function"
4280 e.adb:5:35: missing ".."
4281 fatal error: maximum errors reached
4282 compilation abandoned
4283 @end smallexample
4284
4285 @item -gnatf
4286 @cindex @option{-gnatf} (@code{gcc})
4287 @cindex Error messages, suppressing
4288 @ifclear vms
4289 The @code{f} stands for full.
4290 @end ifclear
4291 Normally, the compiler suppresses error messages that are likely to be
4292 redundant. This switch causes all error
4293 messages to be generated. In particular, in the case of
4294 references to undefined variables. If a given variable is referenced
4295 several times, the normal format of messages is
4296 @smallexample
4297 e.adb:7:07: "V" is undefined (more references follow)
4298 @end smallexample
4299
4300 @noindent
4301 where the parenthetical comment warns that there are additional
4302 references to the variable @code{V}. Compiling the same program with the
4303 @option{-gnatf} switch yields
4304
4305 @smallexample
4306 e.adb:7:07: "V" is undefined
4307 e.adb:8:07: "V" is undefined
4308 e.adb:8:12: "V" is undefined
4309 e.adb:8:16: "V" is undefined
4310 e.adb:9:07: "V" is undefined
4311 e.adb:9:12: "V" is undefined
4312 @end smallexample
4313
4314 @noindent
4315 The @option{-gnatf} switch also generates additional information for
4316 some error messages.  Some examples are:
4317
4318 @itemize @bullet
4319 @item
4320 Full details on entities not available in high integrity mode
4321 @item
4322 Details on possibly non-portable unchecked conversion
4323 @item
4324 List possible interpretations for ambiguous calls
4325 @item
4326 Additional details on incorrect parameters
4327 @end itemize
4328
4329
4330 @item -gnatq
4331 @cindex @option{-gnatq} (@code{gcc})
4332 @ifclear vms
4333 The @code{q} stands for quit (really ``don't quit'').
4334 @end ifclear
4335 In normal operation mode, the compiler first parses the program and
4336 determines if there are any syntax errors. If there are, appropriate
4337 error messages are generated and compilation is immediately terminated.
4338 This switch tells
4339 GNAT to continue with semantic analysis even if syntax errors have been
4340 found. This may enable the detection of more errors in a single run. On
4341 the other hand, the semantic analyzer is more likely to encounter some
4342 internal fatal error when given a syntactically invalid tree.
4343
4344 @item -gnatQ
4345 @cindex @option{-gnatQ} (@code{gcc})
4346 In normal operation mode, the @file{ALI} file is not generated if any
4347 illegalities are detected in the program. The use of @option{-gnatQ} forces
4348 generation of the @file{ALI} file. This file is marked as being in
4349 error, so it cannot be used for binding purposes, but it does contain
4350 reasonably complete cross-reference information, and thus may be useful
4351 for use by tools (e.g. semantic browsing tools or integrated development
4352 environments) that are driven from the @file{ALI} file. This switch
4353 implies @option{-gnatq}, since the semantic phase must be run to get a
4354 meaningful ALI file.
4355
4356 In addition, if @option{-gnatt} is also specified, then the tree file is
4357 generated even if there are illegalities. It may be useful in this case
4358 to also specify @option{-gnatq} to ensure that full semantic processing
4359 occurs. The resulting tree file can be processed by ASIS, for the purpose
4360 of providing partial information about illegal units, but if the error
4361 causes the tree to be badly malformed, then ASIS may crash during the
4362 analysis.
4363
4364 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4365 being in error, @code{gnatmake} will attempt to recompile the source when it
4366 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4367
4368 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4369 since ALI files are never generated if @option{-gnats} is set.
4370
4371 @end table
4372
4373
4374 @node Warning Message Control
4375 @subsection Warning Message Control
4376 @cindex Warning messages
4377 @noindent
4378 In addition to error messages, which correspond to illegalities as defined
4379 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4380 situations.
4381
4382 First, the compiler considers some constructs suspicious and generates a
4383 warning message to alert you to a possible error. Second, if the
4384 compiler detects a situation that is sure to raise an exception at
4385 run time, it generates a warning message. The following shows an example
4386 of warning messages:
4387 @smallexample
4388 e.adb:4:24: warning: creation of object may raise Storage_Error
4389 e.adb:10:17: warning: static value out of range
4390 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4391 @end smallexample
4392
4393 @noindent
4394 GNAT considers a large number of situations as appropriate
4395 for the generation of warning messages. As always, warnings are not
4396 definite indications of errors. For example, if you do an out-of-range
4397 assignment with the deliberate intention of raising a
4398 @code{Constraint_Error} exception, then the warning that may be
4399 issued does not indicate an error. Some of the situations for which GNAT
4400 issues warnings (at least some of the time) are given in the following
4401 list. This list is not complete, and new warnings are often added to
4402 subsequent versions of GNAT. The list is intended to give a general idea
4403 of the kinds of warnings that are generated.
4404
4405 @itemize @bullet
4406 @item
4407 Possible infinitely recursive calls
4408
4409 @item
4410 Out-of-range values being assigned
4411
4412 @item
4413 Possible order of elaboration problems
4414
4415 @item
4416 Unreachable code
4417
4418 @item
4419 Fixed-point type declarations with a null range
4420
4421 @item
4422 Variables that are never assigned a value
4423
4424 @item
4425 Variables that are referenced before being initialized
4426
4427 @item
4428 Task entries with no corresponding @code{accept} statement
4429
4430 @item
4431 Duplicate accepts for the same task entry in a @code{select}
4432
4433 @item
4434 Objects that take too much storage
4435
4436 @item
4437 Unchecked conversion between types of differing sizes
4438
4439 @item
4440 Missing @code{return} statement along some execution path in a function
4441
4442 @item
4443 Incorrect (unrecognized) pragmas
4444
4445 @item
4446 Incorrect external names
4447
4448 @item
4449 Allocation from empty storage pool
4450
4451 @item
4452 Potentially blocking operation in protected type
4453
4454 @item
4455 Suspicious parenthesization of expressions
4456
4457 @item
4458 Mismatching bounds in an aggregate
4459
4460 @item
4461 Attempt to return local value by reference
4462
4463
4464 @item
4465 Premature instantiation of a generic body
4466
4467 @item
4468 Attempt to pack aliased components
4469
4470 @item
4471 Out of bounds array subscripts
4472
4473 @item
4474 Wrong length on string assignment
4475
4476 @item
4477 Violations of style rules if style checking is enabled
4478
4479 @item
4480 Unused @code{with} clauses
4481
4482 @item
4483 @code{Bit_Order} usage that does not have any effect
4484
4485 @item
4486 @code{Standard.Duration} used to resolve universal fixed expression
4487
4488 @item
4489 Dereference of possibly null value
4490
4491 @item
4492 Declaration that is likely to cause storage error
4493
4494 @item
4495 Internal GNAT unit @code{with}'ed by application unit
4496
4497 @item
4498 Values known to be out of range at compile time
4499
4500 @item
4501 Unreferenced labels and variables
4502
4503 @item
4504 Address overlays that could clobber memory
4505
4506 @item
4507 Unexpected initialization when address clause present
4508
4509 @item
4510 Bad alignment for address clause
4511
4512 @item
4513 Useless type conversions
4514
4515 @item
4516 Redundant assignment statements and other redundant constructs
4517
4518 @item
4519 Useless exception handlers
4520
4521 @item
4522 Accidental hiding of name by child unit
4523
4524
4525 @item
4526 Access before elaboration detected at compile time
4527
4528 @item
4529 A range in a @code{for} loop that is known to be null or might be null
4530
4531 @end itemize
4532
4533 @noindent
4534 The following switches are available to control the handling of
4535 warning messages:
4536
4537 @table @option
4538 @c !sort!
4539 @item -gnatwa
4540 @emph{Activate all optional errors.}
4541 @cindex @option{-gnatwa} (@code{gcc})
4542 This switch activates most optional warning messages, see remaining list
4543 in this section for details on optional warning messages that can be
4544 individually controlled.  The warnings that are not turned on by this
4545 switch are
4546 @option{-gnatwd} (implicit dereferencing),
4547 @option{-gnatwh} (hiding),
4548 and @option{-gnatwl} (elaboration warnings).
4549 All other optional warnings are turned on.
4550
4551 @item -gnatwA
4552 @emph{Suppress all optional errors.}
4553 @cindex @option{-gnatwA} (@code{gcc})
4554 This switch suppresses all optional warning messages, see remaining list
4555 in this section for details on optional warning messages that can be
4556 individually controlled.
4557
4558 @item -gnatwc
4559 @emph{Activate warnings on conditionals.}
4560 @cindex @option{-gnatwc} (@code{gcc})
4561 @cindex Conditionals, constant
4562 This switch activates warnings for conditional expressions used in
4563 tests that are known to be True or False at compile time. The default
4564 is that such warnings are not generated.
4565 Note that this warning does
4566 not get issued for the use of boolean variables or constants whose
4567 values are known at compile time, since this is a standard technique
4568 for conditional compilation in Ada, and this would generate too many
4569 ``false positive'' warnings.
4570 This warning can also be turned on using @option{-gnatwa}.
4571
4572 @item -gnatwC
4573 @emph{Suppress warnings on conditionals.}
4574 @cindex @option{-gnatwC} (@code{gcc})
4575 This switch suppresses warnings for conditional expressions used in
4576 tests that are known to be True or False at compile time.
4577
4578 @item -gnatwd
4579 @emph{Activate warnings on implicit dereferencing.}
4580 @cindex @option{-gnatwd} (@code{gcc})
4581 If this switch is set, then the use of a prefix of an access type
4582 in an indexed component, slice, or selected component without an
4583 explicit @code{.all} will generate a warning. With this warning
4584 enabled, access checks occur only at points where an explicit
4585 @code{.all} appears in the source code (assuming no warnings are
4586 generated as a result of this switch). The default is that such
4587 warnings are not generated.
4588 Note that @option{-gnatwa} does not affect the setting of
4589 this warning option.
4590
4591 @item -gnatwD
4592 @emph{Suppress warnings on implicit dereferencing.}
4593 @cindex @option{-gnatwD} (@code{gcc})
4594 @cindex Implicit dereferencing
4595 @cindex Dereferencing, implicit
4596 This switch suppresses warnings for implicit dereferences in
4597 indexed components, slices, and selected components.
4598
4599 @item -gnatwe
4600 @emph{Treat warnings as errors.}
4601 @cindex @option{-gnatwe} (@code{gcc})
4602 @cindex Warnings, treat as error
4603 This switch causes warning messages to be treated as errors.
4604 The warning string still appears, but the warning messages are counted
4605 as errors, and prevent the generation of an object file.
4606
4607 @item -gnatwf
4608 @emph{Activate warnings on unreferenced formals.}
4609 @cindex @option{-gnatwf} (@code{gcc})
4610 @cindex Formals, unreferenced
4611 This switch causes a warning to be generated if a formal parameter
4612 is not referenced in the body of the subprogram. This warning can
4613 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4614
4615 @item -gnatwF
4616 @emph{Suppress warnings on unreferenced formals.}
4617 @cindex @option{-gnatwF} (@code{gcc})
4618 This switch suppresses warnings for unreferenced formal
4619 parameters. Note that the
4620 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4621 effect of warning on unreferenced entities other than subprogram
4622 formals.
4623
4624 @item -gnatwg
4625 @emph{Activate warnings on unrecognized pragmas.}
4626 @cindex @option{-gnatwg} (@code{gcc})
4627 @cindex Pragmas, unrecognized
4628 This switch causes a warning to be generated if an unrecognized
4629 pragma is encountered. Apart from issuing this warning, the
4630 pragma is ignored and has no effect. This warning can
4631 also be turned on using @option{-gnatwa}. The default
4632 is that such warnings are issued (satisfying the Ada Reference
4633 Manual requirement that such warnings appear).
4634
4635 @item -gnatwG
4636 @emph{Suppress warnings on unrecognized pragmas.}
4637 @cindex @option{-gnatwG} (@code{gcc})
4638 This switch suppresses warnings for unrecognized pragmas.
4639
4640 @item -gnatwh
4641 @emph{Activate warnings on hiding.}
4642 @cindex @option{-gnatwh} (@code{gcc})
4643 @cindex Hiding of Declarations
4644 This switch activates warnings on hiding declarations.
4645 A declaration is considered hiding
4646 if it is for a non-overloadable entity, and it declares an entity with the
4647 same name as some other entity that is directly or use-visible. The default
4648 is that such warnings are not generated.
4649 Note that @option{-gnatwa} does not affect the setting of this warning option.
4650
4651 @item -gnatwH
4652 @emph{Suppress warnings on hiding.}
4653 @cindex @option{-gnatwH} (@code{gcc})
4654 This switch suppresses warnings on hiding declarations.
4655
4656 @item -gnatwi
4657 @emph{Activate warnings on implementation units.}
4658 @cindex @option{-gnatwi} (@code{gcc})
4659 This switch activates warnings for a @code{with} of an internal GNAT
4660 implementation unit, defined as any unit from the @code{Ada},
4661 @code{Interfaces}, @code{GNAT},
4662 ^^@code{DEC},^ or @code{System}
4663 hierarchies that is not
4664 documented in either the Ada Reference Manual or the GNAT
4665 Programmer's Reference Manual. Such units are intended only
4666 for internal implementation purposes and should not be @code{with}'ed
4667 by user programs. The default is that such warnings are generated
4668 This warning can also be turned on using @option{-gnatwa}.
4669
4670 @item -gnatwI
4671 @emph{Disable warnings on implementation units.}
4672 @cindex @option{-gnatwI} (@code{gcc})
4673 This switch disables warnings for a @code{with} of an internal GNAT
4674 implementation unit.
4675
4676 @item -gnatwj
4677 @emph{Activate warnings on obsolescent features (Annex J).}
4678 @cindex @option{-gnatwj} (@code{gcc})
4679 @cindex Features, obsolescent
4680 @cindex Obsolescent features
4681 If this warning option is activated, then warnings are generated for
4682 calls to subprograms marked with @code{pragma Obsolescent} and
4683 for use of features in Annex J of the Ada Reference Manual. In the
4684 case of Annex J, not all features are flagged. In particular use
4685 of the renamed packages (like @code{Text_IO}) and use of package
4686 @code{ASCII} are not flagged, since these are very common and
4687 would generate many annoying positive warnings. The default is that
4688 such warnings are not generated.
4689
4690 @item -gnatwJ
4691 @emph{Suppress warnings on obsolescent features (Annex J).}
4692 @cindex @option{-gnatwJ} (@code{gcc})
4693 This switch disables warnings on use of obsolescent features.
4694
4695 @item -gnatwk
4696 @emph{Activate warnings on variables that could be constants.}
4697 @cindex @option{-gnatwk} (@code{gcc})
4698 This switch activates warnings for variables that are initialized but
4699 never modified, and then could be declared constants.
4700
4701 @item -gnatwK
4702 @emph{Suppress warnings on variables that could be constants.}
4703 @cindex @option{-gnatwK} (@code{gcc})
4704 This switch disables warnings on variables that could be declared constants.
4705
4706 @item -gnatwl
4707 @emph{Activate warnings for missing elaboration pragmas.}
4708 @cindex @option{-gnatwl} (@code{gcc})
4709 @cindex Elaboration, warnings
4710 This switch activates warnings on missing
4711 @code{pragma Elaborate_All} statements.
4712 See the section in this guide on elaboration checking for details on
4713 when such pragma should be used. Warnings are also generated if you
4714 are using the static mode of elaboration, and a @code{pragma Elaborate}
4715 is encountered. The default is that such warnings
4716 are not generated.
4717 This warning is not automatically turned on by the use of @option{-gnatwa}.
4718
4719 @item -gnatwL
4720 @emph{Suppress warnings for missing elaboration pragmas.}
4721 @cindex @option{-gnatwL} (@code{gcc})
4722 This switch suppresses warnings on missing pragma Elaborate_All statements.
4723 See the section in this guide on elaboration checking for details on
4724 when such pragma should be used.
4725
4726 @item -gnatwm
4727 @emph{Activate warnings on modified but unreferenced variables.}
4728 @cindex @option{-gnatwm} (@code{gcc})
4729 This switch activates warnings for variables that are assigned (using
4730 an initialization value or with one or more assignment statements) but
4731 whose value is never read. The warning is suppressed for volatile
4732 variables and also for variables that are renamings of other variables
4733 or for which an address clause is given.
4734 This warning can also be turned on using @option{-gnatwa}.
4735
4736 @item -gnatwM
4737 @emph{Disable warnings on modified but unreferenced variables.}
4738 @cindex @option{-gnatwM} (@code{gcc})
4739 This switch disables warnings for variables that are assigned or
4740 initialized, but never read.
4741
4742 @item -gnatwn
4743 @emph{Set normal warnings mode.}
4744 @cindex @option{-gnatwn} (@code{gcc})
4745 This switch sets normal warning mode, in which enabled warnings are
4746 issued and treated as warnings rather than errors. This is the default
4747 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4748 an explicit @option{-gnatws} or
4749 @option{-gnatwe}. It also cancels the effect of the
4750 implicit @option{-gnatwe} that is activated by the
4751 use of @option{-gnatg}.
4752
4753 @item -gnatwo
4754 @emph{Activate warnings on address clause overlays.}
4755 @cindex @option{-gnatwo} (@code{gcc})
4756 @cindex Address Clauses, warnings
4757 This switch activates warnings for possibly unintended initialization
4758 effects of defining address clauses that cause one variable to overlap
4759 another. The default is that such warnings are generated.
4760 This warning can also be turned on using @option{-gnatwa}.
4761
4762 @item -gnatwO
4763 @emph{Suppress warnings on address clause overlays.}
4764 @cindex @option{-gnatwO} (@code{gcc})
4765 This switch suppresses warnings on possibly unintended initialization
4766 effects of defining address clauses that cause one variable to overlap
4767 another.
4768
4769 @item -gnatwp
4770 @emph{Activate warnings on ineffective pragma Inlines.}
4771 @cindex @option{-gnatwp} (@code{gcc})
4772 @cindex Inlining, warnings
4773 This switch activates warnings for failure of front end inlining
4774 (activated by @option{-gnatN}) to inline a particular call. There are
4775 many reasons for not being able to inline a call, including most
4776 commonly that the call is too complex to inline.
4777 This warning can also be turned on using @option{-gnatwa}.
4778
4779 @item -gnatwP
4780 @emph{Suppress warnings on ineffective pragma Inlines.}
4781 @cindex @option{-gnatwP} (@code{gcc})
4782 This switch suppresses warnings on ineffective pragma Inlines. If the
4783 inlining mechanism cannot inline a call, it will simply ignore the
4784 request silently.
4785
4786 @item -gnatwr
4787 @emph{Activate warnings on redundant constructs.}
4788 @cindex @option{-gnatwr} (@code{gcc})
4789 This switch activates warnings for redundant constructs. The following
4790 is the current list of constructs regarded as redundant:
4791 This warning can also be turned on using @option{-gnatwa}.
4792
4793 @itemize @bullet
4794 @item
4795 Assignment of an item to itself.
4796 @item
4797 Type conversion that converts an expression to its own type.
4798 @item
4799 Use of the attribute @code{Base} where @code{typ'Base} is the same
4800 as @code{typ}.
4801 @item
4802 Use of pragma @code{Pack} when all components are placed by a record
4803 representation clause.
4804 @item
4805 Exception handler containing only a reraise statement (raise with no
4806 operand) which has no effect.
4807 @item
4808 Use of the operator abs on an operand that is known at compile time
4809 to be non-negative
4810 @item
4811 Use of an unnecessary extra level of parentheses (C-style) around conditions
4812 in @code{if} statements, @code{while} statements and @code{exit} statements.
4813 @item
4814 Comparison of boolean expressions to an explicit True value.
4815 @end itemize
4816
4817 @item -gnatwR
4818 @emph{Suppress warnings on redundant constructs.}
4819 @cindex @option{-gnatwR} (@code{gcc})
4820 This switch suppresses warnings for redundant constructs.
4821
4822 @item -gnatws
4823 @emph{Suppress all warnings.}
4824 @cindex @option{-gnatws} (@code{gcc})
4825 This switch completely suppresses the
4826 output of all warning messages from the GNAT front end.
4827 Note that it does not suppress warnings from the @code{gcc} back end.
4828 To suppress these back end warnings as well, use the switch @option{-w}
4829 in addition to @option{-gnatws}.
4830
4831 @item -gnatwu
4832 @emph{Activate warnings on unused entities.}
4833 @cindex @option{-gnatwu} (@code{gcc})
4834 This switch activates warnings to be generated for entities that
4835 are declared but not referenced, and for units that are @code{with}'ed
4836 and not
4837 referenced. In the case of packages, a warning is also generated if
4838 no entities in the package are referenced. This means that if the package
4839 is referenced but the only references are in @code{use}
4840 clauses or @code{renames}
4841 declarations, a warning is still generated. A warning is also generated
4842 for a generic package that is @code{with}'ed but never instantiated.
4843 In the case where a package or subprogram body is compiled, and there
4844 is a @code{with} on the corresponding spec
4845 that is only referenced in the body,
4846 a warning is also generated, noting that the
4847 @code{with} can be moved to the body. The default is that
4848 such warnings are not generated.
4849 This switch also activates warnings on unreferenced formals
4850 (it is includes the effect of @option{-gnatwf}).
4851 This warning can also be turned on using @option{-gnatwa}.
4852
4853 @item -gnatwU
4854 @emph{Suppress warnings on unused entities.}
4855 @cindex @option{-gnatwU} (@code{gcc})
4856 This switch suppresses warnings for unused entities and packages.
4857 It also turns off warnings on unreferenced formals (and thus includes
4858 the effect of @option{-gnatwF}).
4859
4860 @item -gnatwv
4861 @emph{Activate warnings on unassigned variables.}
4862 @cindex @option{-gnatwv} (@code{gcc})
4863 @cindex Unassigned variable warnings
4864 This switch activates warnings for access to variables which
4865 may not be properly initialized. The default is that
4866 such warnings are generated.
4867
4868 @item -gnatwV
4869 @emph{Suppress warnings on unassigned variables.}
4870 @cindex @option{-gnatwV} (@code{gcc})
4871 This switch suppresses warnings for access to variables which
4872 may not be properly initialized.
4873
4874 @item -gnatwx
4875 @emph{Activate warnings on Export/Import pragmas.}
4876 @cindex @option{-gnatwx} (@code{gcc})
4877 @cindex Export/Import pragma warnings
4878 This switch activates warnings on Export/Import pragmas when
4879 the compiler detects a possible conflict between the Ada and
4880 foreign language calling sequences. For example, the use of
4881 default parameters in a convention C procedure is dubious
4882 because the C compiler cannot supply the proper default, so
4883 a warning is issued. The default is that such warnings are
4884 generated.
4885
4886 @item -gnatwX
4887 @emph{Suppress warnings on Export/Import pragmas.}
4888 @cindex @option{-gnatwX} (@code{gcc})
4889 This switch suppresses warnings on Export/Import pragmas.
4890 The sense of this is that you are telling the compiler that
4891 you know what you are doing in writing the pragma, and it
4892 should not complain at you.
4893
4894 @item -gnatwz
4895 @emph{Activate warnings on unchecked conversions.}
4896 @cindex @option{-gnatwz} (@code{gcc})
4897 @cindex Unchecked_Conversion warnings
4898 This switch activates warnings for unchecked conversions
4899 where the types are known at compile time to have different
4900 sizes. The default
4901 is that such warnings are generated.
4902
4903 @item -gnatwZ
4904 @emph{Suppress warnings on unchecked conversions.}
4905 @cindex @option{-gnatwZ} (@code{gcc})
4906 This switch suppresses warnings for unchecked conversions
4907 where the types are known at compile time to have different
4908 sizes.
4909
4910 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
4911 @cindex @option{-Wuninitialized}
4912 The warnings controlled by the @option{-gnatw} switch are generated by the
4913 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
4914 can provide additional warnings. One such useful warning is provided by
4915 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
4916 conjunction with tunrning on optimization mode. This causes the flow
4917 analysis circuits of the back end optimizer to output additional
4918 warnings about uninitialized variables.
4919
4920 @item ^-w^/NO_BACK_END_WARNINGS^
4921 @cindex @option{-w}
4922 This switch suppresses warnings from the @option{^gcc^GCC^} back end. It may
4923 be used in conjunction with @option{-gnatws} to ensure that all warnings
4924 are suppressed during the entire compilation process.
4925
4926 @end table
4927
4928 @noindent
4929 @ifclear vms
4930 A string of warning parameters can be used in the same parameter. For example:
4931
4932 @smallexample
4933 -gnatwaLe
4934 @end smallexample
4935
4936 @noindent
4937 will turn on all optional warnings except for elaboration pragma warnings,
4938 and also specify that warnings should be treated as errors.
4939 @end ifclear
4940 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
4941
4942 @table @option
4943 @c !sort!
4944 @item -gnatwC
4945 @item -gnatwD
4946 @item -gnatwF
4947 @item -gnatwg
4948 @item -gnatwH
4949 @item -gnatwi
4950 @item -gnatwJ
4951 @item -gnatwK
4952 @item -gnatwL
4953 @item -gnatwM
4954 @item -gnatwn
4955 @item -gnatwo
4956 @item -gnatwP
4957 @item -gnatwR
4958 @item -gnatwU
4959 @item -gnatwv
4960 @item -gnatwz
4961 @item -gnatwx
4962
4963 @end table
4964
4965
4966 @node Debugging and Assertion Control
4967 @subsection Debugging and Assertion Control
4968
4969 @table @option
4970 @item -gnata
4971 @cindex @option{-gnata} (@code{gcc})
4972 @findex Assert
4973 @findex Debug
4974 @cindex Assertions
4975
4976 @noindent
4977 The pragmas @code{Assert} and @code{Debug} normally have no effect and
4978 are ignored. This switch, where @samp{a} stands for assert, causes
4979 @code{Assert} and @code{Debug} pragmas to be activated.
4980
4981 The pragmas have the form:
4982
4983 @smallexample
4984 @cartouche
4985    @b{pragma} Assert (@var{Boolean-expression} [,
4986                       @var{static-string-expression}])
4987    @b{pragma} Debug (@var{procedure call})
4988 @end cartouche
4989 @end smallexample
4990
4991 @noindent
4992 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
4993 If the result is @code{True}, the pragma has no effect (other than
4994 possible side effects from evaluating the expression). If the result is
4995 @code{False}, the exception @code{Assert_Failure} declared in the package
4996 @code{System.Assertions} is
4997 raised (passing @var{static-string-expression}, if present, as the
4998 message associated with the exception). If no string expression is
4999 given the default is a string giving the file name and line number
5000 of the pragma.
5001
5002 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5003 @code{pragma Debug} may appear within a declaration sequence, allowing
5004 debugging procedures to be called between declarations.
5005
5006 @ifset vms
5007 @item /DEBUG[=debug-level]
5008 @itemx  /NODEBUG
5009 Specifies how much debugging information is to be included in
5010 the resulting object file where 'debug-level' is one of the following:
5011 @table @code
5012 @item   TRACEBACK
5013 Include both debugger symbol records and traceback
5014 the object file.
5015 This is the default setting.
5016 @item   ALL
5017 Include both debugger symbol records and traceback in
5018 object file.
5019 @item   NONE
5020 Excludes both debugger symbol records and traceback
5021 the object file. Same as /NODEBUG.
5022 @item   SYMBOLS
5023 Includes only debugger symbol records in the object
5024 file. Note that this doesn't include traceback information.
5025 @end table
5026 @end ifset
5027 @end table
5028
5029 @node Validity Checking
5030 @subsection Validity Checking
5031 @findex Validity Checking
5032
5033 @noindent
5034 The Ada 95 Reference Manual has specific requirements for checking
5035 for invalid values. In particular, RM 13.9.1 requires that the
5036 evaluation of invalid values (for example from unchecked conversions),
5037 not result in erroneous execution. In GNAT, the result of such an
5038 evaluation in normal default mode is to either use the value
5039 unmodified, or to raise Constraint_Error in those cases where use
5040 of the unmodified value would cause erroneous execution. The cases
5041 where unmodified values might lead to erroneous execution are case
5042 statements (where a wild jump might result from an invalid value),
5043 and subscripts on the left hand side (where memory corruption could
5044 occur as a result of an invalid value).
5045
5046 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5047 checking mode.
5048 @ifclear vms
5049 The @code{x} argument is a string of letters that
5050 indicate validity checks that are performed or not performed in addition
5051 to the default checks described above.
5052 @end ifclear
5053 @ifset vms
5054 The options allowed for this qualifier
5055 indicate validity checks that are performed or not performed in addition
5056 to the default checks described above.
5057 @end ifset
5058
5059
5060 @table @option
5061 @c !sort!
5062 @item -gnatVa
5063 @emph{All validity checks.}
5064 @cindex @option{-gnatVa} (@code{gcc})
5065 All validity checks are turned on.
5066 @ifclear vms
5067 That is, @option{-gnatVa} is
5068 equivalent to @option{gnatVcdfimorst}.
5069 @end ifclear
5070
5071 @item -gnatVc
5072 @emph{Validity checks for copies.}
5073 @cindex @option{-gnatVc} (@code{gcc})
5074 The right hand side of assignments, and the initializing values of
5075 object declarations are validity checked.
5076
5077 @item -gnatVd
5078 @emph{Default (RM) validity checks.}
5079 @cindex @option{-gnatVd} (@code{gcc})
5080 Some validity checks are done by default following normal Ada semantics
5081 (RM 13.9.1 (9-11)).
5082 A check is done in case statements that the expression is within the range
5083 of the subtype. If it is not, Constraint_Error is raised.
5084 For assignments to array components, a check is done that the expression used
5085 as index is within the range. If it is not, Constraint_Error is raised.
5086 Both these validity checks may be turned off using switch @option{-gnatVD}.
5087 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5088 switch @option{-gnatVd} will leave the checks turned on.
5089 Switch @option{-gnatVD} should be used only if you are sure that all such
5090 expressions have valid values. If you use this switch and invalid values
5091 are present, then the program is erroneous, and wild jumps or memory
5092 overwriting may occur.
5093
5094 @item -gnatVf
5095 @emph{Validity checks for floating-point values.}
5096 @cindex @option{-gnatVf} (@code{gcc})
5097 In the absence of this switch, validity checking occurs only for discrete
5098 values. If @option{-gnatVf} is specified, then validity checking also applies
5099 for floating-point values, and NaN's and infinities are considered invalid,
5100 as well as out of range values for constrained types. Note that this means
5101 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5102 in which floating-point values are checked depends on the setting of other
5103 options. For example,
5104 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5105 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5106 (the order does not matter) specifies that floating-point parameters of mode
5107 @code{in} should be validity checked.
5108
5109 @item -gnatVi
5110 @emph{Validity checks for @code{in} mode parameters}
5111 @cindex @option{-gnatVi} (@code{gcc})
5112 Arguments for parameters of mode @code{in} are validity checked in function
5113 and procedure calls at the point of call.
5114
5115 @item -gnatVm
5116 @emph{Validity checks for @code{in out} mode parameters.}
5117 @cindex @option{-gnatVm} (@code{gcc})
5118 Arguments for parameters of mode @code{in out} are validity checked in
5119 procedure calls at the point of call. The @code{'m'} here stands for
5120 modify, since this concerns parameters that can be modified by the call.
5121 Note that there is no specific option to test @code{out} parameters,
5122 but any reference within the subprogram will be tested in the usual
5123 manner, and if an invalid value is copied back, any reference to it
5124 will be subject to validity checking.
5125
5126 @item -gnatVn
5127 @emph{No validity checks.}
5128 @cindex @option{-gnatVn} (@code{gcc})
5129 This switch turns off all validity checking, including the default checking
5130 for case statements and left hand side subscripts. Note that the use of
5131 the switch @option{-gnatp} suppresses all run-time checks, including
5132 validity checks, and thus implies @option{-gnatVn}. When this switch
5133 is used, it cancels any other @option{-gnatV} previously issued.
5134
5135 @item -gnatVo
5136 @emph{Validity checks for operator and attribute operands.}
5137 @cindex @option{-gnatVo} (@code{gcc})
5138 Arguments for predefined operators and attributes are validity checked.
5139 This includes all operators in package @code{Standard},
5140 the shift operators defined as intrinsic in package @code{Interfaces}
5141 and operands for attributes such as @code{Pos}. Checks are also made
5142 on individual component values for composite comparisons.
5143
5144 @item -gnatVp
5145 @emph{Validity checks for parameters.}
5146 @cindex @option{-gnatVp} (@code{gcc})
5147 This controls the treatment of parameters within a subprogram (as opposed
5148 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5149 of parameters on a call. If either of these call options is used, then
5150 normally an assumption is made within a subprogram that the input arguments
5151 have been validity checking at the point of call, and do not need checking
5152 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5153 is not made, and parameters are not assumed to be valid, so their validity
5154 will be checked (or rechecked) within the subprogram.
5155
5156 @item -gnatVr
5157 @emph{Validity checks for function returns.}
5158 @cindex @option{-gnatVr} (@code{gcc})
5159 The expression in @code{return} statements in functions is validity
5160 checked.
5161
5162 @item -gnatVs
5163 @emph{Validity checks for subscripts.}
5164 @cindex @option{-gnatVs} (@code{gcc})
5165 All subscripts expressions are checked for validity, whether they appear
5166 on the right side or left side (in default mode only left side subscripts
5167 are validity checked).
5168
5169 @item -gnatVt
5170 @emph{Validity checks for tests.}
5171 @cindex @option{-gnatVt} (@code{gcc})
5172 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5173 statements are checked, as well as guard expressions in entry calls.
5174
5175 @end table
5176
5177 @noindent
5178 The @option{-gnatV} switch may be followed by
5179 ^a string of letters^a list of options^
5180 to turn on a series of validity checking options.
5181 For example,
5182 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5183 specifies that in addition to the default validity checking, copies and
5184 function return expressions are to be validity checked.
5185 In order to make it easier
5186 to specify the desired combination of effects,
5187 @ifclear vms
5188 the upper case letters @code{CDFIMORST} may
5189 be used to turn off the corresponding lower case option.
5190 @end ifclear
5191 @ifset vms
5192 the prefix @code{NO} on an option turns off the corresponding validity
5193 checking:
5194 @itemize @bullet
5195 @item @code{NOCOPIES}
5196 @item @code{NODEFAULT}
5197 @item @code{NOFLOATS}
5198 @item @code{NOIN_PARAMS}
5199 @item @code{NOMOD_PARAMS}
5200 @item @code{NOOPERANDS}
5201 @item @code{NORETURNS}
5202 @item @code{NOSUBSCRIPTS}
5203 @item @code{NOTESTS}
5204 @end itemize
5205 @end ifset
5206 Thus
5207 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5208 turns on all validity checking options except for
5209 checking of @code{@b{in out}} procedure arguments.
5210
5211 The specification of additional validity checking generates extra code (and
5212 in the case of @option{-gnatVa} the code expansion can be substantial.
5213 However, these additional checks can be very useful in detecting
5214 uninitialized variables, incorrect use of unchecked conversion, and other
5215 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5216 is useful in conjunction with the extra validity checking, since this
5217 ensures that wherever possible uninitialized variables have invalid values.
5218
5219 See also the pragma @code{Validity_Checks} which allows modification of
5220 the validity checking mode at the program source level, and also allows for
5221 temporary disabling of validity checks.
5222
5223
5224 @node Style Checking
5225 @subsection Style Checking
5226 @findex Style checking
5227
5228 @noindent
5229 The @option{-gnaty^x^(option,option,...)^} switch
5230 @cindex @option{-gnaty} (@code{gcc})
5231 causes the compiler to
5232 enforce specified style rules. A limited set of style rules has been used
5233 in writing the GNAT sources themselves. This switch allows user programs
5234 to activate all or some of these checks. If the source program fails a
5235 specified style check, an appropriate warning message is given, preceded by
5236 the character sequence ``(style)''.
5237 @ifset vms
5238 @code{(option,option,...)} is a sequence of keywords
5239 @end ifset
5240 @ifclear vms
5241 The string @var{x} is a sequence of letters or digits
5242 @end ifclear
5243 indicating the particular style
5244 checks to be performed. The following checks are defined:
5245
5246 @table @option
5247 @c !sort!
5248 @item 1-9
5249 @emph{Specify indentation level.}
5250 If a digit from 1-9 appears
5251 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5252 then proper indentation is checked, with the digit indicating the
5253 indentation level required.
5254 The general style of required indentation is as specified by
5255 the examples in the Ada Reference Manual. Full line comments must be
5256 aligned with the @code{--} starting on a column that is a multiple of
5257 the alignment level.
5258
5259 @item ^a^ATTRIBUTE^
5260 @emph{Check attribute casing.}
5261 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5262 then attribute names, including the case of keywords such as @code{digits}
5263 used as attributes names, must be written in mixed case, that is, the
5264 initial letter and any letter following an underscore must be uppercase.
5265 All other letters must be lowercase.
5266
5267 @item ^b^BLANKS^
5268 @emph{Blanks not allowed at statement end.}
5269 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5270 trailing blanks are not allowed at the end of statements. The purpose of this
5271 rule, together with h (no horizontal tabs), is to enforce a canonical format
5272 for the use of blanks to separate source tokens.
5273
5274 @item ^c^COMMENTS^
5275 @emph{Check comments.}
5276 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5277 then comments must meet the following set of rules:
5278
5279 @itemize @bullet
5280
5281 @item
5282 The ``@code{--}'' that starts the column must either start in column one,
5283 or else at least one blank must precede this sequence.
5284
5285 @item
5286 Comments that follow other tokens on a line must have at least one blank
5287 following the ``@code{--}'' at the start of the comment.
5288
5289 @item
5290 Full line comments must have two blanks following the ``@code{--}'' that
5291 starts the comment, with the following exceptions.
5292
5293 @item
5294 A line consisting only of the ``@code{--}'' characters, possibly preceded
5295 by blanks is permitted.
5296
5297 @item
5298 A comment starting with ``@code{--x}'' where @code{x} is a special character
5299 is permitted.
5300 This allows proper processing of the output generated by specialized tools
5301 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5302 annotation
5303 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5304 special character is defined as being in one of the ASCII ranges
5305 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5306 Note that this usage is not permitted
5307 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5308
5309 @item
5310 A line consisting entirely of minus signs, possibly preceded by blanks, is
5311 permitted. This allows the construction of box comments where lines of minus
5312 signs are used to form the top and bottom of the box.
5313
5314 @item
5315 If a comment starts and ends with ``@code{--}'' is permitted as long as at
5316 least one blank follows the initial ``@code{--}''. Together with the preceding
5317 rule, this allows the construction of box comments, as shown in the following
5318 example:
5319 @smallexample
5320 ---------------------------
5321 -- This is a box comment --
5322 -- with two text lines.  --
5323 ---------------------------
5324 @end smallexample
5325 @end itemize
5326
5327 @item ^e^END^
5328 @emph{Check end/exit labels.}
5329 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5330 optional labels on @code{end} statements ending subprograms and on
5331 @code{exit} statements exiting named loops, are required to be present.
5332
5333 @item ^f^VTABS^
5334 @emph{No form feeds or vertical tabs.}
5335 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5336 neither form feeds nor vertical tab characters are not permitted
5337 in the source text.
5338
5339 @item ^h^HTABS^
5340 @emph{No horizontal tabs.}
5341 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5342 horizontal tab characters are not permitted in the source text.
5343 Together with the b (no blanks at end of line) check, this
5344 enforces a canonical form for the use of blanks to separate
5345 source tokens.
5346
5347 @item ^i^IF_THEN^
5348 @emph{Check if-then layout.}
5349 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5350 then the keyword @code{then} must appear either on the same
5351 line as corresponding @code{if}, or on a line on its own, lined
5352 up under the @code{if} with at least one non-blank line in between
5353 containing all or part of the condition to be tested.
5354
5355 @item ^k^KEYWORD^
5356 @emph{Check keyword casing.}
5357 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5358 all keywords must be in lower case (with the exception of keywords
5359 such as @code{digits} used as attribute names to which this check
5360 does not apply).
5361
5362 @item ^l^LAYOUT^
5363 @emph{Check layout.}
5364 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5365 layout of statement and declaration constructs must follow the
5366 recommendations in the Ada Reference Manual, as indicated by the
5367 form of the syntax rules. For example an @code{else} keyword must
5368 be lined up with the corresponding @code{if} keyword.
5369
5370 There are two respects in which the style rule enforced by this check
5371 option are more liberal than those in the Ada Reference Manual. First
5372 in the case of record declarations, it is permissible to put the
5373 @code{record} keyword on the same line as the @code{type} keyword, and
5374 then the @code{end} in @code{end record} must line up under @code{type}.
5375 For example, either of the following two layouts is acceptable:
5376
5377 @smallexample @c ada
5378 @cartouche
5379 type q is record
5380    a : integer;
5381    b : integer;
5382 end record;
5383
5384 type q is
5385    record
5386       a : integer;
5387       b : integer;
5388    end record;
5389 @end cartouche
5390 @end smallexample
5391
5392 @noindent
5393 Second, in the case of a block statement, a permitted alternative
5394 is to put the block label on the same line as the @code{declare} or
5395 @code{begin} keyword, and then line the @code{end} keyword up under
5396 the block label. For example both the following are permitted:
5397
5398 @smallexample @c ada
5399 @cartouche
5400 Block : declare
5401    A : Integer := 3;
5402 begin
5403    Proc (A, A);
5404 end Block;
5405
5406 Block :
5407    declare
5408       A : Integer := 3;
5409    begin
5410       Proc (A, A);
5411    end Block;
5412 @end cartouche
5413 @end smallexample
5414
5415 @noindent
5416 The same alternative format is allowed for loops. For example, both of
5417 the following are permitted:
5418
5419 @smallexample @c ada
5420 @cartouche
5421 Clear : while J < 10 loop
5422    A (J) := 0;
5423 end loop Clear;
5424
5425 Clear :
5426    while J < 10 loop
5427       A (J) := 0;
5428    end loop Clear;
5429 @end cartouche
5430 @end smallexample
5431
5432 @item ^m^LINE_LENGTH^
5433 @emph{Check maximum line length.}
5434 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5435 then the length of source lines must not exceed 79 characters, including
5436 any trailing blanks. The value of 79 allows convenient display on an
5437 80 character wide device or window, allowing for possible special
5438 treatment of 80 character lines. Note that this count is of raw
5439 characters in the source text. This means that a tab character counts
5440 as one character in this count and a wide character sequence counts as
5441 several characters (however many are needed in the encoding).
5442
5443 @item ^Mnnn^MAX_LENGTH=nnn^
5444 @emph{Set maximum line length.}
5445 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5446 the string after @option{-gnaty} then the length of lines must not exceed the
5447 given value.
5448
5449 @item ^n^STANDARD_CASING^
5450 @emph{Check casing of entities in Standard.}
5451 If the ^letter n^word STANDARD_CASING^ appears in the string
5452 after @option{-gnaty} then any identifier from Standard must be cased
5453 to match the presentation in the Ada Reference Manual (for example,
5454 @code{Integer} and @code{ASCII.NUL}).
5455
5456 @item ^o^ORDERED_SUBPROGRAMS^
5457 @emph{Check order of subprogram bodies.}
5458 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5459 after @option{-gnaty} then all subprogram bodies in a given scope
5460 (e.g. a package body) must be in alphabetical order. The ordering
5461 rule uses normal Ada rules for comparing strings, ignoring casing
5462 of letters, except that if there is a trailing numeric suffix, then
5463 the value of this suffix is used in the ordering (e.g. Junk2 comes
5464 before Junk10).
5465
5466 @item ^p^PRAGMA^
5467 @emph{Check pragma casing.}
5468 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5469 pragma names must be written in mixed case, that is, the
5470 initial letter and any letter following an underscore must be uppercase.
5471 All other letters must be lowercase.
5472
5473 @item ^r^REFERENCES^
5474 @emph{Check references.}
5475 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5476 then all identifier references must be cased in the same way as the
5477 corresponding declaration. No specific casing style is imposed on
5478 identifiers. The only requirement is for consistency of references
5479 with declarations.
5480
5481 @item ^s^SPECS^
5482 @emph{Check separate specs.}
5483 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5484 separate declarations (``specs'') are required for subprograms (a
5485 body is not allowed to serve as its own declaration). The only
5486 exception is that parameterless library level procedures are
5487 not required to have a separate declaration. This exception covers
5488 the most frequent form of main program procedures.
5489
5490 @item ^t^TOKEN^
5491 @emph{Check token spacing.}
5492 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5493 the following token spacing rules are enforced:
5494
5495 @itemize @bullet
5496
5497 @item
5498 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5499
5500 @item
5501 The token @code{=>} must be surrounded by spaces.
5502
5503 @item
5504 The token @code{<>} must be preceded by a space or a left parenthesis.
5505
5506 @item
5507 Binary operators other than @code{**} must be surrounded by spaces.
5508 There is no restriction on the layout of the @code{**} binary operator.
5509
5510 @item
5511 Colon must be surrounded by spaces.
5512
5513 @item
5514 Colon-equal (assignment, initialization) must be surrounded by spaces.
5515
5516 @item
5517 Comma must be the first non-blank character on the line, or be
5518 immediately preceded by a non-blank character, and must be followed
5519 by a space.
5520
5521 @item
5522 If the token preceding a left parenthesis ends with a letter or digit, then
5523 a space must separate the two tokens.
5524
5525 @item
5526 A right parenthesis must either be the first non-blank character on
5527 a line, or it must be preceded by a non-blank character.
5528
5529 @item
5530 A semicolon must not be preceded by a space, and must not be followed by
5531 a non-blank character.
5532
5533 @item
5534 A unary plus or minus may not be followed by a space.
5535
5536 @item
5537 A vertical bar must be surrounded by spaces.
5538 @end itemize
5539
5540 @noindent
5541 In the above rules, appearing in column one is always permitted, that is,
5542 counts as meeting either a requirement for a required preceding space,
5543 or as meeting a requirement for no preceding space.
5544
5545 Appearing at the end of a line is also always permitted, that is, counts
5546 as meeting either a requirement for a following space, or as meeting
5547 a requirement for no following space.
5548
5549 @end table
5550
5551 @noindent
5552 If any of these style rules is violated, a message is generated giving
5553 details on the violation. The initial characters of such messages are
5554 always ``@code{(style)}''. Note that these messages are treated as warning
5555 messages, so they normally do not prevent the generation of an object
5556 file. The @option{-gnatwe} switch can be used to treat warning messages,
5557 including style messages, as fatal errors.
5558
5559 The switch
5560 @ifclear vms
5561 @option{-gnaty} on its own (that is not
5562 followed by any letters or digits),
5563 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
5564 options enabled with the exception of -gnatyo,
5565 @end ifclear
5566 @ifset vms
5567 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5568 the exception of ORDERED_SUBPROGRAMS,
5569 @end ifset
5570 with an indentation level of 3. This is the standard
5571 checking option that is used for the GNAT sources.
5572
5573 The switch
5574 @ifclear vms
5575 @option{-gnatyN}
5576 @end ifclear
5577 @ifset vms
5578 /STYLE_CHECKS=NONE
5579 @end ifset
5580 clears any previously set style checks.
5581
5582 @node Run-Time Checks
5583 @subsection Run-Time Checks
5584 @cindex Division by zero
5585 @cindex Access before elaboration
5586 @cindex Checks, division by zero
5587 @cindex Checks, access before elaboration
5588
5589 @noindent
5590 If you compile with the default options, GNAT will insert many run-time
5591 checks into the compiled code, including code that performs range
5592 checking against constraints, but not arithmetic overflow checking for
5593 integer operations (including division by zero) or checks for access
5594 before elaboration on subprogram calls. All other run-time checks, as
5595 required by the Ada 95 Reference Manual, are generated by default.
5596 The following @code{gcc} switches refine this default behavior:
5597
5598 @table @option
5599 @c !sort!
5600 @item -gnatp
5601 @cindex @option{-gnatp} (@code{gcc})
5602 @cindex Suppressing checks
5603 @cindex Checks, suppressing
5604 @findex Suppress
5605 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5606 had been present in the source. Validity checks are also suppressed (in
5607 other words @option{-gnatp} also implies @option{-gnatVn}.
5608 Use this switch to improve the performance
5609 of the code at the expense of safety in the presence of invalid data or
5610 program bugs.
5611
5612 @item -gnato
5613 @cindex @option{-gnato} (@code{gcc})
5614 @cindex Overflow checks
5615 @cindex Check, overflow
5616 Enables overflow checking for integer operations.
5617 This causes GNAT to generate slower and larger executable
5618 programs by adding code to check for overflow (resulting in raising
5619 @code{Constraint_Error} as required by standard Ada
5620 semantics). These overflow checks correspond to situations in which
5621 the true value of the result of an operation may be outside the base
5622 range of the result type. The following example shows the distinction:
5623
5624 @smallexample @c ada
5625 X1 : Integer := Integer'Last;
5626 X2 : Integer range 1 .. 5 := 5;
5627 X3 : Integer := Integer'Last;
5628 X4 : Integer range 1 .. 5 := 5;
5629 F  : Float := 2.0E+20;
5630 ...
5631 X1 := X1 + 1;
5632 X2 := X2 + 1;
5633 X3 := Integer (F);
5634 X4 := Integer (F);
5635 @end smallexample
5636
5637 @noindent
5638 Here the first addition results in a value that is outside the base range
5639 of Integer, and hence requires an overflow check for detection of the
5640 constraint error. Thus the first assignment to @code{X1} raises a
5641 @code{Constraint_Error} exception only if @option{-gnato} is set.
5642
5643 The second increment operation results in a violation
5644 of the explicit range constraint, and such range checks are always
5645 performed (unless specifically suppressed with a pragma @code{suppress}
5646 or the use of @option{-gnatp}).
5647
5648 The two conversions of @code{F} both result in values that are outside
5649 the base range of type @code{Integer} and thus will raise
5650 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5651 The fact that the result of the second conversion is assigned to
5652 variable @code{X4} with a restricted range is irrelevant, since the problem
5653 is in the conversion, not the assignment.
5654
5655 Basically the rule is that in the default mode (@option{-gnato} not
5656 used), the generated code assures that all integer variables stay
5657 within their declared ranges, or within the base range if there is
5658 no declared range. This prevents any serious problems like indexes
5659 out of range for array operations.
5660
5661 What is not checked in default mode is an overflow that results in
5662 an in-range, but incorrect value. In the above example, the assignments
5663 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5664 range of the target variable, but the result is wrong in the sense that
5665 it is too large to be represented correctly. Typically the assignment
5666 to @code{X1} will result in wrap around to the largest negative number.
5667 The conversions of @code{F} will result in some @code{Integer} value
5668 and if that integer value is out of the @code{X4} range then the
5669 subsequent assignment would generate an exception.
5670
5671 @findex Machine_Overflows
5672 Note that the @option{-gnato} switch does not affect the code generated
5673 for any floating-point operations; it applies only to integer
5674 semantics).
5675 For floating-point, GNAT has the @code{Machine_Overflows}
5676 attribute set to @code{False} and the normal mode of operation is to
5677 generate IEEE NaN and infinite values on overflow or invalid operations
5678 (such as dividing 0.0 by 0.0).
5679
5680 The reason that we distinguish overflow checking from other kinds of
5681 range constraint checking is that a failure of an overflow check can
5682 generate an incorrect value, but cannot cause erroneous behavior. This
5683 is unlike the situation with a constraint check on an array subscript,
5684 where failure to perform the check can result in random memory description,
5685 or the range check on a case statement, where failure to perform the check
5686 can cause a wild jump.
5687
5688 Note again that @option{-gnato} is off by default, so overflow checking is
5689 not performed in default mode. This means that out of the box, with the
5690 default settings, GNAT does not do all the checks expected from the
5691 language description in the Ada Reference Manual. If you want all constraint
5692 checks to be performed, as described in this Manual, then you must
5693 explicitly use the -gnato switch either on the @code{gnatmake} or
5694 @code{gcc} command.
5695
5696 @item -gnatE
5697 @cindex @option{-gnatE} (@code{gcc})
5698 @cindex Elaboration checks
5699 @cindex Check, elaboration
5700 Enables dynamic checks for access-before-elaboration
5701 on subprogram calls and generic instantiations.
5702 For full details of the effect and use of this switch,
5703 @xref{Compiling Using gcc}.
5704 @end table
5705
5706 @findex Unsuppress
5707 @noindent
5708 The setting of these switches only controls the default setting of the
5709 checks. You may modify them using either @code{Suppress} (to remove
5710 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5711 the program source.
5712
5713 @node Stack Overflow Checking
5714 @subsection Stack Overflow Checking
5715 @cindex Stack Overflow Checking
5716 @cindex -fstack-check
5717
5718 @noindent
5719 For most operating systems, @code{gcc} does not perform stack overflow
5720 checking by default. This means that if the main environment task or
5721 some other task exceeds the available stack space, then unpredictable
5722 behavior will occur.
5723
5724 To activate stack checking, compile all units with the gcc option
5725 @option{-fstack-check}. For example:
5726
5727 @smallexample
5728 gcc -c -fstack-check package1.adb
5729 @end smallexample
5730
5731 @noindent
5732 Units compiled with this option will generate extra instructions to check
5733 that any use of the stack (for procedure calls or for declaring local
5734 variables in declare blocks) do not exceed the available stack space.
5735 If the space is exceeded, then a @code{Storage_Error} exception is raised.
5736
5737 For declared tasks, the stack size is always controlled by the size
5738 given in an applicable @code{Storage_Size} pragma (or is set to
5739 the default size if no pragma is used.
5740
5741 For the environment task, the stack size depends on
5742 system defaults and is unknown to the compiler. The stack
5743 may even dynamically grow on some systems, precluding the
5744 normal Ada semantics for stack overflow. In the worst case,
5745 unbounded stack usage, causes unbounded stack expansion
5746 resulting in the system running out of virtual memory.
5747
5748 The stack checking may still work correctly if a fixed
5749 size stack is allocated, but this cannot be guaranteed.
5750 To ensure that a clean exception is signalled for stack
5751 overflow, set the environment variable
5752 @code{GNAT_STACK_LIMIT} to indicate the maximum
5753 stack area that can be used, as in:
5754 @cindex GNAT_STACK_LIMIT
5755
5756 @smallexample
5757 SET GNAT_STACK_LIMIT 1600
5758 @end smallexample
5759
5760 @noindent
5761 The limit is given in kilobytes, so the above declaration would
5762 set the stack limit of the environment task to 1.6 megabytes.
5763 Note that the only purpose of this usage is to limit the amount
5764 of stack used by the environment task. If it is necessary to
5765 increase the amount of stack for the environment task, then this
5766 is an operating systems issue, and must be addressed with the
5767 appropriate operating systems commands.
5768
5769
5770 @node Using gcc for Syntax Checking
5771 @subsection Using @code{gcc} for Syntax Checking
5772 @table @option
5773 @item -gnats
5774 @cindex @option{-gnats} (@code{gcc})
5775 @ifclear vms
5776
5777 @noindent
5778 The @code{s} stands for ``syntax''.
5779 @end ifclear
5780
5781 Run GNAT in syntax checking only mode. For
5782 example, the command
5783
5784 @smallexample
5785 $ gcc -c -gnats x.adb
5786 @end smallexample
5787
5788 @noindent
5789 compiles file @file{x.adb} in syntax-check-only mode. You can check a
5790 series of files in a single command
5791 @ifclear vms
5792 , and can use wild cards to specify such a group of files.
5793 Note that you must specify the @option{-c} (compile
5794 only) flag in addition to the @option{-gnats} flag.
5795 @end ifclear
5796 .
5797 You may use other switches in conjunction with @option{-gnats}. In
5798 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5799 format of any generated error messages.
5800
5801 When the source file is empty or contains only empty lines and/or comments,
5802 the output is a warning:
5803
5804 @smallexample
5805 $ gcc -c -gnats -x ada toto.txt
5806 toto.txt:1:01: warning: empty file, contains no compilation units
5807 $
5808 @end smallexample
5809
5810 Otherwise, the output is simply the error messages, if any. No object file or
5811 ALI file is generated by a syntax-only compilation. Also, no units other
5812 than the one specified are accessed. For example, if a unit @code{X}
5813 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5814 check only mode does not access the source file containing unit
5815 @code{Y}.
5816
5817 @cindex Multiple units, syntax checking
5818 Normally, GNAT allows only a single unit in a source file. However, this
5819 restriction does not apply in syntax-check-only mode, and it is possible
5820 to check a file containing multiple compilation units concatenated
5821 together. This is primarily used by the @code{gnatchop} utility
5822 (@pxref{Renaming Files Using gnatchop}).
5823 @end table
5824
5825
5826 @node Using gcc for Semantic Checking
5827 @subsection Using @code{gcc} for Semantic Checking
5828 @table @option
5829 @item -gnatc
5830 @cindex @option{-gnatc} (@code{gcc})
5831
5832 @ifclear vms
5833 @noindent
5834 The @code{c} stands for ``check''.
5835 @end ifclear
5836 Causes the compiler to operate in semantic check mode,
5837 with full checking for all illegalities specified in the
5838 Ada 95 Reference Manual, but without generation of any object code
5839 (no object file is generated).
5840
5841 Because dependent files must be accessed, you must follow the GNAT
5842 semantic restrictions on file structuring to operate in this mode:
5843
5844 @itemize @bullet
5845 @item
5846 The needed source files must be accessible
5847 (@pxref{Search Paths and the Run-Time Library (RTL)}).
5848
5849 @item
5850 Each file must contain only one compilation unit.
5851
5852 @item
5853 The file name and unit name must match (@pxref{File Naming Rules}).
5854 @end itemize
5855
5856 The output consists of error messages as appropriate. No object file is
5857 generated. An @file{ALI} file is generated for use in the context of
5858 cross-reference tools, but this file is marked as not being suitable
5859 for binding (since no object file is generated).
5860 The checking corresponds exactly to the notion of
5861 legality in the Ada 95 Reference Manual.
5862
5863 Any unit can be compiled in semantics-checking-only mode, including
5864 units that would not normally be compiled (subunits,
5865 and specifications where a separate body is present).
5866 @end table
5867
5868 @node Compiling Ada 83 Programs
5869 @subsection Compiling Ada 83 Programs
5870 @table @option
5871 @cindex Ada 83 compatibility
5872 @item -gnat83
5873 @cindex @option{-gnat83} (@code{gcc})
5874 @cindex ACVC, Ada 83 tests
5875
5876 @noindent
5877 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
5878 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
5879 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
5880 where this can be done easily.
5881 It is not possible to guarantee this switch does a perfect
5882 job; for example, some subtle tests, such as are
5883 found in earlier ACVC tests (and that have been removed from the ACATS suite
5884 for Ada 95), might not compile correctly.
5885 Nevertheless, this switch may be useful in some circumstances, for example
5886 where, due to contractual reasons, legacy code needs to be maintained
5887 using only Ada 83 features.
5888
5889 With few exceptions (most notably the need to use @code{<>} on
5890 @cindex Generic formal parameters
5891 unconstrained generic formal parameters, the use of the new Ada 95
5892 reserved words, and the use of packages
5893 with optional bodies), it is not necessary to use the
5894 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
5895 exceptions, Ada 95 is upwardly compatible with Ada 83. This
5896 means that a correct Ada 83 program is usually also a correct Ada 95
5897 program.
5898 For further information, please refer to @ref{Compatibility and Porting Guide}.
5899
5900 @end table
5901
5902 @node Character Set Control
5903 @subsection Character Set Control
5904 @table @option
5905 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
5906 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
5907
5908 @noindent
5909 Normally GNAT recognizes the Latin-1 character set in source program
5910 identifiers, as described in the Ada 95 Reference Manual.
5911 This switch causes
5912 GNAT to recognize alternate character sets in identifiers. @var{c} is a
5913 single character ^^or word^ indicating the character set, as follows:
5914
5915 @table @code
5916 @item 1
5917 ISO 8859-1 (Latin-1) identifiers
5918
5919 @item 2
5920 ISO 8859-2 (Latin-2) letters allowed in identifiers
5921
5922 @item 3
5923 ISO 8859-3 (Latin-3) letters allowed in identifiers
5924
5925 @item 4
5926 ISO 8859-4 (Latin-4) letters allowed in identifiers
5927
5928 @item 5
5929 ISO 8859-5 (Cyrillic) letters allowed in identifiers
5930
5931 @item 9
5932 ISO 8859-15 (Latin-9) letters allowed in identifiers
5933
5934 @item ^p^PC^
5935 IBM PC letters (code page 437) allowed in identifiers
5936
5937 @item ^8^PC850^
5938 IBM PC letters (code page 850) allowed in identifiers
5939
5940 @item ^f^FULL_UPPER^
5941 Full upper-half codes allowed in identifiers
5942
5943 @item ^n^NO_UPPER^
5944 No upper-half codes allowed in identifiers
5945
5946 @item ^w^WIDE^
5947 Wide-character codes (that is, codes greater than 255)
5948 allowed in identifiers
5949 @end table
5950
5951 @xref{Foreign Language Representation}, for full details on the
5952 implementation of these character sets.
5953
5954 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
5955 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
5956 Specify the method of encoding for wide characters.
5957 @var{e} is one of the following:
5958
5959 @table @code
5960
5961 @item ^h^HEX^
5962 Hex encoding (brackets coding also recognized)
5963
5964 @item ^u^UPPER^
5965 Upper half encoding (brackets encoding also recognized)
5966
5967 @item ^s^SHIFT_JIS^
5968 Shift/JIS encoding (brackets encoding also recognized)
5969
5970 @item ^e^EUC^
5971 EUC encoding (brackets encoding also recognized)
5972
5973 @item ^8^UTF8^
5974 UTF-8 encoding (brackets encoding also recognized)
5975
5976 @item ^b^BRACKETS^
5977 Brackets encoding only (default value)
5978 @end table
5979 For full details on the these encoding
5980 methods see @xref{Wide Character Encodings}.
5981 Note that brackets coding is always accepted, even if one of the other
5982 options is specified, so for example @option{-gnatW8} specifies that both
5983 brackets and @code{UTF-8} encodings will be recognized. The units that are
5984 with'ed directly or indirectly will be scanned using the specified
5985 representation scheme, and so if one of the non-brackets scheme is
5986 used, it must be used consistently throughout the program. However,
5987 since brackets encoding is always recognized, it may be conveniently
5988 used in standard libraries, allowing these libraries to be used with
5989 any of the available coding schemes.
5990 scheme. If no @option{-gnatW?} parameter is present, then the default
5991 representation is Brackets encoding only.
5992
5993 Note that the wide character representation that is specified (explicitly
5994 or by default) for the main program also acts as the default encoding used
5995 for Wide_Text_IO files if not specifically overridden by a WCEM form
5996 parameter.
5997
5998 @end table
5999 @node File Naming Control
6000 @subsection File Naming Control
6001
6002 @table @option
6003 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6004 @cindex @option{-gnatk} (@code{gcc})
6005 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6006 1-999, indicates the maximum allowable length of a file name (not
6007 including the @file{.ads} or @file{.adb} extension). The default is not
6008 to enable file name krunching.
6009
6010 For the source file naming rules, @xref{File Naming Rules}.
6011 @end table
6012
6013
6014 @node Subprogram Inlining Control
6015 @subsection Subprogram Inlining Control
6016
6017 @table @option
6018 @c !sort!
6019 @item -gnatn
6020 @cindex @option{-gnatn} (@code{gcc})
6021 @ifclear vms
6022 The @code{n} here is intended to suggest the first syllable of the
6023 word ``inline''.
6024 @end ifclear
6025 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6026 inlining to actually occur, optimization must be enabled. To enable
6027 inlining of subprograms specified by pragma @code{Inline},
6028 you must also specify this switch.
6029 In the absence of this switch, GNAT does not attempt
6030 inlining and does not need to access the bodies of
6031 subprograms for which @code{pragma Inline} is specified if they are not
6032 in the current unit.
6033
6034 If you specify this switch the compiler will access these bodies,
6035 creating an extra source dependency for the resulting object file, and
6036 where possible, the call will be inlined.
6037 For further details on when inlining is possible
6038 see @xref{Inlining of Subprograms}.
6039
6040 @item -gnatN
6041 @cindex @option{-gnatN} (@code{gcc})
6042 The front end inlining activated by this switch is generally more extensive,
6043 and quite often more effective than the standard @option{-gnatn} inlining mode.
6044 It will also generate additional dependencies.
6045 Note that
6046 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6047 to specify both options.
6048 @end table
6049
6050 @node Auxiliary Output Control
6051 @subsection Auxiliary Output Control
6052
6053 @table @option
6054 @item -gnatt
6055 @cindex @option{-gnatt} (@code{gcc})
6056 @cindex Writing internal trees
6057 @cindex Internal trees, writing to file
6058 Causes GNAT to write the internal tree for a unit to a file (with the
6059 extension @file{.adt}.
6060 This not normally required, but is used by separate analysis tools.
6061 Typically
6062 these tools do the necessary compilations automatically, so you should
6063 not have to specify this switch in normal operation.
6064
6065 @item -gnatu
6066 @cindex @option{-gnatu} (@code{gcc})
6067 Print a list of units required by this compilation on @file{stdout}.
6068 The listing includes all units on which the unit being compiled depends
6069 either directly or indirectly.
6070
6071 @ifclear vms
6072 @item -pass-exit-codes
6073 @cindex @option{-pass-exit-codes} (@code{gcc})
6074 If this switch is not used, the exit code returned by @code{gcc} when
6075 compiling multiple files indicates whether all source files have
6076 been successfully used to generate object files or not.
6077
6078 When @option{-pass-exit-codes} is used, @code{gcc} exits with an extended
6079 exit status and allows an integrated development environment to better
6080 react to a compilation failure. Those exit status are:
6081
6082 @table @asis
6083 @item 5
6084 There was an error in at least one source file.
6085 @item 3
6086 At least one source file did not generate an object file.
6087 @item 2
6088 The compiler died unexpectedly (internal error for example).
6089 @item 0
6090 An object file has been generated for every source file.
6091 @end table
6092 @end ifclear
6093 @end table
6094
6095 @node Debugging Control
6096 @subsection Debugging Control
6097
6098 @table @option
6099 @c !sort!
6100 @cindex Debugging options
6101 @ifclear vms
6102 @item -gnatd@var{x}
6103 @cindex @option{-gnatd} (@code{gcc})
6104 Activate internal debugging switches. @var{x} is a letter or digit, or
6105 string of letters or digits, which specifies the type of debugging
6106 outputs desired. Normally these are used only for internal development
6107 or system debugging purposes. You can find full documentation for these
6108 switches in the body of the @code{Debug} unit in the compiler source
6109 file @file{debug.adb}.
6110 @end ifclear
6111
6112 @item -gnatG
6113 @cindex @option{-gnatG} (@code{gcc})
6114 This switch causes the compiler to generate auxiliary output containing
6115 a pseudo-source listing of the generated expanded code. Like most Ada
6116 compilers, GNAT works by first transforming the high level Ada code into
6117 lower level constructs. For example, tasking operations are transformed
6118 into calls to the tasking run-time routines. A unique capability of GNAT
6119 is to list this expanded code in a form very close to normal Ada source.
6120 This is very useful in understanding the implications of various Ada
6121 usage on the efficiency of the generated code. There are many cases in
6122 Ada (e.g. the use of controlled types), where simple Ada statements can
6123 generate a lot of run-time code. By using @option{-gnatG} you can identify
6124 these cases, and consider whether it may be desirable to modify the coding
6125 approach to improve efficiency.
6126
6127 The format of the output is very similar to standard Ada source, and is
6128 easily understood by an Ada programmer. The following special syntactic
6129 additions correspond to low level features used in the generated code that
6130 do not have any exact analogies in pure Ada source form. The following
6131 is a partial list of these special constructions. See the specification
6132 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6133
6134 @table @code
6135 @item new @var{xxx} [storage_pool = @var{yyy}]
6136 Shows the storage pool being used for an allocator.
6137
6138 @item at end @var{procedure-name};
6139 Shows the finalization (cleanup) procedure for a scope.
6140
6141 @item (if @var{expr} then @var{expr} else @var{expr})
6142 Conditional expression equivalent to the @code{x?y:z} construction in C.
6143
6144 @item @var{target}^^^(@var{source})
6145 A conversion with floating-point truncation instead of rounding.
6146
6147 @item @var{target}?(@var{source})
6148 A conversion that bypasses normal Ada semantic checking. In particular
6149 enumeration types and fixed-point types are treated simply as integers.
6150
6151 @item @var{target}?^^^(@var{source})
6152 Combines the above two cases.
6153
6154 @item @var{x} #/ @var{y}
6155 @itemx @var{x} #mod @var{y}
6156 @itemx @var{x} #* @var{y}
6157 @itemx @var{x} #rem @var{y}
6158 A division or multiplication of fixed-point values which are treated as
6159 integers without any kind of scaling.
6160
6161 @item free @var{expr} [storage_pool = @var{xxx}]
6162 Shows the storage pool associated with a @code{free} statement.
6163
6164 @item freeze @var{typename} [@var{actions}]
6165 Shows the point at which @var{typename} is frozen, with possible
6166 associated actions to be performed at the freeze point.
6167
6168 @item reference @var{itype}
6169 Reference (and hence definition) to internal type @var{itype}.
6170
6171 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6172 Intrinsic function call.
6173
6174 @item @var{labelname} : label
6175 Declaration of label @var{labelname}.
6176
6177 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6178 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6179 @var{expr}, but handled more efficiently).
6180
6181 @item [constraint_error]
6182 Raise the @code{Constraint_Error} exception.
6183
6184 @item @var{expression}'reference
6185 A pointer to the result of evaluating @var{expression}.
6186
6187 @item @var{target-type}!(@var{source-expression})
6188 An unchecked conversion of @var{source-expression} to @var{target-type}.
6189
6190 @item [@var{numerator}/@var{denominator}]
6191 Used to represent internal real literals (that) have no exact
6192 representation in base 2-16 (for example, the result of compile time
6193 evaluation of the expression 1.0/27.0).
6194 @end table
6195
6196 @item -gnatD
6197 @cindex @option{-gnatD} (@code{gcc})
6198 When used in conjunction with @option{-gnatG}, this switch causes
6199 the expanded source, as described above for
6200 @option{-gnatG} to be written to files with names
6201 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6202 instead of to the standard ooutput file. For
6203 example, if the source file name is @file{hello.adb}, then a file
6204 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6205 information generated by the @code{gcc} @option{^-g^/DEBUG^} switch
6206 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6207 you to do source level debugging using the generated code which is
6208 sometimes useful for complex code, for example to find out exactly
6209 which part of a complex construction raised an exception. This switch
6210 also suppress generation of cross-reference information (see
6211 @option{-gnatx}) since otherwise the cross-reference information
6212 would refer to the @file{^.dg^.DG^} file, which would cause
6213 confusion since this is not the original source file.
6214
6215 Note that @option{-gnatD} actually implies @option{-gnatG}
6216 automatically, so it is not necessary to give both options.
6217 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6218
6219 @ifclear vms
6220 @item -gnatR[0|1|2|3[s]]
6221 @cindex @option{-gnatR} (@code{gcc})
6222 This switch controls output from the compiler of a listing showing
6223 representation information for declared types and objects. For
6224 @option{-gnatR0}, no information is output (equivalent to omitting
6225 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6226 so @option{-gnatR} with no parameter has the same effect), size and alignment
6227 information is listed for declared array and record types. For
6228 @option{-gnatR2}, size and alignment information is listed for all
6229 expression information for values that are computed at run time for
6230 variant records. These symbolic expressions have a mostly obvious
6231 format with #n being used to represent the value of the n'th
6232 discriminant. See source files @file{repinfo.ads/adb} in the
6233 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6234 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6235 the output is to a file with the name @file{^file.rep^file_REP^} where
6236 file is the name of the corresponding source file.
6237 @end ifclear
6238 @ifset vms
6239 @item /REPRESENTATION_INFO
6240 @cindex @option{/REPRESENTATION_INFO} (@code{gcc})
6241 This qualifier controls output from the compiler of a listing showing
6242 representation information for declared types and objects. For
6243 @option{/REPRESENTATION_INFO=NONE}, no information is output
6244 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6245 @option{/REPRESENTATION_INFO} without option is equivalent to
6246 @option{/REPRESENTATION_INFO=ARRAYS}.
6247 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6248 information is listed for declared array and record types. For
6249 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6250 is listed for all expression information for values that are computed
6251 at run time for variant records. These symbolic expressions have a mostly
6252 obvious format with #n being used to represent the value of the n'th
6253 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6254 @code{GNAT} sources for full details on the format of
6255 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6256 If _FILE is added at the end of an option
6257 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6258 then the output is to a file with the name @file{file_REP} where
6259 file is the name of the corresponding source file.
6260 @end ifset
6261
6262 @item -gnatS
6263 @cindex @option{-gnatS} (@code{gcc})
6264 The use of the switch @option{-gnatS} for an
6265 Ada compilation will cause the compiler to output a
6266 representation of package Standard in a form very
6267 close to standard Ada. It is not quite possible to
6268 do this entirely in standard Ada (since new
6269 numeric base types cannot be created in standard
6270 Ada), but the output is easily
6271 readable to any Ada programmer, and is useful to
6272 determine the characteristics of target dependent
6273 types in package Standard.
6274
6275 @item -gnatx
6276 @cindex @option{-gnatx} (@code{gcc})
6277 Normally the compiler generates full cross-referencing information in
6278 the @file{ALI} file. This information is used by a number of tools,
6279 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6280 suppresses this information. This saves some space and may slightly
6281 speed up compilation, but means that these tools cannot be used.
6282 @end table
6283
6284 @node Exception Handling Control
6285 @subsection Exception Handling Control
6286
6287 @noindent
6288 GNAT uses two methods for handling exceptions at run-time. The
6289 @code{longjmp/setjmp} method saves the context when entering
6290 a frame with an exception handler. Then when an exception is
6291 raised, the context can be restored immediately, without the
6292 need for tracing stack frames. This method provides very fast
6293 exception propagation, but introduces significant overhead for
6294 the use of exception handlers, even if no exception is raised.
6295
6296 The other approach is called ``zero cost'' exception handling.
6297 With this method, the compiler builds static tables to describe
6298 the exception ranges. No dynamic code is required when entering
6299 a frame containing an exception handler. When an exception is
6300 raised, the tables are used to control a back trace of the
6301 subprogram invocation stack to locate the required exception
6302 handler. This method has considerably poorer performance for
6303 the propagation of exceptions, but there is no overhead for
6304 exception handlers if no exception is raised.
6305
6306 The following switches can be used to control which of the
6307 two exception handling methods is used.
6308
6309 @table @option
6310 @c !sort!
6311
6312 @item -gnatL
6313 @cindex @option{-gnatL} (@code{gcc})
6314 This switch causes the longjmp/setjmp approach to be used
6315 for exception handling. If this is the default mechanism for the
6316 target (see below), then this has no effect. If the default
6317 mechanism for the target is zero cost exceptions, then
6318 this switch can be used to modify this default, but it must be
6319 used for all units in the partition, including all run-time
6320 library units. One way to achieve this is to use the
6321 @option{-a} and @option{-f} switches for @code{gnatmake}.
6322 This option is rarely used. One case in which it may be
6323 advantageous is if you have an application where exception
6324 raising is common and the overall performance of the
6325 application is improved by favoring exception propagation.
6326
6327 @item -gnatZ
6328 @cindex @option{-gnatZ} (@code{gcc})
6329 @cindex Zero Cost Exceptions
6330 This switch causes the zero cost approach to be sed
6331 for exception handling. If this is the default mechanism for the
6332 target (see below), then this has no effect. If the default
6333 mechanism for the target is longjmp/setjmp exceptions, then
6334 this switch can be used to modify this default, but it must be
6335 used for all units in the partition, including all run-time
6336 library units. One way to achieve this is to use the
6337 @option{-a} and @option{-f} switches for @code{gnatmake}.
6338 This option can only be used if the zero cost approach
6339 is available for the target in use (see below).
6340 @end table
6341
6342 @noindent
6343 The @code{longjmp/setjmp} approach is available on all targets, but
6344 the @code{zero cost} approach is only available on selected targets.
6345 To determine whether zero cost exceptions can be used for a
6346 particular target, look at the private part of the file system.ads.
6347 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6348 be True to use the zero cost approach. If both of these switches
6349 are set to False, this means that zero cost exception handling
6350 is not yet available for that target. The switch
6351 @code{ZCX_By_Default} indicates the default approach. If this
6352 switch is set to True, then the @code{zero cost} approach is
6353 used by default.
6354
6355 @node Units to Sources Mapping Files
6356 @subsection Units to Sources Mapping Files
6357
6358 @table @option
6359
6360 @item -gnatem^^=^@var{path}
6361 @cindex @option{-gnatem} (@code{gcc})
6362 A mapping file is a way to communicate to the compiler two mappings:
6363 from unit names to file names (without any directory information) and from
6364 file names to path names (with full directory information). These mappings
6365 are used by the compiler to short-circuit the path search.
6366
6367 The use of mapping files is not required for correct operation of the
6368 compiler, but mapping files can improve efficiency, particularly when
6369 sources are read over a slow network connection. In normal operation,
6370 you need not be concerned with the format or use of mapping files,
6371 and the @option{-gnatem} switch is not a switch that you would use
6372 explicitly. it is intended only for use by automatic tools such as
6373 @code{gnatmake} running under the project file facility. The
6374 description here of the format of mapping files is provided
6375 for completeness and for possible use by other tools.
6376
6377 A mapping file is a sequence of sets of three lines. In each set,
6378 the first line is the unit name, in lower case, with ``@code{%s}''
6379 appended for
6380 specifications and ``@code{%b}'' appended for bodies; the second line is the
6381 file name; and the third line is the path name.
6382
6383 Example:
6384 @smallexample
6385    main%b
6386    main.2.ada
6387    /gnat/project1/sources/main.2.ada
6388 @end smallexample
6389
6390 When the switch @option{-gnatem} is specified, the compiler will create
6391 in memory the two mappings from the specified file. If there is any problem
6392 (non existent file, truncated file or duplicate entries), no mapping
6393 will be created.
6394
6395 Several @option{-gnatem} switches may be specified; however, only the last
6396 one on the command line will be taken into account.
6397
6398 When using a project file, @code{gnatmake} create a temporary mapping file
6399 and communicates it to the compiler using this switch.
6400
6401 @end table
6402
6403
6404 @node Integrated Preprocessing
6405 @subsection Integrated Preprocessing
6406
6407 @noindent
6408 GNAT sources may be preprocessed immediately before compilation; the actual
6409 text of the source is not the text of the source file, but is derived from it
6410 through a process called preprocessing. Integrated preprocessing is specified
6411 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6412 indicates, through a text file, the preprocessing data to be used.
6413 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6414
6415 @noindent
6416 It is recommended that @code{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6417 used when Integrated Preprocessing is used. The reason is that preprocessing
6418 with another Preprocessing Data file without changing the sources will
6419 not trigger recompilation without this switch.
6420
6421 @noindent
6422 Note that @code{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6423 always trigger recompilation for sources that are preprocessed,
6424 because @code{gnatmake} cannot compute the checksum of the source after
6425 preprocessing.
6426
6427 @noindent
6428 The actual preprocessing function is described in details in section
6429 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6430 preprocessing is triggered and parameterized.
6431
6432 @table @code
6433
6434 @item -gnatep=@var{file}
6435 @cindex @option{-gnatep} (@code{gcc})
6436 This switch indicates to the compiler the file name (without directory
6437 information) of the preprocessor data file to use. The preprocessor data file
6438 should be found in the source directories.
6439
6440 @noindent
6441 A preprocessing data file is a text file with significant lines indicating
6442 how should be preprocessed either a specific source or all sources not
6443 mentioned in other lines. A significant line is a non empty, non comment line.
6444 Comments are similar to Ada comments.
6445
6446 @noindent
6447 Each significant line starts with either a literal string or the character '*'.
6448 A literal string is the file name (without directory information) of the source
6449 to preprocess. A character '*' indicates the preprocessing for all the sources
6450 that are not specified explicitly on other lines (order of the lines is not
6451 significant). It is an error to have two lines with the same file name or two
6452 lines starting with the character '*'.
6453
6454 @noindent
6455 After the file name or the character '*', another optional literal string
6456 indicating the file name of the definition file to be used for preprocessing.
6457 (see @ref{Form of Definitions File}. The definition files are found by the
6458 compiler in one of the source directories. In some cases, when compiling
6459 a source in a directory other than the current directory, if the definition
6460 file is in the current directory, it may be necessary to add the current
6461 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6462 the compiler would not find the definition file.
6463
6464 @noindent
6465 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6466 be found. Those ^switches^switches^ are:
6467
6468 @table @code
6469
6470 @item -b
6471 Causes both preprocessor lines and the lines deleted by
6472 preprocessing to be replaced by blank lines, preserving the line number.
6473 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6474 it cancels the effect of @option{-c}.
6475
6476 @item -c
6477 Causes both preprocessor lines and the lines deleted
6478 by preprocessing to be retained as comments marked
6479 with the special string ``@code{--! }''.
6480
6481 @item -Dsymbol=value
6482 Define or redefine a symbol, associated with value. A symbol is an Ada
6483 identifier, or an Ada reserved word, with the exception of @code{if},
6484 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6485 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6486 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6487 same name defined in a definition file.
6488
6489 @item -s
6490 Causes a sorted list of symbol names and values to be
6491 listed on the standard output file.
6492
6493 @item -u
6494 Causes undefined symbols to be treated as having the value @code{FALSE}
6495 in the context
6496 of a preprocessor test. In the absence of this option, an undefined symbol in
6497 a @code{#if} or @code{#elsif} test will be treated as an error.
6498
6499 @end table
6500
6501 @noindent
6502 Examples of valid lines in a preprocessor data file:
6503
6504 @smallexample
6505   "toto.adb"  "prep.def" -u
6506   --  preprocess "toto.adb", using definition file "prep.def",
6507   --  undefined symbol are False.
6508
6509   * -c -DVERSION=V101
6510   --  preprocess all other sources without a definition file;
6511   --  suppressed lined are commented; symbol VERSION has the value V101.
6512
6513   "titi.adb" "prep2.def" -s
6514   --  preprocess "titi.adb", using definition file "prep2.def";
6515   --  list all symbols with their values.
6516 @end smallexample
6517
6518 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6519 @cindex @option{-gnateD} (@code{gcc})
6520 Define or redefine a preprocessing symbol, associated with value. If no value
6521 is given on the command line, then the value of the symbol is @code{True}.
6522 A symbol is an identifier, following normal Ada (case-insensitive)
6523 rules for its syntax, and value is any sequence (including an empty sequence)
6524 of characters from the set (letters, digits, period, underline).
6525 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6526 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6527
6528 @noindent
6529 A symbol declared with this ^switch^switch^ on the command line replaces a
6530 symbol with the same name either in a definition file or specified with a
6531 ^switch^switch^ -D in the preprocessor data file.
6532
6533 @noindent
6534 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6535
6536 @end table
6537
6538 @node Code Generation Control
6539 @subsection Code Generation Control
6540
6541 @noindent
6542
6543 The GCC technology provides a wide range of target dependent
6544 @option{-m} switches for controlling
6545 details of code generation with respect to different versions of
6546 architectures. This includes variations in instruction sets (e.g.
6547 different members of the power pc family), and different requirements
6548 for optimal arrangement of instructions (e.g. different members of
6549 the x86 family). The list of available @option{-m} switches may be
6550 found in the GCC documentation.
6551
6552 Use of the these @option{-m} switches may in some cases result in improved
6553 code performance.
6554
6555 The GNAT Pro technology is tested and qualified without any
6556 @option{-m} switches,
6557 so generally the most reliable approach is to avoid the use of these
6558 switches. However, we generally expect most of these switches to work
6559 successfully with GNAT Pro, and many customers have reported successful
6560 use of these options.
6561
6562 Our general advice is to avoid the use of @option{-m} switches unless
6563 special needs lead to requirements in this area. In particular,
6564 there is no point in using @option{-m} switches to improve performance
6565 unless you actually see a performance improvement.
6566
6567 @ifset vms
6568 @node Return Codes
6569 @subsection Return Codes
6570 @cindex Return Codes
6571 @cindex @option{/RETURN_CODES=VMS}
6572
6573 @noindent
6574 On VMS, GNAT compiled programs return POSIX-style codes by default,
6575 e.g. @option{/RETURN_CODES=POSIX}.
6576
6577 To enable VMS style return codes, GNAT LINK with the option
6578 @option{/RETURN_CODES=VMS}. For example:
6579
6580 @smallexample
6581 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6582 @end smallexample
6583
6584 @noindent
6585 Programs built with /RETURN_CODES=VMS are suitable to be called in
6586 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6587 are suitable for spawning with appropriate GNAT RTL routines.
6588
6589 @end ifset
6590
6591
6592 @node Search Paths and the Run-Time Library (RTL)
6593 @section Search Paths and the Run-Time Library (RTL)
6594
6595 @noindent
6596 With the GNAT source-based library system, the compiler must be able to
6597 find source files for units that are needed by the unit being compiled.
6598 Search paths are used to guide this process.
6599
6600 The compiler compiles one source file whose name must be given
6601 explicitly on the command line. In other words, no searching is done
6602 for this file. To find all other source files that are needed (the most
6603 common being the specs of units), the compiler examines the following
6604 directories, in the following order:
6605
6606 @enumerate
6607 @item
6608 The directory containing the source file of the main unit being compiled
6609 (the file name on the command line).
6610
6611 @item
6612 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6613 @code{gcc} command line, in the order given.
6614
6615 @item
6616 @findex ADA_INCLUDE_PATH
6617 Each of the directories listed in the value of the
6618 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6619 @ifclear vms
6620 Construct this value
6621 exactly as the @code{PATH} environment variable: a list of directory
6622 names separated by colons (semicolons when working with the NT version).
6623 @end ifclear
6624 @ifset vms
6625 Normally, define this value as a logical name containing a comma separated
6626 list of directory names.
6627
6628 This variable can also be defined by means of an environment string
6629 (an argument to the DEC C exec* set of functions).
6630
6631 Logical Name:
6632 @smallexample
6633 DEFINE ANOTHER_PATH FOO:[BAG]
6634 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6635 @end smallexample
6636
6637 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6638 first, followed by the standard Ada 95
6639 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6640 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
6641 (Text_IO, Sequential_IO, etc)
6642 instead of the Ada95 packages. Thus, in order to get the Ada 95
6643 packages by default, ADA_INCLUDE_PATH must be redefined.
6644 @end ifset
6645
6646 @item
6647 @findex ADA_PRJ_INCLUDE_FILE
6648 Each of the directories listed in the text file whose name is given
6649 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6650
6651 @noindent
6652 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6653 driver when project files are used. It should not normally be set
6654 by other means.
6655
6656 @item
6657 The content of the @file{ada_source_path} file which is part of the GNAT
6658 installation tree and is used to store standard libraries such as the
6659 GNAT Run Time Library (RTL) source files.
6660 @ifclear vms
6661 @ref{Installing the library}
6662 @end ifclear
6663 @end enumerate
6664
6665 @noindent
6666 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6667 inhibits the use of the directory
6668 containing the source file named in the command line. You can still
6669 have this directory on your search path, but in this case it must be
6670 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6671
6672 Specifying the switch @option{-nostdinc}
6673 inhibits the search of the default location for the GNAT Run Time
6674 Library (RTL) source files.
6675
6676 The compiler outputs its object files and ALI files in the current
6677 working directory.
6678 @ifclear vms
6679 Caution: The object file can be redirected with the @option{-o} switch;
6680 however, @code{gcc} and @code{gnat1} have not been coordinated on this
6681 so the @file{ALI} file will not go to the right place. Therefore, you should
6682 avoid using the @option{-o} switch.
6683 @end ifclear
6684
6685 @findex System.IO
6686 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6687 children make up the GNAT RTL, together with the simple @code{System.IO}
6688 package used in the @code{"Hello World"} example. The sources for these units
6689 are needed by the compiler and are kept together in one directory. Not
6690 all of the bodies are needed, but all of the sources are kept together
6691 anyway. In a normal installation, you need not specify these directory
6692 names when compiling or binding. Either the environment variables or
6693 the built-in defaults cause these files to be found.
6694
6695 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6696 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6697 consisting of child units of @code{GNAT}. This is a collection of generally
6698 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6699 further details.
6700
6701 Besides simplifying access to the RTL, a major use of search paths is
6702 in compiling sources from multiple directories. This can make
6703 development environments much more flexible.
6704
6705
6706 @node Order of Compilation Issues
6707 @section Order of Compilation Issues
6708
6709 @noindent
6710 If, in our earlier example, there was a spec for the @code{hello}
6711 procedure, it would be contained in the file @file{hello.ads}; yet this
6712 file would not have to be explicitly compiled. This is the result of the
6713 model we chose to implement library management. Some of the consequences
6714 of this model are as follows:
6715
6716 @itemize @bullet
6717 @item
6718 There is no point in compiling specs (except for package
6719 specs with no bodies) because these are compiled as needed by clients. If
6720 you attempt a useless compilation, you will receive an error message.
6721 It is also useless to compile subunits because they are compiled as needed
6722 by the parent.
6723
6724 @item
6725 There are no order of compilation requirements: performing a
6726 compilation never obsoletes anything. The only way you can obsolete
6727 something and require recompilations is to modify one of the
6728 source files on which it depends.
6729
6730 @item
6731 There is no library as such, apart from the ALI files
6732 (@pxref{The Ada Library Information Files}, for information on the format
6733 of these files). For now we find it convenient to create separate ALI files,
6734 but eventually the information therein may be incorporated into the object
6735 file directly.
6736
6737 @item
6738 When you compile a unit, the source files for the specs of all units
6739 that it @code{with}'s, all its subunits, and the bodies of any generics it
6740 instantiates must be available (reachable by the search-paths mechanism
6741 described above), or you will receive a fatal error message.
6742 @end itemize
6743
6744 @node Examples
6745 @section Examples
6746
6747 @noindent
6748 The following are some typical Ada compilation command line examples:
6749
6750 @table @code
6751 @item $ gcc -c xyz.adb
6752 Compile body in file @file{xyz.adb} with all default options.
6753
6754 @ifclear vms
6755 @item $ gcc -c -O2 -gnata xyz-def.adb
6756 @end ifclear
6757 @ifset vms
6758 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6759 @end ifset
6760
6761 Compile the child unit package in file @file{xyz-def.adb} with extensive
6762 optimizations, and pragma @code{Assert}/@code{Debug} statements
6763 enabled.
6764
6765 @item $ gcc -c -gnatc abc-def.adb
6766 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6767 mode.
6768 @end table
6769
6770 @node Binding Using gnatbind
6771 @chapter Binding Using @code{gnatbind}
6772 @findex gnatbind
6773
6774 @menu
6775 * Running gnatbind::
6776 * Switches for gnatbind::
6777 * Command-Line Access::
6778 * Search Paths for gnatbind::
6779 * Examples of gnatbind Usage::
6780 @end menu
6781
6782 @noindent
6783 This chapter describes the GNAT binder, @code{gnatbind}, which is used
6784 to bind compiled GNAT objects. The @code{gnatbind} program performs
6785 four separate functions:
6786
6787 @enumerate
6788 @item
6789 Checks that a program is consistent, in accordance with the rules in
6790 Chapter 10 of the Ada 95 Reference Manual. In particular, error
6791 messages are generated if a program uses inconsistent versions of a
6792 given unit.
6793
6794 @item
6795 Checks that an acceptable order of elaboration exists for the program
6796 and issues an error message if it cannot find an order of elaboration
6797 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6798
6799 @item
6800 Generates a main program incorporating the given elaboration order.
6801 This program is a small Ada package (body and spec) that
6802 must be subsequently compiled
6803 using the GNAT compiler. The necessary compilation step is usually
6804 performed automatically by @code{gnatlink}. The two most important
6805 functions of this program
6806 are to call the elaboration routines of units in an appropriate order
6807 and to call the main program.
6808
6809 @item
6810 Determines the set of object files required by the given main program.
6811 This information is output in the forms of comments in the generated program,
6812 to be read by the @code{gnatlink} utility used to link the Ada application.
6813 @end enumerate
6814
6815
6816 @node Running gnatbind
6817 @section Running @code{gnatbind}
6818
6819 @noindent
6820 The form of the @code{gnatbind} command is
6821
6822 @smallexample
6823 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
6824 @end smallexample
6825
6826 @noindent
6827 where @file{@i{mainprog}.adb} is the Ada file containing the main program
6828 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
6829 package in two files whose names are
6830 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
6831 For example, if given the
6832 parameter @file{hello.ali}, for a main program contained in file
6833 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
6834 and @file{b~hello.adb}.
6835
6836 When doing consistency checking, the binder takes into consideration
6837 any source files it can locate. For example, if the binder determines
6838 that the given main program requires the package @code{Pack}, whose
6839 @file{.ALI}
6840 file is @file{pack.ali} and whose corresponding source spec file is
6841 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
6842 (using the same search path conventions as previously described for the
6843 @code{gcc} command). If it can locate this source file, it checks that
6844 the time stamps
6845 or source checksums of the source and its references to in @file{ALI} files
6846 match. In other words, any @file{ALI} files that mentions this spec must have
6847 resulted from compiling this version of the source file (or in the case
6848 where the source checksums match, a version close enough that the
6849 difference does not matter).
6850
6851 @cindex Source files, use by binder
6852 The effect of this consistency checking, which includes source files, is
6853 that the binder ensures that the program is consistent with the latest
6854 version of the source files that can be located at bind time. Editing a
6855 source file without compiling files that depend on the source file cause
6856 error messages to be generated by the binder.
6857
6858 For example, suppose you have a main program @file{hello.adb} and a
6859 package @code{P}, from file @file{p.ads} and you perform the following
6860 steps:
6861
6862 @enumerate
6863 @item
6864 Enter @code{gcc -c hello.adb} to compile the main program.
6865
6866 @item
6867 Enter @code{gcc -c p.ads} to compile package @code{P}.
6868
6869 @item
6870 Edit file @file{p.ads}.
6871
6872 @item
6873 Enter @code{gnatbind hello}.
6874 @end enumerate
6875
6876 @noindent
6877 At this point, the file @file{p.ali} contains an out-of-date time stamp
6878 because the file @file{p.ads} has been edited. The attempt at binding
6879 fails, and the binder generates the following error messages:
6880
6881 @smallexample
6882 error: "hello.adb" must be recompiled ("p.ads" has been modified)
6883 error: "p.ads" has been modified and must be recompiled
6884 @end smallexample
6885
6886 @noindent
6887 Now both files must be recompiled as indicated, and then the bind can
6888 succeed, generating a main program. You need not normally be concerned
6889 with the contents of this file, but for reference purposes a sample
6890 binder output file is given in @ref{Example of Binder Output File}.
6891
6892 In most normal usage, the default mode of @command{gnatbind} which is to
6893 generate the main package in Ada, as described in the previous section.
6894 In particular, this means that any Ada programmer can read and understand
6895 the generated main program. It can also be debugged just like any other
6896 Ada code provided the @option{^-g^/DEBUG^} switch is used for
6897 @command{gnatbind} and @command{gnatlink}.
6898
6899 However for some purposes it may be convenient to generate the main
6900 program in C rather than Ada. This may for example be helpful when you
6901 are generating a mixed language program with the main program in C. The
6902 GNAT compiler itself is an example.
6903 The use of the @option{^-C^/BIND_FILE=C^} switch
6904 for both @code{gnatbind} and @code{gnatlink} will cause the program to
6905 be generated in C (and compiled using the gnu C compiler).
6906
6907
6908 @node Switches for gnatbind
6909 @section Switches for @command{gnatbind}
6910
6911 @noindent
6912 The following switches are available with @code{gnatbind}; details will
6913 be presented in subsequent sections.
6914
6915 @menu
6916 * Consistency-Checking Modes::
6917 * Binder Error Message Control::
6918 * Elaboration Control::
6919 * Output Control::
6920 * Binding with Non-Ada Main Programs::
6921 * Binding Programs with No Main Subprogram::
6922 @end menu
6923
6924 @table @option
6925 @c !sort!
6926 @item ^-aO^/OBJECT_SEARCH^
6927 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
6928 Specify directory to be searched for ALI files.
6929
6930 @item ^-aI^/SOURCE_SEARCH^
6931 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
6932 Specify directory to be searched for source file.
6933
6934 @item ^-A^/BIND_FILE=ADA^
6935 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
6936 Generate binder program in Ada (default)
6937
6938 @item ^-b^/REPORT_ERRORS=BRIEF^
6939 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
6940 Generate brief messages to @file{stderr} even if verbose mode set.
6941
6942 @item ^-c^/NOOUTPUT^
6943 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
6944 Check only, no generation of binder output file.
6945
6946 @item ^-C^/BIND_FILE=C^
6947 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
6948 Generate binder program in C
6949
6950 @item ^-e^/ELABORATION_DEPENDENCIES^
6951 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
6952 Output complete list of elaboration-order dependencies.
6953
6954 @item ^-E^/STORE_TRACEBACKS^
6955 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
6956 Store tracebacks in exception occurrences when the target supports it.
6957 This is the default with the zero cost exception mechanism.
6958 @ignore
6959 @c The following may get moved to an appendix
6960 This option is currently supported on the following targets:
6961 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6962 @end ignore
6963 See also the packages @code{GNAT.Traceback} and
6964 @code{GNAT.Traceback.Symbolic} for more information.
6965 @ifclear vms
6966 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
6967 @code{gcc} option.
6968 @end ifclear
6969
6970 @item ^-F^/FORCE_ELABS_FLAGS^
6971 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
6972 Force the checks of elaboration flags. @command{gnatbind} does not normally
6973 generate checks of elaboration flags for the main executable, except when
6974 a Stand-Alone Library is used. However, there are cases when this cannot be
6975 detected by gnatbind. An example is importing an interface of a Stand-Alone
6976 Library through a pragma Import and only specifying through a linker switch
6977 this Stand-Alone Library. This switch is used to guarantee that elaboration
6978 flag checks are generated.
6979
6980 @item ^-h^/HELP^
6981 @cindex @option{^-h^/HELP^} (@command{gnatbind})
6982 Output usage (help) information
6983
6984 @item ^-I^/SEARCH^
6985 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
6986 Specify directory to be searched for source and ALI files.
6987
6988 @item ^-I-^/NOCURRENT_DIRECTORY^
6989 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
6990 Do not look for sources in the current directory where @code{gnatbind} was
6991 invoked, and do not look for ALI files in the directory containing the
6992 ALI file named in the @code{gnatbind} command line.
6993
6994 @item ^-l^/ORDER_OF_ELABORATION^
6995 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
6996 Output chosen elaboration order.
6997
6998 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
6999 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7000 Binds the units for library building. In this case the adainit and
7001 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
7002 are renamed to ^xxxinit^XXXINIT^ and
7003 ^xxxfinal^XXXFINAL^.
7004 Implies ^-n^/NOCOMPILE^.
7005 @ifclear vms
7006 (@pxref{GNAT and Libraries}, for more details.)
7007 @end ifclear
7008 @ifset vms
7009 On OpenVMS, these init and final procedures are exported in uppercase
7010 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7011 the init procedure will be "TOTOINIT" and the exported name of the final
7012 procedure will be "TOTOFINAL".
7013 @end ifset
7014
7015 @item ^-Mxyz^/RENAME_MAIN=xyz^
7016 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7017 Rename generated main program from main to xyz
7018
7019 @item ^-m^/ERROR_LIMIT=^@var{n}
7020 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7021 Limit number of detected errors to @var{n}, where @var{n} is
7022 in the range 1..999_999. The default value if no switch is
7023 given is 9999. Binding is terminated if the limit is exceeded.
7024 @ifset unw
7025 Furthermore, under Windows, the sources pointed to by the libraries path
7026 set in the registry are not searched for.
7027 @end ifset
7028
7029 @item ^-n^/NOMAIN^
7030 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7031 No main program.
7032
7033 @item -nostdinc
7034 @cindex @option{-nostdinc} (@command{gnatbind})
7035 Do not look for sources in the system default directory.
7036
7037 @item -nostdlib
7038 @cindex @option{-nostdlib} (@command{gnatbind})
7039 Do not look for library files in the system default directory.
7040
7041 @item --RTS=@var{rts-path}
7042 @cindex @option{--RTS} (@code{gnatbind})
7043 Specifies the default location of the runtime library. Same meaning as the
7044 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
7045
7046 @item ^-o ^/OUTPUT=^@var{file}
7047 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7048 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7049 Note that if this option is used, then linking must be done manually,
7050 gnatlink cannot be used.
7051
7052 @item ^-O^/OBJECT_LIST^
7053 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7054 Output object list.
7055
7056 @item ^-p^/PESSIMISTIC_ELABORATION^
7057 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7058 Pessimistic (worst-case) elaboration order
7059
7060 @item ^-s^/READ_SOURCES=ALL^
7061 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7062 Require all source files to be present.
7063
7064 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7065 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7066 Specifies the value to be used when detecting uninitialized scalar
7067 objects with pragma Initialize_Scalars.
7068 The @var{xxx} ^string specified with the switch^option^ may be either
7069 @itemize @bullet
7070 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7071 @item ``@option{^lo^LOW^}'' for the lowest possible value
7072 possible, and the low
7073 @item ``@option{^hi^HIGH^}'' for the highest possible value
7074 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7075 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7076 @end itemize
7077
7078 In addition, you can specify @option{-Sev} to indicate that the value is
7079 to be set at run time. In this case, the program will look for an environment
7080 @cindex GNAT_INIT_SCALARS
7081 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7082 of @option{in/lo/hi/xx} with the same meanings as above.
7083 If no environment variable is found, or if it does not have a valid value,
7084 then the default is @option{in} (invalid values).
7085
7086 @ifclear vms
7087 @item -static
7088 @cindex @option{-static} (@code{gnatbind})
7089 Link against a static GNAT run time.
7090
7091 @item -shared
7092 @cindex @option{-shared} (@code{gnatbind})
7093 Link against a shared GNAT run time when available.
7094 @end ifclear
7095
7096 @item ^-t^/NOTIME_STAMP_CHECK^
7097 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7098 Tolerate time stamp and other consistency errors
7099
7100 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7101 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7102 Set the time slice value to @var{n} milliseconds. If the system supports
7103 the specification of a specific time slice value, then the indicated value
7104 is used. If the system does not support specific time slice values, but
7105 does support some general notion of round-robin scheduling, then any
7106 non-zero value will activate round-robin scheduling.
7107
7108 A value of zero is treated specially. It turns off time
7109 slicing, and in addition, indicates to the tasking run time that the
7110 semantics should match as closely as possible the Annex D
7111 requirements of the Ada RM, and in particular sets the default
7112 scheduling policy to @code{FIFO_Within_Priorities}.
7113
7114 @item ^-v^/REPORT_ERRORS=VERBOSE^
7115 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7116 Verbose mode. Write error messages, header, summary output to
7117 @file{stdout}.
7118
7119 @ifclear vms
7120 @item -w@var{x}
7121 @cindex @option{-w} (@code{gnatbind})
7122 Warning mode (@var{x}=s/e for suppress/treat as error)
7123 @end ifclear
7124
7125 @ifset vms
7126 @item /WARNINGS=NORMAL
7127 @cindex @option{/WARNINGS} (@code{gnatbind})
7128 Normal warnings mode. Warnings are issued but ignored
7129
7130 @item /WARNINGS=SUPPRESS
7131 @cindex @option{/WARNINGS} (@code{gnatbind})
7132 All warning messages are suppressed
7133
7134 @item /WARNINGS=ERROR
7135 @cindex @option{/WARNINGS} (@code{gnatbind})
7136 Warning messages are treated as fatal errors
7137 @end ifset
7138
7139 @item ^-x^/READ_SOURCES=NONE^
7140 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7141 Exclude source files (check object consistency only).
7142
7143 @ifset vms
7144 @item /READ_SOURCES=AVAILABLE
7145 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7146 Default mode, in which sources are checked for consistency only if
7147 they are available.
7148 @end ifset
7149
7150 @item ^-z^/ZERO_MAIN^
7151 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7152 No main subprogram.
7153 @end table
7154
7155 @ifclear vms
7156 @noindent
7157 You may obtain this listing of switches by running @code{gnatbind} with
7158 no arguments.
7159 @end ifclear
7160
7161
7162 @node Consistency-Checking Modes
7163 @subsection Consistency-Checking Modes
7164
7165 @noindent
7166 As described earlier, by default @code{gnatbind} checks
7167 that object files are consistent with one another and are consistent
7168 with any source files it can locate. The following switches control binder
7169 access to sources.
7170
7171 @table @option
7172 @c !sort!
7173 @item ^-s^/READ_SOURCES=ALL^
7174 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7175 Require source files to be present. In this mode, the binder must be
7176 able to locate all source files that are referenced, in order to check
7177 their consistency. In normal mode, if a source file cannot be located it
7178 is simply ignored. If you specify this switch, a missing source
7179 file is an error.
7180
7181 @item ^-x^/READ_SOURCES=NONE^
7182 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7183 Exclude source files. In this mode, the binder only checks that ALI
7184 files are consistent with one another. Source files are not accessed.
7185 The binder runs faster in this mode, and there is still a guarantee that
7186 the resulting program is self-consistent.
7187 If a source file has been edited since it was last compiled, and you
7188 specify this switch, the binder will not detect that the object
7189 file is out of date with respect to the source file. Note that this is the
7190 mode that is automatically used by @code{gnatmake} because in this
7191 case the checking against sources has already been performed by
7192 @code{gnatmake} in the course of compilation (i.e. before binding).
7193
7194 @ifset vms
7195 @item /READ_SOURCES=AVAILABLE
7196 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7197 This is the default mode in which source files are checked if they are
7198 available, and ignored if they are not available.
7199 @end ifset
7200 @end table
7201
7202 @node Binder Error Message Control
7203 @subsection Binder Error Message Control
7204
7205 @noindent
7206 The following switches provide control over the generation of error
7207 messages from the binder:
7208
7209 @table @option
7210 @c !sort!
7211 @item ^-v^/REPORT_ERRORS=VERBOSE^
7212 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7213 Verbose mode. In the normal mode, brief error messages are generated to
7214 @file{stderr}. If this switch is present, a header is written
7215 to @file{stdout} and any error messages are directed to @file{stdout}.
7216 All that is written to @file{stderr} is a brief summary message.
7217
7218 @item ^-b^/REPORT_ERRORS=BRIEF^
7219 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7220 Generate brief error messages to @file{stderr} even if verbose mode is
7221 specified. This is relevant only when used with the
7222 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7223
7224 @ifclear vms
7225 @item -m@var{n}
7226 @cindex @option{-m} (@code{gnatbind})
7227 Limits the number of error messages to @var{n}, a decimal integer in the
7228 range 1-999. The binder terminates immediately if this limit is reached.
7229
7230 @item -M@var{xxx}
7231 @cindex @option{-M} (@code{gnatbind})
7232 Renames the generated main program from @code{main} to @code{xxx}.
7233 This is useful in the case of some cross-building environments, where
7234 the actual main program is separate from the one generated
7235 by @code{gnatbind}.
7236 @end ifclear
7237
7238 @item ^-ws^/WARNINGS=SUPPRESS^
7239 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7240 @cindex Warnings
7241 Suppress all warning messages.
7242
7243 @item ^-we^/WARNINGS=ERROR^
7244 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7245 Treat any warning messages as fatal errors.
7246
7247 @ifset vms
7248 @item /WARNINGS=NORMAL
7249 Standard mode with warnings generated, but warnings do not get treated
7250 as errors.
7251 @end ifset
7252
7253 @item ^-t^/NOTIME_STAMP_CHECK^
7254 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7255 @cindex Time stamp checks, in binder
7256 @cindex Binder consistency checks
7257 @cindex Consistency checks, in binder
7258 The binder performs a number of consistency checks including:
7259
7260 @itemize @bullet
7261 @item
7262 Check that time stamps of a given source unit are consistent
7263 @item
7264 Check that checksums of a given source unit are consistent
7265 @item
7266 Check that consistent versions of @code{GNAT} were used for compilation
7267 @item
7268 Check consistency of configuration pragmas as required
7269 @end itemize
7270
7271 @noindent
7272 Normally failure of such checks, in accordance with the consistency
7273 requirements of the Ada Reference Manual, causes error messages to be
7274 generated which abort the binder and prevent the output of a binder
7275 file and subsequent link to obtain an executable.
7276
7277 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7278 into warnings, so that
7279 binding and linking can continue to completion even in the presence of such
7280 errors. The result may be a failed link (due to missing symbols), or a
7281 non-functional executable which has undefined semantics.
7282 @emph{This means that
7283 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7284 with extreme care.}
7285 @end table
7286
7287 @node Elaboration Control
7288 @subsection Elaboration Control
7289
7290 @noindent
7291 The following switches provide additional control over the elaboration
7292 order. For full details see @xref{Elaboration Order Handling in GNAT}.
7293
7294 @table @option
7295 @item ^-p^/PESSIMISTIC_ELABORATION^
7296 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7297 Normally the binder attempts to choose an elaboration order that is
7298 likely to minimize the likelihood of an elaboration order error resulting
7299 in raising a @code{Program_Error} exception. This switch reverses the
7300 action of the binder, and requests that it deliberately choose an order
7301 that is likely to maximize the likelihood of an elaboration error.
7302 This is useful in ensuring portability and avoiding dependence on
7303 accidental fortuitous elaboration ordering.
7304
7305 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7306 switch if dynamic
7307 elaboration checking is used (@option{-gnatE} switch used for compilation).
7308 This is because in the default static elaboration mode, all necessary
7309 @code{Elaborate_All} pragmas are implicitly inserted.
7310 These implicit pragmas are still respected by the binder in
7311 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7312 safe elaboration order is assured.
7313 @end table
7314
7315 @node Output Control
7316 @subsection Output Control
7317
7318 @noindent
7319 The following switches allow additional control over the output
7320 generated by the binder.
7321
7322 @table @option
7323 @c !sort!
7324
7325 @item ^-A^/BIND_FILE=ADA^
7326 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7327 Generate binder program in Ada (default). The binder program is named
7328 @file{b~@var{mainprog}.adb} by default. This can be changed with
7329 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7330
7331 @item ^-c^/NOOUTPUT^
7332 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7333 Check only. Do not generate the binder output file. In this mode the
7334 binder performs all error checks but does not generate an output file.
7335
7336 @item ^-C^/BIND_FILE=C^
7337 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7338 Generate binder program in C. The binder program is named
7339 @file{b_@var{mainprog}.c}.
7340 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7341 option.
7342
7343 @item ^-e^/ELABORATION_DEPENDENCIES^
7344 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7345 Output complete list of elaboration-order dependencies, showing the
7346 reason for each dependency. This output can be rather extensive but may
7347 be useful in diagnosing problems with elaboration order. The output is
7348 written to @file{stdout}.
7349
7350 @item ^-h^/HELP^
7351 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7352 Output usage information. The output is written to @file{stdout}.
7353
7354 @item ^-K^/LINKER_OPTION_LIST^
7355 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7356 Output linker options to @file{stdout}. Includes library search paths,
7357 contents of pragmas Ident and Linker_Options, and libraries added
7358 by @code{gnatbind}.
7359
7360 @item ^-l^/ORDER_OF_ELABORATION^
7361 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7362 Output chosen elaboration order. The output is written to @file{stdout}.
7363
7364 @item ^-O^/OBJECT_LIST^
7365 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7366 Output full names of all the object files that must be linked to provide
7367 the Ada component of the program. The output is written to @file{stdout}.
7368 This list includes the files explicitly supplied and referenced by the user
7369 as well as implicitly referenced run-time unit files. The latter are
7370 omitted if the corresponding units reside in shared libraries. The
7371 directory names for the run-time units depend on the system configuration.
7372
7373 @item ^-o ^/OUTPUT=^@var{file}
7374 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7375 Set name of output file to @var{file} instead of the normal
7376 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7377 binder generated body filename. In C mode you would normally give
7378 @var{file} an extension of @file{.c} because it will be a C source program.
7379 Note that if this option is used, then linking must be done manually.
7380 It is not possible to use gnatlink in this case, since it cannot locate
7381 the binder file.
7382
7383 @item ^-r^/RESTRICTION_LIST^
7384 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7385 Generate list of @code{pragma Restrictions} that could be applied to
7386 the current unit. This is useful for code audit purposes, and also may
7387 be used to improve code generation in some cases.
7388
7389 @end table
7390
7391 @node Binding with Non-Ada Main Programs
7392 @subsection Binding with Non-Ada Main Programs
7393
7394 @noindent
7395 In our description so far we have assumed that the main
7396 program is in Ada, and that the task of the binder is to generate a
7397 corresponding function @code{main} that invokes this Ada main
7398 program. GNAT also supports the building of executable programs where
7399 the main program is not in Ada, but some of the called routines are
7400 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7401 The following switch is used in this situation:
7402
7403 @table @option
7404 @item ^-n^/NOMAIN^
7405 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7406 No main program. The main program is not in Ada.
7407 @end table
7408
7409 @noindent
7410 In this case, most of the functions of the binder are still required,
7411 but instead of generating a main program, the binder generates a file
7412 containing the following callable routines:
7413
7414 @table @code
7415 @item adainit
7416 @findex adainit
7417 You must call this routine to initialize the Ada part of the program by
7418 calling the necessary elaboration routines. A call to @code{adainit} is
7419 required before the first call to an Ada subprogram.
7420
7421 Note that it is assumed that the basic execution environment must be setup
7422 to be appropriate for Ada execution at the point where the first Ada
7423 subprogram is called. In particular, if the Ada code will do any
7424 floating-point operations, then the FPU must be setup in an appropriate
7425 manner. For the case of the x86, for example, full precision mode is
7426 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7427 that the FPU is in the right state.
7428
7429 @item adafinal
7430 @findex adafinal
7431 You must call this routine to perform any library-level finalization
7432 required by the Ada subprograms. A call to @code{adafinal} is required
7433 after the last call to an Ada subprogram, and before the program
7434 terminates.
7435 @end table
7436
7437 @noindent
7438 If the @option{^-n^/NOMAIN^} switch
7439 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7440 @cindex Binder, multiple input files
7441 is given, more than one ALI file may appear on
7442 the command line for @code{gnatbind}. The normal @dfn{closure}
7443 calculation is performed for each of the specified units. Calculating
7444 the closure means finding out the set of units involved by tracing
7445 @code{with} references. The reason it is necessary to be able to
7446 specify more than one ALI file is that a given program may invoke two or
7447 more quite separate groups of Ada units.
7448
7449 The binder takes the name of its output file from the last specified ALI
7450 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7451 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7452 The output is an Ada unit in source form that can
7453 be compiled with GNAT unless the -C switch is used in which case the
7454 output is a C source file, which must be compiled using the C compiler.
7455 This compilation occurs automatically as part of the @code{gnatlink}
7456 processing.
7457
7458 Currently the GNAT run time requires a FPU using 80 bits mode
7459 precision. Under targets where this is not the default it is required to
7460 call GNAT.Float_Control.Reset before using floating point numbers (this
7461 include float computation, float input and output) in the Ada code. A
7462 side effect is that this could be the wrong mode for the foreign code
7463 where floating point computation could be broken after this call.
7464
7465 @node Binding Programs with No Main Subprogram
7466 @subsection Binding Programs with No Main Subprogram
7467
7468 @noindent
7469 It is possible to have an Ada program which does not have a main
7470 subprogram. This program will call the elaboration routines of all the
7471 packages, then the finalization routines.
7472
7473 The following switch is used to bind programs organized in this manner:
7474
7475 @table @option
7476 @item ^-z^/ZERO_MAIN^
7477 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7478 Normally the binder checks that the unit name given on the command line
7479 corresponds to a suitable main subprogram. When this switch is used,
7480 a list of ALI files can be given, and the execution of the program
7481 consists of elaboration of these units in an appropriate order.
7482 @end table
7483
7484
7485 @node Command-Line Access
7486 @section Command-Line Access
7487
7488 @noindent
7489 The package @code{Ada.Command_Line} provides access to the command-line
7490 arguments and program name. In order for this interface to operate
7491 correctly, the two variables
7492
7493 @smallexample
7494 @group
7495 int gnat_argc;
7496 char **gnat_argv;
7497 @end group
7498 @end smallexample
7499
7500 @noindent
7501 @findex gnat_argv
7502 @findex gnat_argc
7503 are declared in one of the GNAT library routines. These variables must
7504 be set from the actual @code{argc} and @code{argv} values passed to the
7505 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7506 generates the C main program to automatically set these variables.
7507 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7508 set these variables. If they are not set, the procedures in
7509 @code{Ada.Command_Line} will not be available, and any attempt to use
7510 them will raise @code{Constraint_Error}. If command line access is
7511 required, your main program must set @code{gnat_argc} and
7512 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7513 it.
7514
7515
7516 @node Search Paths for gnatbind
7517 @section Search Paths for @code{gnatbind}
7518
7519 @noindent
7520 The binder takes the name of an ALI file as its argument and needs to
7521 locate source files as well as other ALI files to verify object consistency.
7522
7523 For source files, it follows exactly the same search rules as @code{gcc}
7524 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7525 directories searched are:
7526
7527 @enumerate
7528 @item
7529 The directory containing the ALI file named in the command line, unless
7530 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7531
7532 @item
7533 All directories specified by @option{^-I^/SEARCH^}
7534 switches on the @code{gnatbind}
7535 command line, in the order given.
7536
7537 @item
7538 @findex ADA_OBJECTS_PATH
7539 Each of the directories listed in the value of the
7540 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7541 @ifset unw
7542 Construct this value
7543 exactly as the @code{PATH} environment variable: a list of directory
7544 names separated by colons (semicolons when working with the NT version
7545 of GNAT).
7546 @end ifset
7547 @ifset vms
7548 Normally, define this value as a logical name containing a comma separated
7549 list of directory names.
7550
7551 This variable can also be defined by means of an environment string
7552 (an argument to the DEC C exec* set of functions).
7553
7554 Logical Name:
7555 @smallexample
7556 DEFINE ANOTHER_PATH FOO:[BAG]
7557 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7558 @end smallexample
7559
7560 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7561 first, followed by the standard Ada 95
7562 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7563 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
7564 (Text_IO, Sequential_IO, etc)
7565 instead of the Ada95 packages. Thus, in order to get the Ada 95
7566 packages by default, ADA_OBJECTS_PATH must be redefined.
7567 @end ifset
7568
7569 @item
7570 @findex ADA_PRJ_OBJECTS_FILE
7571 Each of the directories listed in the text file whose name is given
7572 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7573
7574 @noindent
7575 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7576 driver when project files are used. It should not normally be set
7577 by other means.
7578
7579 @item
7580 The content of the @file{ada_object_path} file which is part of the GNAT
7581 installation tree and is used to store standard libraries such as the
7582 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7583 specified.
7584 @ifclear vms
7585 @ref{Installing the library}
7586 @end ifclear
7587 @end enumerate
7588
7589 @noindent
7590 In the binder the switch @option{^-I^/SEARCH^}
7591 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7592 is used to specify both source and
7593 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7594 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7595 instead if you want to specify
7596 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7597 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7598 if you want to specify library paths
7599 only. This means that for the binder
7600 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7601 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7602 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7603 The binder generates the bind file (a C language source file) in the
7604 current working directory.
7605
7606 @findex Ada
7607 @findex System
7608 @findex Interfaces
7609 @findex GNAT
7610 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7611 children make up the GNAT Run-Time Library, together with the package
7612 GNAT and its children, which contain a set of useful additional
7613 library functions provided by GNAT. The sources for these units are
7614 needed by the compiler and are kept together in one directory. The ALI
7615 files and object files generated by compiling the RTL are needed by the
7616 binder and the linker and are kept together in one directory, typically
7617 different from the directory containing the sources. In a normal
7618 installation, you need not specify these directory names when compiling
7619 or binding. Either the environment variables or the built-in defaults
7620 cause these files to be found.
7621
7622 Besides simplifying access to the RTL, a major use of search paths is
7623 in compiling sources from multiple directories. This can make
7624 development environments much more flexible.
7625
7626 @node Examples of gnatbind Usage
7627 @section Examples of @code{gnatbind} Usage
7628
7629 @noindent
7630 This section contains a number of examples of using the GNAT binding
7631 utility @code{gnatbind}.
7632
7633 @table @code
7634 @item gnatbind hello
7635 The main program @code{Hello} (source program in @file{hello.adb}) is
7636 bound using the standard switch settings. The generated main program is
7637 @file{b~hello.adb}. This is the normal, default use of the binder.
7638
7639 @ifclear vms
7640 @item gnatbind hello -o mainprog.adb
7641 @end ifclear
7642 @ifset vms
7643 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7644 @end ifset
7645 The main program @code{Hello} (source program in @file{hello.adb}) is
7646 bound using the standard switch settings. The generated main program is
7647 @file{mainprog.adb} with the associated spec in
7648 @file{mainprog.ads}. Note that you must specify the body here not the
7649 spec, in the case where the output is in Ada. Note that if this option
7650 is used, then linking must be done manually, since gnatlink will not
7651 be able to find the generated file.
7652
7653 @ifclear vms
7654 @item gnatbind main -C -o mainprog.c -x
7655 @end ifclear
7656 @ifset vms
7657 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7658 @end ifset
7659 The main program @code{Main} (source program in
7660 @file{main.adb}) is bound, excluding source files from the
7661 consistency checking, generating
7662 the file @file{mainprog.c}.
7663
7664 @ifclear vms
7665 @item gnatbind -x main_program -C -o mainprog.c
7666 This command is exactly the same as the previous example. Switches may
7667 appear anywhere in the command line, and single letter switches may be
7668 combined into a single switch.
7669 @end ifclear
7670
7671 @ifclear vms
7672 @item gnatbind -n math dbase -C -o ada-control.c
7673 @end ifclear
7674 @ifset vms
7675 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7676 @end ifset
7677 The main program is in a language other than Ada, but calls to
7678 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7679 to @code{gnatbind} generates the file @file{ada-control.c} containing
7680 the @code{adainit} and @code{adafinal} routines to be called before and
7681 after accessing the Ada units.
7682 @end table
7683
7684
7685 @c ------------------------------------
7686 @node Linking Using gnatlink
7687 @chapter Linking Using @code{gnatlink}
7688 @c ------------------------------------
7689 @findex gnatlink
7690
7691 @noindent
7692 This chapter discusses @code{gnatlink}, a tool that links
7693 an Ada program and builds an executable file. This utility
7694 invokes the system linker ^(via the @code{gcc} command)^^
7695 with a correct list of object files and library references.
7696 @code{gnatlink} automatically determines the list of files and
7697 references for the Ada part of a program. It uses the binder file
7698 generated by the @command{gnatbind} to determine this list.
7699
7700 @menu
7701 * Running gnatlink::
7702 * Switches for gnatlink::
7703 * Setting Stack Size from gnatlink::
7704 * Setting Heap Size from gnatlink::
7705 @end menu
7706
7707 @node Running gnatlink
7708 @section Running @code{gnatlink}
7709
7710 @noindent
7711 The form of the @code{gnatlink} command is
7712
7713 @smallexample
7714 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
7715            [@var{non-Ada objects}] [@var{linker options}]
7716 @end smallexample
7717
7718 @noindent
7719 The arguments of @code{gnatlink} (switches, main @file{ALI} file,
7720 non-Ada objects
7721 or linker options) may be in any order, provided that no non-Ada object may
7722 be mistaken for a main @file{ALI} file.
7723 Any file name @file{F} without the @file{.ali}
7724 extension will be taken as the main @file{ALI} file if a file exists
7725 whose name is the concatenation of @file{F} and @file{.ali}.
7726
7727 @noindent
7728 @file{@var{mainprog}.ali} references the ALI file of the main program.
7729 The @file{.ali} extension of this file can be omitted. From this
7730 reference, @code{gnatlink} locates the corresponding binder file
7731 @file{b~@var{mainprog}.adb} and, using the information in this file along
7732 with the list of non-Ada objects and linker options, constructs a
7733 linker command file to create the executable.
7734
7735 The arguments other than the @code{gnatlink} switches and the main @file{ALI}
7736 file are passed to the linker uninterpreted.
7737 They typically include the names of
7738 object files for units written in other languages than Ada and any library
7739 references required to resolve references in any of these foreign language
7740 units, or in @code{Import} pragmas in any Ada units.
7741
7742 @var{linker options} is an optional list of linker specific
7743 switches.
7744 The default linker called by gnatlink is @var{gcc} which in
7745 turn calls the appropriate system linker.
7746 Standard options for the linker such as @option{-lmy_lib} or
7747 @option{-Ldir} can be added as is.
7748 For options that are not recognized by
7749 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7750 @option{-Wl,}.
7751 Refer to the GCC documentation for
7752 details. Here is an example showing how to generate a linker map:
7753
7754 @ifclear vms
7755 @smallexample
7756 $ gnatlink my_prog -Wl,-Map,MAPFILE
7757 @end smallexample
7758 @end ifclear
7759
7760 @ifset vms
7761 <<Need example for VMS>>
7762 @end ifset
7763
7764 Using @var{linker options} it is possible to set the program stack and
7765 heap size. See @ref{Setting Stack Size from gnatlink}, and
7766 @ref{Setting Heap Size from gnatlink}.
7767
7768 @code{gnatlink} determines the list of objects required by the Ada
7769 program and prepends them to the list of objects passed to the linker.
7770 @code{gnatlink} also gathers any arguments set by the use of
7771 @code{pragma Linker_Options} and adds them to the list of arguments
7772 presented to the linker.
7773
7774 @ifset vms
7775 @code{gnatlink} accepts the following types of extra files on the command
7776 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7777 options files (.OPT). These are recognized and handled according to their
7778 extension.
7779 @end ifset
7780
7781 @node Switches for gnatlink
7782 @section Switches for @code{gnatlink}
7783
7784 @noindent
7785 The following switches are available with the @code{gnatlink} utility:
7786
7787 @table @option
7788 @c !sort!
7789
7790 @item ^-A^/BIND_FILE=ADA^
7791 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatlink})
7792 The binder has generated code in Ada. This is the default.
7793
7794 @item ^-C^/BIND_FILE=C^
7795 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatlink})
7796 If instead of generating a file in Ada, the binder has generated one in
7797 C, then the linker needs to know about it. Use this switch to signal
7798 to @code{gnatlink} that the binder has generated C code rather than
7799 Ada code.
7800
7801 @item ^-f^/FORCE_OBJECT_FILE_LIST^
7802 @cindex Command line length
7803 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@code{gnatlink})
7804 On some targets, the command line length is limited, and @code{gnatlink}
7805 will generate a separate file for the linker if the list of object files
7806 is too long.
7807 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
7808 to be generated even if
7809 the limit is not exceeded. This is useful in some cases to deal with
7810 special situations where the command line length is exceeded.
7811
7812 @item ^-g^/DEBUG^
7813 @cindex Debugging information, including
7814 @cindex @option{^-g^/DEBUG^} (@code{gnatlink})
7815 The option to include debugging information causes the Ada bind file (in
7816 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7817 @option{^-g^/DEBUG^}.
7818 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7819 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7820 Without @option{^-g^/DEBUG^}, the binder removes these files by
7821 default. The same procedure apply if a C bind file was generated using
7822 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
7823 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7824
7825 @item ^-n^/NOCOMPILE^
7826 @cindex @option{^-n^/NOCOMPILE^} (@code{gnatlink})
7827 Do not compile the file generated by the binder. This may be used when
7828 a link is rerun with different options, but there is no need to recompile
7829 the binder file.
7830
7831 @item ^-v^/VERBOSE^
7832 @cindex @option{^-v^/VERBOSE^} (@code{gnatlink})
7833 Causes additional information to be output, including a full list of the
7834 included object files. This switch option is most useful when you want
7835 to see what set of object files are being used in the link step.
7836
7837 @item ^-v -v^/VERBOSE/VERBOSE^
7838 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@code{gnatlink})
7839 Very verbose mode. Requests that the compiler operate in verbose mode when
7840 it compiles the binder file, and that the system linker run in verbose mode.
7841
7842 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7843 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatlink})
7844 @var{exec-name} specifies an alternate name for the generated
7845 executable program. If this switch is omitted, the executable has the same
7846 name as the main unit. For example, @code{gnatlink try.ali} creates
7847 an executable called @file{^try^TRY.EXE^}.
7848
7849 @ifclear vms
7850 @item -b @var{target}
7851 @cindex @option{-b} (@code{gnatlink})
7852 Compile your program to run on @var{target}, which is the name of a
7853 system configuration. You must have a GNAT cross-compiler built if
7854 @var{target} is not the same as your host system.
7855
7856 @item -B@var{dir}
7857 @cindex @option{-B} (@code{gnatlink})
7858 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7859 from @var{dir} instead of the default location. Only use this switch
7860 when multiple versions of the GNAT compiler are available. See the
7861 @code{gcc} manual page for further details. You would normally use the
7862 @option{-b} or @option{-V} switch instead.
7863
7864 @item --GCC=@var{compiler_name}
7865 @cindex @option{--GCC=compiler_name} (@code{gnatlink})
7866 Program used for compiling the binder file. The default is
7867 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
7868 @code{compiler_name} contains spaces or other separator characters. As
7869 an example @option{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
7870 @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
7871 inserted after your command name. Thus in the above example the compiler
7872 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
7873 If several @option{--GCC=compiler_name} are used, only the last
7874 @var{compiler_name} is taken into account. However, all the additional
7875 switches are also taken into account. Thus,
7876 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7877 @option{--GCC="bar -x -y -z -t"}.
7878
7879 @item --LINK=@var{name}
7880 @cindex @option{--LINK=} (@code{gnatlink})
7881 @var{name} is the name of the linker to be invoked. This is especially
7882 useful in mixed language programs since languages such as C++ require
7883 their own linker to be used. When this switch is omitted, the default
7884 name for the linker is (@file{gcc}). When this switch is used, the
7885 specified linker is called instead of (@file{gcc}) with exactly the same
7886 parameters that would have been passed to (@file{gcc}) so if the desired
7887 linker requires different parameters it is necessary to use a wrapper
7888 script that massages the parameters before invoking the real linker. It
7889 may be useful to control the exact invocation by using the verbose
7890 switch.
7891
7892 @end ifclear
7893
7894 @ifset vms
7895 @item /DEBUG=TRACEBACK
7896 @cindex @code{/DEBUG=TRACEBACK} (@code{gnatlink})
7897 This qualifier causes sufficient information to be included in the
7898 executable file to allow a traceback, but does not include the full
7899 symbol information needed by the debugger.
7900
7901 @item /IDENTIFICATION="<string>"
7902 @code{"<string>"} specifies the string to be stored in the image file
7903 identification field in the image header.
7904 It overrides any pragma @code{Ident} specified string.
7905
7906 @item /NOINHIBIT-EXEC
7907 Generate the executable file even if there are linker warnings.
7908
7909 @item /NOSTART_FILES
7910 Don't link in the object file containing the ``main'' transfer address.
7911 Used when linking with a foreign language main program compiled with a
7912 Digital compiler.
7913
7914 @item /STATIC
7915 Prefer linking with object libraries over sharable images, even without
7916 /DEBUG.
7917 @end ifset
7918
7919 @end table
7920
7921 @node Setting Stack Size from gnatlink
7922 @section Setting Stack Size from @code{gnatlink}
7923
7924 @noindent
7925 Under Windows systems, it is possible to specify the program stack size from
7926 @code{gnatlink} using either:
7927
7928 @itemize @bullet
7929
7930 @item using @option{-Xlinker} linker option
7931
7932 @smallexample
7933 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
7934 @end smallexample
7935
7936 This sets the stack reserve size to 0x10000 bytes and the stack commit
7937 size to 0x1000 bytes.
7938
7939 @item using @option{-Wl} linker option
7940
7941 @smallexample
7942 $ gnatlink hello -Wl,--stack=0x1000000
7943 @end smallexample
7944
7945 This sets the stack reserve size to 0x1000000 bytes. Note that with
7946 @option{-Wl} option it is not possible to set the stack commit size
7947 because the coma is a separator for this option.
7948
7949 @end itemize
7950
7951 @node Setting Heap Size from gnatlink
7952 @section Setting Heap Size from @code{gnatlink}
7953
7954 @noindent
7955 Under Windows systems, it is possible to specify the program heap size from
7956 @code{gnatlink} using either:
7957
7958 @itemize @bullet
7959
7960 @item using @option{-Xlinker} linker option
7961
7962 @smallexample
7963 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
7964 @end smallexample
7965
7966 This sets the heap reserve size to 0x10000 bytes and the heap commit
7967 size to 0x1000 bytes.
7968
7969 @item using @option{-Wl} linker option
7970
7971 @smallexample
7972 $ gnatlink hello -Wl,--heap=0x1000000
7973 @end smallexample
7974
7975 This sets the heap reserve size to 0x1000000 bytes. Note that with
7976 @option{-Wl} option it is not possible to set the heap commit size
7977 because the coma is a separator for this option.
7978
7979 @end itemize
7980
7981 @node The GNAT Make Program gnatmake
7982 @chapter The GNAT Make Program @code{gnatmake}
7983 @findex gnatmake
7984
7985 @menu
7986 * Running gnatmake::
7987 * Switches for gnatmake::
7988 * Mode Switches for gnatmake::
7989 * Notes on the Command Line::
7990 * How gnatmake Works::
7991 * Examples of gnatmake Usage::
7992 @end menu
7993 @noindent
7994 A typical development cycle when working on an Ada program consists of
7995 the following steps:
7996
7997 @enumerate
7998 @item
7999 Edit some sources to fix bugs.
8000
8001 @item
8002 Add enhancements.
8003
8004 @item
8005 Compile all sources affected.
8006
8007 @item
8008 Rebind and relink.
8009
8010 @item
8011 Test.
8012 @end enumerate
8013
8014 @noindent
8015 The third step can be tricky, because not only do the modified files
8016 @cindex Dependency rules
8017 have to be compiled, but any files depending on these files must also be
8018 recompiled. The dependency rules in Ada can be quite complex, especially
8019 in the presence of overloading, @code{use} clauses, generics and inlined
8020 subprograms.
8021
8022 @code{gnatmake} automatically takes care of the third and fourth steps
8023 of this process. It determines which sources need to be compiled,
8024 compiles them, and binds and links the resulting object files.
8025
8026 Unlike some other Ada make programs, the dependencies are always
8027 accurately recomputed from the new sources. The source based approach of
8028 the GNAT compilation model makes this possible. This means that if
8029 changes to the source program cause corresponding changes in
8030 dependencies, they will always be tracked exactly correctly by
8031 @code{gnatmake}.
8032
8033 @node Running gnatmake
8034 @section Running @code{gnatmake}
8035
8036 @noindent
8037 The usual form of the @code{gnatmake} command is
8038
8039 @smallexample
8040 $ gnatmake [@var{switches}] @var{file_name}
8041       [@var{file_names}] [@var{mode_switches}]
8042 @end smallexample
8043
8044 @noindent
8045 The only required argument is one @var{file_name}, which specifies
8046 a compilation unit that is a main program. Several @var{file_names} can be
8047 specified: this will result in several executables being built.
8048 If @code{switches} are present, they can be placed before the first
8049 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8050 If @var{mode_switches} are present, they must always be placed after
8051 the last @var{file_name} and all @code{switches}.
8052
8053 If you are using standard file extensions (.adb and .ads), then the
8054 extension may be omitted from the @var{file_name} arguments. However, if
8055 you are using non-standard extensions, then it is required that the
8056 extension be given. A relative or absolute directory path can be
8057 specified in a @var{file_name}, in which case, the input source file will
8058 be searched for in the specified directory only. Otherwise, the input
8059 source file will first be searched in the directory where
8060 @code{gnatmake} was invoked and if it is not found, it will be search on
8061 the source path of the compiler as described in
8062 @ref{Search Paths and the Run-Time Library (RTL)}.
8063
8064 All @code{gnatmake} output (except when you specify
8065 @option{^-M^/DEPENDENCIES_LIST^}) is to
8066 @file{stderr}. The output produced by the
8067 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8068 @file{stdout}.
8069
8070 @node Switches for gnatmake
8071 @section Switches for @code{gnatmake}
8072
8073 @noindent
8074 You may specify any of the following switches to @code{gnatmake}:
8075
8076 @table @option
8077 @c !sort!
8078 @ifclear vms
8079 @item --GCC=@var{compiler_name}
8080 @cindex @option{--GCC=compiler_name} (@code{gnatmake})
8081 Program used for compiling. The default is `@code{gcc}'. You need to use
8082 quotes around @var{compiler_name} if @code{compiler_name} contains
8083 spaces or other separator characters. As an example @option{--GCC="foo -x
8084 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
8085 compiler. Note that switch @option{-c} is always inserted after your
8086 command name. Thus in the above example the compiler command that will
8087 be used by @code{gnatmake} will be @code{foo -c -x -y}.
8088 If several @option{--GCC=compiler_name} are used, only the last
8089 @var{compiler_name} is taken into account. However, all the additional
8090 switches are also taken into account. Thus,
8091 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8092 @option{--GCC="bar -x -y -z -t"}.
8093
8094 @item --GNATBIND=@var{binder_name}
8095 @cindex @option{--GNATBIND=binder_name} (@code{gnatmake})
8096 Program used for binding. The default is `@code{gnatbind}'. You need to
8097 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8098 or other separator characters. As an example @option{--GNATBIND="bar -x
8099 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
8100 binder. Binder switches that are normally appended by @code{gnatmake} to
8101 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8102
8103 @item --GNATLINK=@var{linker_name}
8104 @cindex @option{--GNATLINK=linker_name} (@code{gnatmake})
8105 Program used for linking. The default is `@code{gnatlink}'. You need to
8106 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8107 or other separator characters. As an example @option{--GNATLINK="lan -x
8108 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
8109 linker. Linker switches that are normally appended by @code{gnatmake} to
8110 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
8111
8112 @end ifclear
8113
8114 @item ^-a^/ALL_FILES^
8115 @cindex @option{^-a^/ALL_FILES^} (@code{gnatmake})
8116 Consider all files in the make process, even the GNAT internal system
8117 files (for example, the predefined Ada library files), as well as any
8118 locked files. Locked files are files whose ALI file is write-protected.
8119 By default,
8120 @code{gnatmake} does not check these files,
8121 because the assumption is that the GNAT internal files are properly up
8122 to date, and also that any write protected ALI files have been properly
8123 installed. Note that if there is an installation problem, such that one
8124 of these files is not up to date, it will be properly caught by the
8125 binder.
8126 You may have to specify this switch if you are working on GNAT
8127 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8128 in conjunction with @option{^-f^/FORCE_COMPILE^}
8129 if you need to recompile an entire application,
8130 including run-time files, using special configuration pragmas,
8131 such as a @code{Normalize_Scalars} pragma.
8132
8133 By default
8134 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8135 internal files with
8136 @ifclear vms
8137 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8138 @end ifclear
8139 @ifset vms
8140 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8141 @end ifset
8142
8143 @item ^-b^/ACTIONS=BIND^
8144 @cindex @option{^-b^/ACTIONS=BIND^} (@code{gnatmake})
8145 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8146 compilation and binding, but no link.
8147 Can be combined with @option{^-l^/ACTIONS=LINK^}
8148 to do binding and linking. When not combined with
8149 @option{^-c^/ACTIONS=COMPILE^}
8150 all the units in the closure of the main program must have been previously
8151 compiled and must be up to date. The root unit specified by @var{file_name}
8152 may be given without extension, with the source extension or, if no GNAT
8153 Project File is specified, with the ALI file extension.
8154
8155 @item ^-c^/ACTIONS=COMPILE^
8156 @cindex @option{^-c^/ACTIONS=COMPILE^} (@code{gnatmake})
8157 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8158 is also specified. Do not perform linking, except if both
8159 @option{^-b^/ACTIONS=BIND^} and
8160  @option{^-l^/ACTIONS=LINK^} are also specified.
8161 If the root unit specified by @var{file_name} is not a main unit, this is the
8162 default. Otherwise @code{gnatmake} will attempt binding and linking
8163 unless all objects are up to date and the executable is more recent than
8164 the objects.
8165
8166 @item ^-C^/MAPPING^
8167 @cindex @option{^-C^/MAPPING^} (@code{gnatmake})
8168 Use a temporary mapping file. A mapping file is a way to communicate to the
8169 compiler two mappings: from unit names to file names (without any directory
8170 information) and from file names to path names (with full directory
8171 information). These mappings are used by the compiler to short-circuit the path
8172 search. When @code{gnatmake} is invoked with this switch, it will create
8173 a temporary mapping file, initially populated by the project manager,
8174 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8175 Each invocation of the compiler will add the newly accessed sources to the
8176 mapping file. This will improve the source search during the next invocation
8177 of the compiler.
8178
8179 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8180 @cindex @option{^-C=^/USE_MAPPING^} (@code{gnatmake})
8181 Use a specific mapping file. The file, specified as a path name (absolute or
8182 relative) by this switch, should already exist, otherwise the switch is
8183 ineffective. The specified mapping file will be communicated to the compiler.
8184 This switch is not compatible with a project file
8185 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8186 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8187
8188 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8189 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatmake})
8190 Put all object files and ALI file in directory @var{dir}.
8191 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8192 and ALI files go in the current working directory.
8193
8194 This switch cannot be used when using a project file.
8195
8196 @ifclear vms
8197 @item -eL
8198 @cindex @option{-eL} (@code{gnatmake})
8199 Follow all symbolic links when processing project files.
8200 @end ifclear
8201
8202 @item ^-f^/FORCE_COMPILE^
8203 @cindex @option{^-f^/FORCE_COMPILE^} (@code{gnatmake})
8204 Force recompilations. Recompile all sources, even though some object
8205 files may be up to date, but don't recompile predefined or GNAT internal
8206 files or locked files (files with a write-protected ALI file),
8207 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8208
8209 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8210 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatmake})
8211 When using project files, if some errors or warnings are detected during
8212 parsing and verbose mode is not in effect (no use of switch
8213 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8214 file, rather than its simple file name.
8215
8216 @item ^-i^/IN_PLACE^
8217 @cindex @option{^-i^/IN_PLACE^} (@code{gnatmake})
8218 In normal mode, @code{gnatmake} compiles all object files and ALI files
8219 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8220 then instead object files and ALI files that already exist are overwritten
8221 in place. This means that once a large project is organized into separate
8222 directories in the desired manner, then @code{gnatmake} will automatically
8223 maintain and update this organization. If no ALI files are found on the
8224 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8225 the new object and ALI files are created in the
8226 directory containing the source being compiled. If another organization
8227 is desired, where objects and sources are kept in different directories,
8228 a useful technique is to create dummy ALI files in the desired directories.
8229 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
8230 the corresponding source file, and it will be put the resulting object
8231 and ALI files in the directory where it found the dummy file.
8232
8233 @item ^-j^/PROCESSES=^@var{n}
8234 @cindex @option{^-j^/PROCESSES^} (@code{gnatmake})
8235 @cindex Parallel make
8236 Use @var{n} processes to carry out the (re)compilations. On a
8237 multiprocessor machine compilations will occur in parallel. In the
8238 event of compilation errors, messages from various compilations might
8239 get interspersed (but @code{gnatmake} will give you the full ordered
8240 list of failing compiles at the end). If this is problematic, rerun
8241 the make process with n set to 1 to get a clean list of messages.
8242
8243 @item ^-k^/CONTINUE_ON_ERROR^
8244 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@code{gnatmake})
8245 Keep going. Continue as much as possible after a compilation error. To
8246 ease the programmer's task in case of compilation errors, the list of
8247 sources for which the compile fails is given when @code{gnatmake}
8248 terminates.
8249
8250 If @code{gnatmake} is invoked with several @file{file_names} and with this
8251 switch, if there are compilation errors when building an executable,
8252 @code{gnatmake} will not attempt to build the following executables.
8253
8254 @item ^-l^/ACTIONS=LINK^
8255 @cindex @option{^-l^/ACTIONS=LINK^} (@code{gnatmake})
8256 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8257 and linking. Linking will not be performed if combined with
8258 @option{^-c^/ACTIONS=COMPILE^}
8259 but not with @option{^-b^/ACTIONS=BIND^}.
8260 When not combined with @option{^-b^/ACTIONS=BIND^}
8261 all the units in the closure of the main program must have been previously
8262 compiled and must be up to date, and the main program need to have been bound.
8263 The root unit specified by @var{file_name}
8264 may be given without extension, with the source extension or, if no GNAT
8265 Project File is specified, with the ALI file extension.
8266
8267 @item ^-m^/MINIMAL_RECOMPILATION^
8268 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@code{gnatmake})
8269 Specifies that the minimum necessary amount of recompilations
8270 be performed. In this mode @code{gnatmake} ignores time
8271 stamp differences when the only
8272 modifications to a source file consist in adding/removing comments,
8273 empty lines, spaces or tabs. This means that if you have changed the
8274 comments in a source file or have simply reformatted it, using this
8275 switch will tell gnatmake not to recompile files that depend on it
8276 (provided other sources on which these files depend have undergone no
8277 semantic modifications). Note that the debugging information may be
8278 out of date with respect to the sources if the @option{-m} switch causes
8279 a compilation to be switched, so the use of this switch represents a
8280 trade-off between compilation time and accurate debugging information.
8281
8282 @item ^-M^/DEPENDENCIES_LIST^
8283 @cindex Dependencies, producing list
8284 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@code{gnatmake})
8285 Check if all objects are up to date. If they are, output the object
8286 dependences to @file{stdout} in a form that can be directly exploited in
8287 a @file{Makefile}. By default, each source file is prefixed with its
8288 (relative or absolute) directory name. This name is whatever you
8289 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8290 and @option{^-I^/SEARCH^} switches. If you use
8291 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8292 @option{^-q^/QUIET^}
8293 (see below), only the source file names,
8294 without relative paths, are output. If you just specify the
8295 @option{^-M^/DEPENDENCIES_LIST^}
8296 switch, dependencies of the GNAT internal system files are omitted. This
8297 is typically what you want. If you also specify
8298 the @option{^-a^/ALL_FILES^} switch,
8299 dependencies of the GNAT internal files are also listed. Note that
8300 dependencies of the objects in external Ada libraries (see switch
8301 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8302 are never reported.
8303
8304 @item ^-n^/DO_OBJECT_CHECK^
8305 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@code{gnatmake})
8306 Don't compile, bind, or link. Checks if all objects are up to date.
8307 If they are not, the full name of the first file that needs to be
8308 recompiled is printed.
8309 Repeated use of this option, followed by compiling the indicated source
8310 file, will eventually result in recompiling all required units.
8311
8312 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8313 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatmake})
8314 Output executable name. The name of the final executable program will be
8315 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8316 name for the executable will be the name of the input file in appropriate form
8317 for an executable file on the host system.
8318
8319 This switch cannot be used when invoking @code{gnatmake} with several
8320 @file{file_names}.
8321
8322 @item ^-P^/PROJECT_FILE=^@var{project}
8323 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatmake})
8324 Use project file @var{project}. Only one such switch can be used.
8325 See @ref{gnatmake and Project Files}.
8326
8327 @item ^-q^/QUIET^
8328 @cindex @option{^-q^/QUIET^} (@code{gnatmake})
8329 Quiet. When this flag is not set, the commands carried out by
8330 @code{gnatmake} are displayed.
8331
8332 @item ^-s^/SWITCH_CHECK/^
8333 @cindex @option{^-s^/SWITCH_CHECK^} (@code{gnatmake})
8334 Recompile if compiler switches have changed since last compilation.
8335 All compiler switches but -I and -o are taken into account in the
8336 following way:
8337 orders between different ``first letter'' switches are ignored, but
8338 orders between same switches are taken into account. For example,
8339 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8340 is equivalent to @option{-O -g}.
8341
8342 This switch is recommended when Integrated Preprocessing is used.
8343
8344 @item ^-u^/UNIQUE^
8345 @cindex @option{^-u^/UNIQUE^} (@code{gnatmake})
8346 Unique. Recompile at most the main files. It implies -c. Combined with
8347 -f, it is equivalent to calling the compiler directly. Note that using
8348 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8349 (see @ref{Project Files and Main Subprograms}).
8350
8351 @item ^-U^/ALL_PROJECTS^
8352 @cindex @option{^-U^/ALL_PROJECTS^} (@code{gnatmake})
8353 When used without a project file or with one or several mains on the command
8354 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8355 on the command line, all sources of all project files are checked and compiled
8356 if not up to date, and libraries are rebuilt, if necessary.
8357
8358 @item ^-v^/REASONS^
8359 @cindex @option{^-v^/REASONS^} (@code{gnatmake})
8360 Verbose. Displays the reason for all recompilations @code{gnatmake}
8361 decides are necessary.
8362
8363 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8364 Indicates the verbosity of the parsing of GNAT project files.
8365 See @ref{Switches Related to Project Files}.
8366
8367 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8368 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@code{gnatmake})
8369 Indicates that sources that are not part of any Project File may be compiled.
8370 Normally, when using Project Files, only sources that are part of a Project
8371 File may be compile. When this switch is used, a source outside of all Project
8372 Files may be compiled. The ALI file and the object file will be put in the
8373 object directory of the main Project. The compilation switches used will only
8374 be those specified on the command line.
8375
8376 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8377 Indicates that external variable @var{name} has the value @var{value}.
8378 The Project Manager will use this value for occurrences of
8379 @code{external(name)} when parsing the project file.
8380 See @ref{Switches Related to Project Files}.
8381
8382 @item ^-z^/NOMAIN^
8383 @cindex @option{^-z^/NOMAIN^} (@code{gnatmake})
8384 No main subprogram. Bind and link the program even if the unit name
8385 given on the command line is a package name. The resulting executable
8386 will execute the elaboration routines of the package and its closure,
8387 then the finalization routines.
8388
8389 @item ^-g^/DEBUG^
8390 @cindex @option{^-g^/DEBUG^} (@code{gnatmake})
8391 Enable debugging. This switch is simply passed to the compiler and to the
8392 linker.
8393
8394 @end table
8395
8396 @table @asis
8397 @item @code{gcc} @asis{switches}
8398 @ifclear vms
8399 Any uppercase or multi-character switch that is not a @code{gnatmake} switch
8400 is passed to @code{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8401 @end ifclear
8402 @ifset vms
8403 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8404 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8405 automatically treated as a compiler switch, and passed on to all
8406 compilations that are carried out.
8407 @end ifset
8408 @end table
8409
8410 @noindent
8411 Source and library search path switches:
8412
8413 @table @option
8414 @c !sort!
8415 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8416 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatmake})
8417 When looking for source files also look in directory @var{dir}.
8418 The order in which source files search is undertaken is
8419 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8420
8421 @item ^-aL^/SKIP_MISSING=^@var{dir}
8422 @cindex @option{^-aL^/SKIP_MISSING^} (@code{gnatmake})
8423 Consider @var{dir} as being an externally provided Ada library.
8424 Instructs @code{gnatmake} to skip compilation units whose @file{.ALI}
8425 files have been located in directory @var{dir}. This allows you to have
8426 missing bodies for the units in @var{dir} and to ignore out of date bodies
8427 for the same units. You still need to specify
8428 the location of the specs for these units by using the switches
8429 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8430 or @option{^-I^/SEARCH=^@var{dir}}.
8431 Note: this switch is provided for compatibility with previous versions
8432 of @code{gnatmake}. The easier method of causing standard libraries
8433 to be excluded from consideration is to write-protect the corresponding
8434 ALI files.
8435
8436 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8437 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatmake})
8438 When searching for library and object files, look in directory
8439 @var{dir}. The order in which library files are searched is described in
8440 @ref{Search Paths for gnatbind}.
8441
8442 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8443 @cindex Search paths, for @code{gnatmake}
8444 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@code{gnatmake})
8445 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8446 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8447
8448 @item ^-I^/SEARCH=^@var{dir}
8449 @cindex @option{^-I^/SEARCH^} (@code{gnatmake})
8450 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8451 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8452
8453 @item ^-I-^/NOCURRENT_DIRECTORY^
8454 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatmake})
8455 @cindex Source files, suppressing search
8456 Do not look for source files in the directory containing the source
8457 file named in the command line.
8458 Do not look for ALI or object files in the directory
8459 where @code{gnatmake} was invoked.
8460
8461 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8462 @cindex @option{^-L^/LIBRARY_SEARCH^} (@code{gnatmake})
8463 @cindex Linker libraries
8464 Add directory @var{dir} to the list of directories in which the linker
8465 will search for libraries. This is equivalent to
8466 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8467 @ifclear vms
8468 Furthermore, under Windows, the sources pointed to by the libraries path
8469 set in the registry are not searched for.
8470 @end ifclear
8471
8472 @item -nostdinc
8473 @cindex @option{-nostdinc} (@code{gnatmake})
8474 Do not look for source files in the system default directory.
8475
8476 @item -nostdlib
8477 @cindex @option{-nostdlib} (@code{gnatmake})
8478 Do not look for library files in the system default directory.
8479
8480 @item --RTS=@var{rts-path}
8481 @cindex @option{--RTS} (@code{gnatmake})
8482 Specifies the default location of the runtime library. GNAT looks for the
8483 runtime
8484 in the following directories, and stops as soon as a valid runtime is found
8485 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8486 @file{ada_object_path} present):
8487
8488 @itemize @bullet
8489 @item <current directory>/$rts_path
8490
8491 @item <default-search-dir>/$rts_path
8492
8493 @item <default-search-dir>/rts-$rts_path
8494 @end itemize
8495
8496 @noindent
8497 The selected path is handled like a normal RTS path.
8498
8499 @end table
8500
8501 @node Mode Switches for gnatmake
8502 @section Mode Switches for @code{gnatmake}
8503
8504 @noindent
8505 The mode switches (referred to as @code{mode_switches}) allow the
8506 inclusion of switches that are to be passed to the compiler itself, the
8507 binder or the linker. The effect of a mode switch is to cause all
8508 subsequent switches up to the end of the switch list, or up to the next
8509 mode switch, to be interpreted as switches to be passed on to the
8510 designated component of GNAT.
8511
8512 @table @option
8513 @c !sort!
8514 @item -cargs @var{switches}
8515 @cindex @option{-cargs} (@code{gnatmake})
8516 Compiler switches. Here @var{switches} is a list of switches
8517 that are valid switches for @code{gcc}. They will be passed on to
8518 all compile steps performed by @code{gnatmake}.
8519
8520 @item -bargs @var{switches}
8521 @cindex @option{-bargs} (@code{gnatmake})
8522 Binder switches. Here @var{switches} is a list of switches
8523 that are valid switches for @code{gnatbind}. They will be passed on to
8524 all bind steps performed by @code{gnatmake}.
8525
8526 @item -largs @var{switches}
8527 @cindex @option{-largs} (@code{gnatmake})
8528 Linker switches. Here @var{switches} is a list of switches
8529 that are valid switches for @code{gnatlink}. They will be passed on to
8530 all link steps performed by @code{gnatmake}.
8531
8532 @item -margs @var{switches}
8533 @cindex @option{-margs} (@code{gnatmake})
8534 Make switches. The switches are directly interpreted by @code{gnatmake},
8535 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8536 or @option{-largs}.
8537 @end table
8538
8539 @node Notes on the Command Line
8540 @section Notes on the Command Line
8541
8542 @noindent
8543 This section contains some additional useful notes on the operation
8544 of the @code{gnatmake} command.
8545
8546 @itemize @bullet
8547 @item
8548 @cindex Recompilation, by @code{gnatmake}
8549 If @code{gnatmake} finds no ALI files, it recompiles the main program
8550 and all other units required by the main program.
8551 This means that @code{gnatmake}
8552 can be used for the initial compile, as well as during subsequent steps of
8553 the development cycle.
8554
8555 @item
8556 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8557 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8558 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8559 warning.
8560
8561 @item
8562 In @code{gnatmake} the switch @option{^-I^/SEARCH^}
8563 is used to specify both source and
8564 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8565 instead if you just want to specify
8566 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8567 if you want to specify library paths
8568 only.
8569
8570 @item
8571 @code{gnatmake} examines both an ALI file and its corresponding object file
8572 for consistency. If an ALI is more recent than its corresponding object,
8573 or if the object file is missing, the corresponding source will be recompiled.
8574 Note that @code{gnatmake} expects an ALI and the corresponding object file
8575 to be in the same directory.
8576
8577 @item
8578 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8579 This may conveniently be used to exclude standard libraries from
8580 consideration and in particular it means that the use of the
8581 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8582 unless @option{^-a^/ALL_FILES^} is also specified.
8583
8584 @item
8585 @code{gnatmake} has been designed to make the use of Ada libraries
8586 particularly convenient. Assume you have an Ada library organized
8587 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8588 of your Ada compilation units,
8589 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8590 specs of these units, but no bodies. Then to compile a unit
8591 stored in @code{main.adb}, which uses this Ada library you would just type
8592
8593 @smallexample
8594 @ifclear vms
8595 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8596 @end ifclear
8597 @ifset vms
8598 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8599            /SKIP_MISSING=@i{[OBJ_DIR]} main
8600 @end ifset
8601 @end smallexample
8602
8603 @item
8604 Using @code{gnatmake} along with the
8605 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8606 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8607 this switch,
8608 you can update the comments/format of your
8609 source files without having to recompile everything. Note, however, that
8610 adding or deleting lines in a source files may render its debugging
8611 info obsolete. If the file in question is a spec, the impact is rather
8612 limited, as that debugging info will only be useful during the
8613 elaboration phase of your program. For bodies the impact can be more
8614 significant. In all events, your debugger will warn you if a source file
8615 is more recent than the corresponding object, and alert you to the fact
8616 that the debugging information may be out of date.
8617 @end itemize
8618
8619 @node How gnatmake Works
8620 @section How @code{gnatmake} Works
8621
8622 @noindent
8623 Generally @code{gnatmake} automatically performs all necessary
8624 recompilations and you don't need to worry about how it works. However,
8625 it may be useful to have some basic understanding of the @code{gnatmake}
8626 approach and in particular to understand how it uses the results of
8627 previous compilations without incorrectly depending on them.
8628
8629 First a definition: an object file is considered @dfn{up to date} if the
8630 corresponding ALI file exists and its time stamp predates that of the
8631 object file and if all the source files listed in the
8632 dependency section of this ALI file have time stamps matching those in
8633 the ALI file. This means that neither the source file itself nor any
8634 files that it depends on have been modified, and hence there is no need
8635 to recompile this file.
8636
8637 @code{gnatmake} works by first checking if the specified main unit is up
8638 to date. If so, no compilations are required for the main unit. If not,
8639 @code{gnatmake} compiles the main program to build a new ALI file that
8640 reflects the latest sources. Then the ALI file of the main unit is
8641 examined to find all the source files on which the main program depends,
8642 and @code{gnatmake} recursively applies the above procedure on all these files.
8643
8644 This process ensures that @code{gnatmake} only trusts the dependencies
8645 in an existing ALI file if they are known to be correct. Otherwise it
8646 always recompiles to determine a new, guaranteed accurate set of
8647 dependencies. As a result the program is compiled ``upside down'' from what may
8648 be more familiar as the required order of compilation in some other Ada
8649 systems. In particular, clients are compiled before the units on which
8650 they depend. The ability of GNAT to compile in any order is critical in
8651 allowing an order of compilation to be chosen that guarantees that
8652 @code{gnatmake} will recompute a correct set of new dependencies if
8653 necessary.
8654
8655 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
8656 imported by several of the executables, it will be recompiled at most once.
8657
8658 Note: when using non-standard naming conventions
8659 (See @ref{Using Other File Names}), changing through a configuration pragmas
8660 file the version of a source and invoking @code{gnatmake} to recompile may
8661 have no effect, if the previous version of the source is still accessible
8662 by @code{gnatmake}. It may be necessary to use the switch ^-f^/FORCE_COMPILE^.
8663
8664 @node Examples of gnatmake Usage
8665 @section Examples of @code{gnatmake} Usage
8666
8667 @table @code
8668 @item gnatmake hello.adb
8669 Compile all files necessary to bind and link the main program
8670 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8671 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8672
8673 @item gnatmake main1 main2 main3
8674 Compile all files necessary to bind and link the main programs
8675 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8676 (containing unit @code{Main2}) and @file{main3.adb}
8677 (containing unit @code{Main3}) and bind and link the resulting object files
8678 to generate three executable files @file{^main1^MAIN1.EXE^},
8679 @file{^main2^MAIN2.EXE^}
8680 and @file{^main3^MAIN3.EXE^}.
8681
8682 @ifclear vms
8683 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8684 @end ifclear
8685
8686 @ifset vms
8687 @item gnatmake Main_Unit /QUIET
8688    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8689    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8690 @end ifset
8691 Compile all files necessary to bind and link the main program unit
8692 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8693 be done with optimization level 2 and the order of elaboration will be
8694 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8695 displaying commands it is executing.
8696 @end table
8697
8698
8699 @c *************************
8700 @node Improving Performance
8701 @chapter Improving Performance
8702 @cindex Improving performance
8703
8704 @noindent
8705 This chapter presents several topics related to program performance.
8706 It first describes some of the tradeoffs that need to be considered
8707 and some of the techniques for making your program run faster.
8708 It then documents the @command{gnatelim} tool, which can reduce
8709 the size of program executables.
8710
8711 @ifnottex
8712 @menu
8713 * Performance Considerations::
8714 * Reducing the Size of Ada Executables with gnatelim::
8715 @end menu
8716 @end ifnottex
8717
8718
8719 @c *****************************
8720 @node Performance Considerations
8721 @section Performance Considerations
8722
8723 @noindent
8724 The GNAT system provides a number of options that allow a trade-off
8725 between
8726
8727 @itemize @bullet
8728 @item
8729 performance of the generated code
8730
8731 @item
8732 speed of compilation
8733
8734 @item
8735 minimization of dependences and recompilation
8736
8737 @item
8738 the degree of run-time checking.
8739 @end itemize
8740
8741 @noindent
8742 The defaults (if no options are selected) aim at improving the speed
8743 of compilation and minimizing dependences, at the expense of performance
8744 of the generated code:
8745
8746 @itemize @bullet
8747 @item
8748 no optimization
8749
8750 @item
8751 no inlining of subprogram calls
8752
8753 @item
8754 all run-time checks enabled except overflow and elaboration checks
8755 @end itemize
8756
8757 @noindent
8758 These options are suitable for most program development purposes. This
8759 chapter describes how you can modify these choices, and also provides
8760 some guidelines on debugging optimized code.
8761
8762 @menu
8763 * Controlling Run-Time Checks::
8764 * Use of Restrictions::
8765 * Optimization Levels::
8766 * Debugging Optimized Code::
8767 * Inlining of Subprograms::
8768 * Optimization and Strict Aliasing::
8769 @ifset vms
8770 * Coverage Analysis::
8771 @end ifset
8772 @end menu
8773
8774 @node Controlling Run-Time Checks
8775 @subsection Controlling Run-Time Checks
8776
8777 @noindent
8778 By default, GNAT generates all run-time checks, except arithmetic overflow
8779 checking for integer operations and checks for access before elaboration on
8780 subprogram calls. The latter are not required in default mode, because all
8781 necessary checking is done at compile time.
8782 @cindex @option{-gnatp} (@code{gcc})
8783 @cindex @option{-gnato} (@code{gcc})
8784 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8785 be modified. @xref{Run-Time Checks}.
8786
8787 Our experience is that the default is suitable for most development
8788 purposes.
8789
8790 We treat integer overflow specially because these
8791 are quite expensive and in our experience are not as important as other
8792 run-time checks in the development process. Note that division by zero
8793 is not considered an overflow check, and divide by zero checks are
8794 generated where required by default.
8795
8796 Elaboration checks are off by default, and also not needed by default, since
8797 GNAT uses a static elaboration analysis approach that avoids the need for
8798 run-time checking. This manual contains a full chapter discussing the issue
8799 of elaboration checks, and if the default is not satisfactory for your use,
8800 you should read this chapter.
8801
8802 For validity checks, the minimal checks required by the Ada Reference
8803 Manual (for case statements and assignments to array elements) are on
8804 by default. These can be suppressed by use of the @option{-gnatVn} switch.
8805 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8806 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8807 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8808 are also suppressed entirely if @option{-gnatp} is used.
8809
8810 @cindex Overflow checks
8811 @cindex Checks, overflow
8812 @findex Suppress
8813 @findex Unsuppress
8814 @cindex pragma Suppress
8815 @cindex pragma Unsuppress
8816 Note that the setting of the switches controls the default setting of
8817 the checks. They may be modified using either @code{pragma Suppress} (to
8818 remove checks) or @code{pragma Unsuppress} (to add back suppressed
8819 checks) in the program source.
8820
8821 @node Use of Restrictions
8822 @subsection Use of Restrictions
8823
8824 @noindent
8825 The use of pragma Restrictions allows you to control which features are
8826 permitted in your program. Apart from the obvious point that if you avoid
8827 relatively expensive features like finalization (enforceable by the use
8828 of pragma Restrictions (No_Finalization), the use of this pragma does not
8829 affect the generated code in most cases.
8830
8831 One notable exception to this rule is that the possibility of task abort
8832 results in some distributed overhead, particularly if finalization or
8833 exception handlers are used. The reason is that certain sections of code
8834 have to be marked as non-abortable.
8835
8836 If you use neither the @code{abort} statement, nor asynchronous transfer
8837 of control (@code{select .. then abort}), then this distributed overhead
8838 is removed, which may have a general positive effect in improving
8839 overall performance.  Especially code involving frequent use of tasking
8840 constructs and controlled types will show much improved performance.
8841 The relevant restrictions pragmas are
8842
8843 @smallexample
8844    pragma Restrictions (No_Abort_Statements);
8845    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
8846 @end smallexample
8847
8848 @noindent
8849 It is recommended that these restriction pragmas be used if possible. Note
8850 that this also means that you can write code without worrying about the
8851 possibility of an immediate abort at any point.
8852
8853 @node Optimization Levels
8854 @subsection Optimization Levels
8855 @cindex @option{^-O^/OPTIMIZE^} (@code{gcc})
8856
8857 @noindent
8858 The default is optimization off. This results in the fastest compile
8859 times, but GNAT makes absolutely no attempt to optimize, and the
8860 generated programs are considerably larger and slower than when
8861 optimization is enabled. You can use the
8862 @ifclear vms
8863 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
8864 @end ifclear
8865 @ifset vms
8866 @code{OPTIMIZE} qualifier
8867 @end ifset
8868 to @code{gcc} to control the optimization level:
8869
8870 @table @option
8871 @item ^-O0^/OPTIMIZE=NONE^
8872 No optimization (the default);
8873 generates unoptimized code but has
8874 the fastest compilation time.
8875
8876 @item ^-O1^/OPTIMIZE=SOME^
8877 Medium level optimization;
8878 optimizes reasonably well but does not
8879 degrade compilation time significantly.
8880
8881 @item ^-O2^/OPTIMIZE=ALL^
8882 @ifset vms
8883 @itemx /OPTIMIZE=DEVELOPMENT
8884 @end ifset
8885 Full optimization;
8886 generates highly optimized code and has
8887 the slowest compilation time.
8888
8889 @item ^-O3^/OPTIMIZE=INLINING^
8890 Full optimization as in @option{-O2},
8891 and also attempts automatic inlining of small
8892 subprograms within a unit (@pxref{Inlining of Subprograms}).
8893 @end table
8894
8895 @noindent
8896 Higher optimization levels perform more global transformations on the
8897 program and apply more expensive analysis algorithms in order to generate
8898 faster and more compact code. The price in compilation time, and the
8899 resulting improvement in execution time,
8900 both depend on the particular application and the hardware environment.
8901 You should experiment to find the best level for your application.
8902
8903 Since the precise set of optimizations done at each level will vary from
8904 release to release (and sometime from target to target), it is best to think
8905 of the optimization settings in general terms.
8906 The @cite{Using GNU GCC} manual contains details about
8907 ^the @option{-O} settings and a number of @option{-f} options that^how to^
8908 individually enable or disable specific optimizations.
8909
8910 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
8911 been tested extensively at all optimization levels. There are some bugs
8912 which appear only with optimization turned on, but there have also been
8913 bugs which show up only in @emph{unoptimized} code. Selecting a lower
8914 level of optimization does not improve the reliability of the code
8915 generator, which in practice is highly reliable at all optimization
8916 levels.
8917
8918 Note regarding the use of @option{-O3}: The use of this optimization level
8919 is generally discouraged with GNAT, since it often results in larger
8920 executables which run more slowly. See further discussion of this point
8921 in @pxref{Inlining of Subprograms}.
8922
8923
8924 @node Debugging Optimized Code
8925 @subsection Debugging Optimized Code
8926 @cindex Debugging optimized code
8927 @cindex Optimization and debugging
8928
8929 @noindent
8930 Although it is possible to do a reasonable amount of debugging at
8931 @ifclear vms
8932 non-zero optimization levels,
8933 the higher the level the more likely that
8934 @end ifclear
8935 @ifset vms
8936 @option{/OPTIMIZE} settings other than @code{NONE},
8937 such settings will make it more likely that
8938 @end ifset
8939 source-level constructs will have been eliminated by optimization.
8940 For example, if a loop is strength-reduced, the loop
8941 control variable may be completely eliminated and thus cannot be
8942 displayed in the debugger.
8943 This can only happen at @option{-O2} or @option{-O3}.
8944 Explicit temporary variables that you code might be eliminated at
8945 ^level^setting^ @option{-O1} or higher.
8946
8947 The use of the @option{^-g^/DEBUG^} switch,
8948 @cindex @option{^-g^/DEBUG^} (@code{gcc})
8949 which is needed for source-level debugging,
8950 affects the size of the program executable on disk,
8951 and indeed the debugging information can be quite large.
8952 However, it has no effect on the generated code (and thus does not
8953 degrade performance)
8954
8955 Since the compiler generates debugging tables for a compilation unit before
8956 it performs optimizations, the optimizing transformations may invalidate some
8957 of the debugging data.  You therefore need to anticipate certain
8958 anomalous situations that may arise while debugging optimized code.
8959 These are the most common cases:
8960
8961 @enumerate
8962 @item
8963 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
8964 commands show
8965 the PC bouncing back and forth in the code.  This may result from any of
8966 the following optimizations:
8967
8968 @itemize @bullet
8969 @item
8970 @i{Common subexpression elimination:} using a single instance of code for a
8971 quantity that the source computes several times.  As a result you
8972 may not be able to stop on what looks like a statement.
8973
8974 @item
8975 @i{Invariant code motion:} moving an expression that does not change within a
8976 loop, to the beginning of the loop.
8977
8978 @item
8979 @i{Instruction scheduling:} moving instructions so as to
8980 overlap loads and stores (typically) with other code, or in
8981 general to move computations of values closer to their uses. Often
8982 this causes you to pass an assignment statement without the assignment
8983 happening and then later bounce back to the statement when the
8984 value is actually needed.  Placing a breakpoint on a line of code
8985 and then stepping over it may, therefore, not always cause all the
8986 expected side-effects.
8987 @end itemize
8988
8989 @item
8990 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
8991 two identical pieces of code are merged and the program counter suddenly
8992 jumps to a statement that is not supposed to be executed, simply because
8993 it (and the code following) translates to the same thing as the code
8994 that @emph{was} supposed to be executed.  This effect is typically seen in
8995 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
8996 a @code{break} in a C @code{^switch^switch^} statement.
8997
8998 @item
8999 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9000 There are various reasons for this effect:
9001
9002 @itemize @bullet
9003 @item
9004 In a subprogram prologue, a parameter may not yet have been moved to its
9005 ``home''.
9006
9007 @item
9008 A variable may be dead, and its register re-used.  This is
9009 probably the most common cause.
9010
9011 @item
9012 As mentioned above, the assignment of a value to a variable may
9013 have been moved.
9014
9015 @item
9016 A variable may be eliminated entirely by value propagation or
9017 other means.  In this case, GCC may incorrectly generate debugging
9018 information for the variable
9019 @end itemize
9020
9021 @noindent
9022 In general, when an unexpected value appears for a local variable or parameter
9023 you should first ascertain if that value was actually computed by
9024 your program, as opposed to being incorrectly reported by the debugger.
9025 Record fields or
9026 array elements in an object designated by an access value
9027 are generally less of a problem, once you have ascertained that the access
9028 value is sensible.
9029 Typically, this means checking variables in the preceding code and in the
9030 calling subprogram to verify that the value observed is explainable from other
9031 values (one must apply the procedure recursively to those
9032 other values); or re-running the code and stopping a little earlier
9033 (perhaps before the call) and stepping to better see how the variable obtained
9034 the value in question; or continuing to step @emph{from} the point of the
9035 strange value to see if code motion had simply moved the variable's
9036 assignments later.
9037 @end enumerate
9038
9039 @noindent
9040 In light of such anomalies, a recommended technique is to use @option{-O0}
9041 early in the software development cycle, when extensive debugging capabilities
9042 are most needed, and then move to @option{-O1} and later @option{-O2} as
9043 the debugger becomes less critical.
9044 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9045 a release management issue.
9046 @ifclear vms
9047 Note that if you use @option{-g} you can then use the @command{strip} program
9048 on the resulting executable,
9049 which removes both debugging information and global symbols.
9050 @end ifclear
9051
9052
9053 @node Inlining of Subprograms
9054 @subsection Inlining of Subprograms
9055
9056 @noindent
9057 A call to a subprogram in the current unit is inlined if all the
9058 following conditions are met:
9059
9060 @itemize @bullet
9061 @item
9062 The optimization level is at least @option{-O1}.
9063
9064 @item
9065 The called subprogram is suitable for inlining: It must be small enough
9066 and not contain nested subprograms or anything else that @code{gcc}
9067 cannot support in inlined subprograms.
9068
9069 @item
9070 The call occurs after the definition of the body of the subprogram.
9071
9072 @item
9073 @cindex pragma Inline
9074 @findex Inline
9075 Either @code{pragma Inline} applies to the subprogram or it is
9076 small and automatic inlining (optimization level @option{-O3}) is
9077 specified.
9078 @end itemize
9079
9080 @noindent
9081 Calls to subprograms in @code{with}'ed units are normally not inlined.
9082 To achieve this level of inlining, the following conditions must all be
9083 true:
9084
9085 @itemize @bullet
9086 @item
9087 The optimization level is at least @option{-O1}.
9088
9089 @item
9090 The called subprogram is suitable for inlining: It must be small enough
9091 and not contain nested subprograms or anything else @code{gcc} cannot
9092 support in inlined subprograms.
9093
9094 @item
9095 The call appears in a body (not in a package spec).
9096
9097 @item
9098 There is a @code{pragma Inline} for the subprogram.
9099
9100 @item
9101 @cindex @option{-gnatn} (@code{gcc})
9102 The @option{^-gnatn^/INLINE^} switch
9103 is used in the @code{gcc} command line
9104 @end itemize
9105
9106 Note that specifying the @option{-gnatn} switch causes additional
9107 compilation dependencies. Consider the following:
9108
9109 @smallexample @c ada
9110 @cartouche
9111 package R is
9112    procedure Q;
9113    pragma Inline (Q);
9114 end R;
9115 package body R is
9116    ...
9117 end R;
9118
9119 with R;
9120 procedure Main is
9121 begin
9122    ...
9123    R.Q;
9124 end Main;
9125 @end cartouche
9126 @end smallexample
9127
9128 @noindent
9129 With the default behavior (no @option{-gnatn} switch specified), the
9130 compilation of the @code{Main} procedure depends only on its own source,
9131 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9132 means that editing the body of @code{R} does not require recompiling
9133 @code{Main}.
9134
9135 On the other hand, the call @code{R.Q} is not inlined under these
9136 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9137 is compiled, the call will be inlined if the body of @code{Q} is small
9138 enough, but now @code{Main} depends on the body of @code{R} in
9139 @file{r.adb} as well as on the spec. This means that if this body is edited,
9140 the main program must be recompiled. Note that this extra dependency
9141 occurs whether or not the call is in fact inlined by @code{gcc}.
9142
9143 The use of front end inlining with @option{-gnatN} generates similar
9144 additional dependencies.
9145
9146 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@code{gcc})
9147 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9148 can be used to prevent
9149 all inlining. This switch overrides all other conditions and ensures
9150 that no inlining occurs. The extra dependences resulting from
9151 @option{-gnatn} will still be active, even if
9152 this switch is used to suppress the resulting inlining actions.
9153
9154 Note regarding the use of @option{-O3}: There is no difference in inlining
9155 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9156 pragma @code{Inline} assuming the use of @option{-gnatn}
9157 or @option{-gnatN} (the switches that activate inlining). If you have used
9158 pragma @code{Inline} in appropriate cases, then it is usually much better
9159 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9160 in this case only has the effect of inlining subprograms you did not
9161 think should be inlined. We often find that the use of @option{-O3} slows
9162 down code by performing excessive inlining, leading to increased instruction
9163 cache pressure from the increased code size. So the bottom line here is
9164 that you should not automatically assume that @option{-O3} is better than
9165 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9166 it actually improves performance.
9167
9168 @node Optimization and Strict Aliasing
9169 @subsection Optimization and Strict Aliasing
9170 @cindex Aliasing
9171 @cindex Strict Aliasing
9172 @cindex No_Strict_Aliasing
9173
9174 @noindent
9175 The strong typing capabilities of Ada allow an optimizer to generate
9176 efficient code in situations where other languages would be forced to
9177 make worst case assumptions preventing such optimizations. Consider
9178 the following example:
9179
9180 @smallexample @c ada
9181 @cartouche
9182 procedure R is
9183    type Int1 is new Integer;
9184    type Int2 is new Integer;
9185    type Int1A is access Int1;
9186    type Int2A is access Int2;
9187    Int1V : Int1A;
9188    Int2V : Int2A;
9189    ...
9190
9191 begin
9192    ...
9193    for J in Data'Range loop
9194       if Data (J) = Int1V.all then
9195          Int2V.all := Int2V.all + 1;
9196       end if;
9197    end loop;
9198    ...
9199 end R;
9200 @end cartouche
9201 @end smallexample
9202
9203 @noindent
9204 In this example, since the variable @code{Int1V} can only access objects
9205 of type @code{Int1}, and @code{Int2V} can only access objects of type
9206 @code{Int2}, there is no possibility that the assignment to
9207 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9208 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9209 for all iterations of the loop and avoid the extra memory reference
9210 required to dereference it each time through the loop.
9211
9212 This kind of optimziation, called strict aliasing analysis, is
9213 triggered by specifying an optimization level of @option{-O2} or
9214 higher and allows @code{GNAT} to generate more efficient code
9215 when access values are involved.
9216
9217 However, although this optimization is always correct in terms of
9218 the formal semantics of the Ada Reference Manual, difficulties can
9219 arise if features like @code{Unchecked_Conversion} are used to break
9220 the typing system. Consider the following complete program example:
9221
9222 @smallexample @c ada
9223 @cartouche
9224 package p1 is
9225    type int1 is new integer;
9226    type int2 is new integer;
9227    type a1 is access int1;
9228    type a2 is access int2;
9229 end p1;
9230
9231 with p1; use p1;
9232 package p2 is
9233    function to_a2 (Input : a1) return a2;
9234 end p2;
9235
9236 with Unchecked_Conversion;
9237 package body p2 is
9238    function to_a2 (Input : a1) return a2 is
9239       function to_a2u is
9240         new Unchecked_Conversion (a1, a2);
9241    begin
9242       return to_a2u (Input);
9243    end to_a2;
9244 end p2;
9245
9246 with p2; use p2;
9247 with p1; use p1;
9248 with Text_IO; use Text_IO;
9249 procedure m is
9250    v1 : a1 := new int1;
9251    v2 : a2 := to_a2 (v1);
9252 begin
9253    v1.all := 1;
9254    v2.all := 0;
9255    put_line (int1'image (v1.all));
9256 end;
9257 @end cartouche
9258 @end smallexample
9259
9260 @noindent
9261 This program prints out 0 in @code{-O0} or @code{-O1}
9262 mode, but it prints out 1 in @code{-O2} mode. That's
9263 because in strict aliasing mode, the compiler can and
9264 does assume that the assignment to @code{v2.all} could not
9265 affect the value of @code{v1.all}, since different types
9266 are involved.
9267
9268 This behavior is not a case of non-conformance with the standard, since
9269 the Ada RM specifies that an unchecked conversion where the resulting
9270 bit pattern is not a correct value of the target type can result in an
9271 abnormal value and attempting to reference an abnormal value makes the
9272 execution of a program erroneous.  That's the case here since the result
9273 does not point to an object of type @code{int2}.  This means that the
9274 effect is entirely unpredictable.
9275
9276 However, although that explanation may satisfy a language
9277 lawyer, in practice an applications programmer expects an
9278 unchecked conversion involving pointers to create true
9279 aliases and the behavior of printing 1 seems plain wrong.
9280 In this case, the strict aliasing optimization is unwelcome.
9281
9282 Indeed the compiler recognizes this possibility, and the
9283 unchecked conversion generates a warning:
9284
9285 @smallexample
9286 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9287 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9288 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9289 @end smallexample
9290
9291 @noindent
9292 Unfortunately the problem is recognized when compiling the body of
9293 package @code{p2}, but the actual "bad" code is generated while
9294 compiling the body of @code{m} and this latter compilation does not see
9295 the suspicious @code{Unchecked_Conversion}.
9296
9297 As implied by the warning message, there are approaches you can use to
9298 avoid the unwanted strict aliasing optimization in a case like this.
9299
9300 One possibility is to simply avoid the use of @code{-O2}, but
9301 that is a bit drastic, since it throws away a number of useful
9302 optimizations that do not involve strict aliasing assumptions.
9303
9304 A less drastic approach is to compile the program using the
9305 option @code{-fno-strict-aliasing}. Actually it is only the
9306 unit containing the dereferencing of the suspicious pointer
9307 that needs to be compiled. So in this case, if we compile
9308 unit @code{m} with this switch, then we get the expected
9309 value of zero printed. Analyzing which units might need
9310 the switch can be painful, so a more reasonable approach
9311 is to compile the entire program with options @code{-O2}
9312 and @code{-fno-strict-aliasing}. If the performance is
9313 satisfactory with this combination of options, then the
9314 advantage is that the entire issue of possible "wrong"
9315 optimization due to strict aliasing is avoided.
9316
9317 To avoid the use of compiler switches, the configuration
9318 pragma @code{No_Strict_Aliasing} with no parameters may be
9319 used to specify that for all access types, the strict
9320 aliasing optimization should be suppressed.
9321
9322 However, these approaches are still overkill, in that they causes
9323 all manipulations of all access values to be deoptimized. A more
9324 refined approach is to concentrate attention on the specific
9325 access type identified as problematic.
9326
9327 First, if a careful analysis of uses of the pointer shows
9328 that there are no possible problematic references, then
9329 the warning can be suppressed by bracketing the
9330 instantiation of @code{Unchecked_Conversion} to turn
9331 the warning off:
9332
9333 @smallexample @c ada
9334    pragma Warnings (Off);
9335    function to_a2u is
9336      new Unchecked_Conversion (a1, a2);
9337    pragma Warnings (On);
9338 @end smallexample
9339
9340 @noindent
9341 Of course that approach is not appropriate for this particular
9342 example, since indeed there is a problematic reference. In this
9343 case we can take one of two other approaches.
9344
9345 The first possibility is to move the instantiation of unchecked
9346 conversion to the unit in which the type is declared. In
9347 this example, we would move the instantiation of
9348 @code{Unchecked_Conversion} from the body of package
9349 @code{p2} to the spec of package @code{p1}. Now the
9350 warning disappears. That's because any use of the
9351 access type knows there is a suspicious unchecked
9352 conversion, and the strict aliasing optimization
9353 is automatically suppressed for the type.
9354
9355 If it is not practical to move the unchecked conversion to the same unit
9356 in which the destination access type is declared (perhaps because the
9357 source type is not visible in that unit), you may use pragma
9358 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9359 same declarative sequence as the declaration of the access type:
9360
9361 @smallexample @c ada
9362    type a2 is access int2;
9363    pragma No_Strict_Aliasing (a2);
9364 @end smallexample
9365
9366 @noindent
9367 Here again, the compiler now knows that the strict aliasing optimization
9368 should be suppressed for any reference to type @code{a2} and the
9369 expected behavior is obtained.
9370
9371 Finally, note that although the compiler can generate warnings for
9372 simple cases of unchecked conversions, there are tricker and more
9373 indirect ways of creating type incorrect aliases which the compiler
9374 cannot detect. Examples are the use of address overlays and unchecked
9375 conversions involving composite types containing access types as
9376 components. In such cases, no warnings are generated, but there can
9377 still be aliasing problems. One safe coding practice is to forbid the
9378 use of address clauses for type overlaying, and to allow unchecked
9379 conversion only for primitive types. This is not really a significant
9380 restriction since any possible desired effect can be achieved by
9381 unchecked conversion of access values.
9382
9383 @ifset vms
9384 @node Coverage Analysis
9385 @subsection Coverage Analysis
9386
9387 @noindent
9388 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
9389 the user to determine the distribution of execution time across a program,
9390 @pxref{Profiling} for details of usage.
9391 @end ifset
9392
9393 @node Reducing the Size of Ada Executables with gnatelim
9394 @section Reducing the Size of Ada Executables with @code{gnatelim}
9395 @findex gnatelim
9396
9397 @noindent
9398 This section describes @command{gnatelim}, a tool which detects unused
9399 subprograms and helps the compiler to create a smaller executable for your
9400 program.
9401
9402 @menu
9403 * About gnatelim::
9404 * Running gnatelim::
9405 * Correcting the List of Eliminate Pragmas::
9406 * Making Your Executables Smaller::
9407 * Summary of the gnatelim Usage Cycle::
9408 @end menu
9409
9410 @node About gnatelim
9411 @subsection About @code{gnatelim}
9412
9413 @noindent
9414 When a program shares a set of Ada
9415 packages with other programs, it may happen that this program uses
9416 only a fraction of the subprograms defined in these packages. The code
9417 created for these unused subprograms increases the size of the executable.
9418
9419 @code{gnatelim} tracks unused subprograms in an Ada program and
9420 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9421 subprograms that are declared but never called. By placing the list of
9422 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9423 recompiling your program, you may decrease the size of its executable,
9424 because the compiler will not generate the code for 'eliminated' subprograms.
9425 See GNAT Reference Manual for more information about this pragma.
9426
9427 @code{gnatelim} needs as its input data the name of the main subprogram
9428 and a bind file for a main subprogram.
9429
9430 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9431 the main subprogram. @code{gnatelim} can work with both Ada and C
9432 bind files; when both are present, it uses the Ada bind file.
9433 The following commands will build the program and create the bind file:
9434
9435 @smallexample
9436 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9437 $ gnatbind main_prog
9438 @end smallexample
9439
9440 Note that @code{gnatelim} needs neither object nor ALI files.
9441
9442 @node Running gnatelim
9443 @subsection Running @code{gnatelim}
9444
9445 @noindent
9446 @code{gnatelim} has the following command-line interface:
9447
9448 @smallexample
9449 $ gnatelim [options] name
9450 @end smallexample
9451
9452 @noindent
9453 @code{name} should be a name of a source file that contains the main subprogram
9454 of a program (partition).
9455
9456 @code{gnatelim} has the following switches:
9457
9458 @table @option
9459 @c !sort!
9460 @item ^-q^/QUIET^
9461 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9462 Quiet mode: by default @code{gnatelim} outputs to the standard error
9463 stream the number of program units left to be processed. This option turns
9464 this trace off.
9465
9466 @item ^-v^/VERBOSE^
9467 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9468 Verbose mode: @code{gnatelim} version information is printed as Ada
9469 comments to the standard output stream. Also, in addition to the number of
9470 program units left @code{gnatelim} will output the name of the current unit
9471 being processed.
9472
9473 @item ^-a^/ALL^
9474 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9475 Also look for subprograms from the GNAT run time that can be eliminated. Note
9476 that when @file{gnat.adc} is produced using this switch, the entire program
9477 must be recompiled with switch @option{^-a^/ALL_FILES^} to @code{gnatmake}.
9478
9479 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9480 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9481 When looking for source files also look in directory @var{dir}. Specifying
9482 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9483 sources in the current directory.
9484
9485 @item ^-b^/BIND_FILE=^@var{bind_file}
9486 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9487 Specifies @var{bind_file} as the bind file to process. If not set, the name
9488 of the bind file is computed from the full expanded Ada name
9489 of a main subprogram.
9490
9491 @item ^-C^/CONFIG_FILE=^@var{config_file}
9492 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9493 Specifies a file @var{config_file} that contains configuration pragmas. The
9494 file must be specified with full path.
9495
9496 @item ^--GCC^/COMPILER^=@var{compiler_name}
9497 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9498 Instructs @code{gnatelim} to use specific @code{gcc} compiler instead of one
9499 available on the path.
9500
9501 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9502 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9503 Instructs @code{gnatelim} to use specific @code{gnatmake} instead of one
9504 available on the path.
9505
9506 @item -d@var{x}
9507 @cindex @option{-d@var{x}} (@command{gnatelim})
9508 Activate internal debugging switches. @var{x} is a letter or digit, or
9509 string of letters or digits, which specifies the type of debugging
9510 mode desired.  Normally these are used only for internal development
9511 or system debugging purposes. You can find full documentation for these
9512 switches in the spec of the @code{Gnatelim} unit in the compiler
9513 source file @file{gnatelim.ads}.
9514 @end table
9515
9516 @noindent
9517 @code{gnatelim} sends its output to the standard output stream, and all the
9518 tracing and debug information is sent to the standard error stream.
9519 In order to produce a proper GNAT configuration file
9520 @file{gnat.adc}, redirection must be used:
9521
9522 @smallexample
9523 @ifset vms
9524 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9525 @end ifset
9526 @ifclear vms
9527 $ gnatelim main_prog.adb > gnat.adc
9528 @end ifclear
9529 @end smallexample
9530
9531 @ifclear vms
9532 @noindent
9533 or
9534
9535 @smallexample
9536 $ gnatelim main_prog.adb >> gnat.adc
9537 @end smallexample
9538
9539 @noindent
9540 in order to append the @code{gnatelim} output to the existing contents of
9541 @file{gnat.adc}.
9542 @end ifclear
9543
9544 @node Correcting the List of Eliminate Pragmas
9545 @subsection Correcting the List of Eliminate Pragmas
9546
9547 @noindent
9548 In some rare cases @code{gnatelim} may try to eliminate
9549 subprograms that are actually called in the program. In this case, the
9550 compiler will generate an error message of the form:
9551
9552 @smallexample
9553 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9554 @end smallexample
9555
9556 @noindent
9557 You will need to manually remove the wrong @code{Eliminate} pragmas from
9558 the @file{gnat.adc} file. You should recompile your program
9559 from scratch after that, because you need a consistent @file{gnat.adc} file
9560 during the entire compilation.
9561
9562
9563 @node Making Your Executables Smaller
9564 @subsection Making Your Executables Smaller
9565
9566 @noindent
9567 In order to get a smaller executable for your program you now have to
9568 recompile the program completely with the new @file{gnat.adc} file
9569 created by @code{gnatelim} in your current directory:
9570
9571 @smallexample
9572 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9573 @end smallexample
9574
9575 @noindent
9576 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9577 recompile everything
9578 with the set of pragmas @code{Eliminate} that you have obtained with
9579 @command{gnatelim}).
9580
9581 Be aware that the set of @code{Eliminate} pragmas is specific to each
9582 program. It is not recommended to merge sets of @code{Eliminate}
9583 pragmas created for different programs in one @file{gnat.adc} file.
9584
9585 @node Summary of the gnatelim Usage Cycle
9586 @subsection Summary of the gnatelim Usage Cycle
9587
9588 @noindent
9589 Here is a quick summary of the steps to be taken in order to reduce
9590 the size of your executables with @code{gnatelim}. You may use
9591 other GNAT options to control the optimization level,
9592 to produce the debugging information, to set search path, etc.
9593
9594 @enumerate
9595 @item
9596 Produce a bind file
9597
9598 @smallexample
9599 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9600 $ gnatbind main_prog
9601 @end smallexample
9602
9603 @item
9604 Generate a list of @code{Eliminate} pragmas
9605 @smallexample
9606 @ifset vms
9607 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9608 @end ifset
9609 @ifclear vms
9610 $ gnatelim main_prog >[>] gnat.adc
9611 @end ifclear
9612 @end smallexample
9613
9614 @item
9615 Recompile the application
9616
9617 @smallexample
9618 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9619 @end smallexample
9620
9621 @end enumerate
9622
9623
9624
9625
9626 @c ********************************
9627 @node Renaming Files Using gnatchop
9628 @chapter Renaming Files Using @code{gnatchop}
9629 @findex gnatchop
9630
9631 @noindent
9632 This chapter discusses how to handle files with multiple units by using
9633 the @code{gnatchop} utility. This utility is also useful in renaming
9634 files to meet the standard GNAT default file naming conventions.
9635
9636 @menu
9637 * Handling Files with Multiple Units::
9638 * Operating gnatchop in Compilation Mode::
9639 * Command Line for gnatchop::
9640 * Switches for gnatchop::
9641 * Examples of gnatchop Usage::
9642 @end menu
9643
9644 @node Handling Files with Multiple Units
9645 @section Handling Files with Multiple Units
9646
9647 @noindent
9648 The basic compilation model of GNAT requires that a file submitted to the
9649 compiler have only one unit and there be a strict correspondence
9650 between the file name and the unit name.
9651
9652 The @code{gnatchop} utility allows both of these rules to be relaxed,
9653 allowing GNAT to process files which contain multiple compilation units
9654 and files with arbitrary file names. @code{gnatchop}
9655 reads the specified file and generates one or more output files,
9656 containing one unit per file. The unit and the file name correspond,
9657 as required by GNAT.
9658
9659 If you want to permanently restructure a set of ``foreign'' files so that
9660 they match the GNAT rules, and do the remaining development using the
9661 GNAT structure, you can simply use @command{gnatchop} once, generate the
9662 new set of files and work with them from that point on.
9663
9664 Alternatively, if you want to keep your files in the ``foreign'' format,
9665 perhaps to maintain compatibility with some other Ada compilation
9666 system, you can set up a procedure where you use @command{gnatchop} each
9667 time you compile, regarding the source files that it writes as temporary
9668 files that you throw away.
9669
9670
9671 @node Operating gnatchop in Compilation Mode
9672 @section Operating gnatchop in Compilation Mode
9673
9674 @noindent
9675 The basic function of @code{gnatchop} is to take a file with multiple units
9676 and split it into separate files. The boundary between files is reasonably
9677 clear, except for the issue of comments and pragmas. In default mode, the
9678 rule is that any pragmas between units belong to the previous unit, except
9679 that configuration pragmas always belong to the following unit. Any comments
9680 belong to the following unit. These rules
9681 almost always result in the right choice of
9682 the split point without needing to mark it explicitly and most users will
9683 find this default to be what they want. In this default mode it is incorrect to
9684 submit a file containing only configuration pragmas, or one that ends in
9685 configuration pragmas, to @code{gnatchop}.
9686
9687 However, using a special option to activate ``compilation mode'',
9688 @code{gnatchop}
9689 can perform another function, which is to provide exactly the semantics
9690 required by the RM for handling of configuration pragmas in a compilation.
9691 In the absence of configuration pragmas (at the main file level), this
9692 option has no effect, but it causes such configuration pragmas to be handled
9693 in a quite different manner.
9694
9695 First, in compilation mode, if @code{gnatchop} is given a file that consists of
9696 only configuration pragmas, then this file is appended to the
9697 @file{gnat.adc} file in the current directory. This behavior provides
9698 the required behavior described in the RM for the actions to be taken
9699 on submitting such a file to the compiler, namely that these pragmas
9700 should apply to all subsequent compilations in the same compilation
9701 environment. Using GNAT, the current directory, possibly containing a
9702 @file{gnat.adc} file is the representation
9703 of a compilation environment. For more information on the
9704 @file{gnat.adc} file, see the section on handling of configuration
9705 pragmas @pxref{Handling of Configuration Pragmas}.
9706
9707 Second, in compilation mode, if @code{gnatchop}
9708 is given a file that starts with
9709 configuration pragmas, and contains one or more units, then these
9710 configuration pragmas are prepended to each of the chopped files. This
9711 behavior provides the required behavior described in the RM for the
9712 actions to be taken on compiling such a file, namely that the pragmas
9713 apply to all units in the compilation, but not to subsequently compiled
9714 units.
9715
9716 Finally, if configuration pragmas appear between units, they are appended
9717 to the previous unit. This results in the previous unit being illegal,
9718 since the compiler does not accept configuration pragmas that follow
9719 a unit. This provides the required RM behavior that forbids configuration
9720 pragmas other than those preceding the first compilation unit of a
9721 compilation.
9722
9723 For most purposes, @code{gnatchop} will be used in default mode. The
9724 compilation mode described above is used only if you need exactly
9725 accurate behavior with respect to compilations, and you have files
9726 that contain multiple units and configuration pragmas. In this
9727 circumstance the use of @code{gnatchop} with the compilation mode
9728 switch provides the required behavior, and is for example the mode
9729 in which GNAT processes the ACVC tests.
9730
9731 @node Command Line for gnatchop
9732 @section Command Line for @code{gnatchop}
9733
9734 @noindent
9735 The @code{gnatchop} command has the form:
9736
9737 @smallexample
9738 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9739       [@var{directory}]
9740 @end smallexample
9741
9742 @noindent
9743 The only required argument is the file name of the file to be chopped.
9744 There are no restrictions on the form of this file name. The file itself
9745 contains one or more Ada units, in normal GNAT format, concatenated
9746 together. As shown, more than one file may be presented to be chopped.
9747
9748 When run in default mode, @code{gnatchop} generates one output file in
9749 the current directory for each unit in each of the files.
9750
9751 @var{directory}, if specified, gives the name of the directory to which
9752 the output files will be written. If it is not specified, all files are
9753 written to the current directory.
9754
9755 For example, given a
9756 file called @file{hellofiles} containing
9757
9758 @smallexample @c ada
9759 @group
9760 @cartouche
9761 procedure hello;
9762
9763 with Text_IO; use Text_IO;
9764 procedure hello is
9765 begin
9766    Put_Line ("Hello");
9767 end hello;
9768 @end cartouche
9769 @end group
9770 @end smallexample
9771
9772 @noindent
9773 the command
9774
9775 @smallexample
9776 $ gnatchop ^hellofiles^HELLOFILES.^
9777 @end smallexample
9778
9779 @noindent
9780 generates two files in the current directory, one called
9781 @file{hello.ads} containing the single line that is the procedure spec,
9782 and the other called @file{hello.adb} containing the remaining text. The
9783 original file is not affected. The generated files can be compiled in
9784 the normal manner.
9785
9786 @noindent
9787 When gnatchop is invoked on a file that is empty or that contains only empty
9788 lines and/or comments, gnatchop will not fail, but will not produce any
9789 new sources.
9790
9791 For example, given a
9792 file called @file{toto.txt} containing
9793
9794 @smallexample @c ada
9795 @group
9796 @cartouche
9797 --  Just a comment
9798 @end cartouche
9799 @end group
9800 @end smallexample
9801
9802 @noindent
9803 the command
9804
9805 @smallexample
9806 $ gnatchop ^toto.txt^TOT.TXT^
9807 @end smallexample
9808
9809 @noindent
9810 will not produce any new file and will result in the following warnings:
9811
9812 @smallexample
9813 toto.txt:1:01: warning: empty file, contains no compilation units
9814 no compilation units found
9815 no source files written
9816 @end smallexample
9817
9818 @node Switches for gnatchop
9819 @section Switches for @code{gnatchop}
9820
9821 @noindent
9822 @command{gnatchop} recognizes the following switches:
9823
9824 @table @option
9825 @c !sort!
9826
9827 @item ^-c^/COMPILATION^
9828 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
9829 Causes @code{gnatchop} to operate in compilation mode, in which
9830 configuration pragmas are handled according to strict RM rules. See
9831 previous section for a full description of this mode.
9832
9833 @ifclear vms
9834 @item -gnatxxx
9835 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
9836 used to parse the given file. Not all @code{xxx} options make sense,
9837 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
9838 process a source file that uses Latin-2 coding for identifiers.
9839 @end ifclear
9840
9841 @item ^-h^/HELP^
9842 Causes @code{gnatchop} to generate a brief help summary to the standard
9843 output file showing usage information.
9844
9845 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
9846 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
9847 Limit generated file names to the specified number @code{mm}
9848 of characters.
9849 This is useful if the
9850 resulting set of files is required to be interoperable with systems
9851 which limit the length of file names.
9852 @ifset vms
9853 If no value is given, or
9854 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
9855 a default of 39, suitable for OpenVMS Alpha
9856 Systems, is assumed
9857 @end ifset
9858 @ifclear vms
9859 No space is allowed between the @option{-k} and the numeric value. The numeric
9860 value may be omitted in which case a default of @option{-k8},
9861 suitable for use
9862 with DOS-like file systems, is used. If no @option{-k} switch
9863 is present then
9864 there is no limit on the length of file names.
9865 @end ifclear
9866
9867 @item ^-p^/PRESERVE^
9868 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
9869 Causes the file ^modification^creation^ time stamp of the input file to be
9870 preserved and used for the time stamp of the output file(s). This may be
9871 useful for preserving coherency of time stamps in an environment where
9872 @code{gnatchop} is used as part of a standard build process.
9873
9874 @item ^-q^/QUIET^
9875 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
9876 Causes output of informational messages indicating the set of generated
9877 files to be suppressed. Warnings and error messages are unaffected.
9878
9879 @item ^-r^/REFERENCE^
9880 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
9881 @findex Source_Reference
9882 Generate @code{Source_Reference} pragmas. Use this switch if the output
9883 files are regarded as temporary and development is to be done in terms
9884 of the original unchopped file. This switch causes
9885 @code{Source_Reference} pragmas to be inserted into each of the
9886 generated files to refers back to the original file name and line number.
9887 The result is that all error messages refer back to the original
9888 unchopped file.
9889 In addition, the debugging information placed into the object file (when
9890 the @option{^-g^/DEBUG^} switch of @code{gcc} or @code{gnatmake} is specified)
9891 also refers back to this original file so that tools like profilers and
9892 debuggers will give information in terms of the original unchopped file.
9893
9894 If the original file to be chopped itself contains
9895 a @code{Source_Reference}
9896 pragma referencing a third file, then gnatchop respects
9897 this pragma, and the generated @code{Source_Reference} pragmas
9898 in the chopped file refer to the original file, with appropriate
9899 line numbers. This is particularly useful when @code{gnatchop}
9900 is used in conjunction with @code{gnatprep} to compile files that
9901 contain preprocessing statements and multiple units.
9902
9903 @item ^-v^/VERBOSE^
9904 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
9905 Causes @code{gnatchop} to operate in verbose mode. The version
9906 number and copyright notice are output, as well as exact copies of
9907 the gnat1 commands spawned to obtain the chop control information.
9908
9909 @item ^-w^/OVERWRITE^
9910 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
9911 Overwrite existing file names. Normally @code{gnatchop} regards it as a
9912 fatal error if there is already a file with the same name as a
9913 file it would otherwise output, in other words if the files to be
9914 chopped contain duplicated units. This switch bypasses this
9915 check, and causes all but the last instance of such duplicated
9916 units to be skipped.
9917
9918 @ifclear vms
9919 @item --GCC=xxxx
9920 @cindex @option{--GCC=} (@code{gnatchop})
9921 Specify the path of the GNAT parser to be used. When this switch is used,
9922 no attempt is made to add the prefix to the GNAT parser executable.
9923 @end ifclear
9924 @end table
9925
9926 @node Examples of gnatchop Usage
9927 @section Examples of @code{gnatchop} Usage
9928
9929 @table @code
9930 @ifset vms
9931 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
9932 @end ifset
9933 @ifclear vms
9934 @item gnatchop -w hello_s.ada prerelease/files
9935 @end ifclear
9936
9937 Chops the source file @file{hello_s.ada}. The output files will be
9938 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
9939 overwriting any
9940 files with matching names in that directory (no files in the current
9941 directory are modified).
9942
9943 @item gnatchop ^archive^ARCHIVE.^
9944 Chops the source file @file{^archive^ARCHIVE.^}
9945 into the current directory. One
9946 useful application of @code{gnatchop} is in sending sets of sources
9947 around, for example in email messages. The required sources are simply
9948 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
9949 command), and then
9950 @code{gnatchop} is used at the other end to reconstitute the original
9951 file names.
9952
9953 @item gnatchop file1 file2 file3 direc
9954 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
9955 the resulting files in the directory @file{direc}. Note that if any units
9956 occur more than once anywhere within this set of files, an error message
9957 is generated, and no files are written. To override this check, use the
9958 @option{^-w^/OVERWRITE^} switch,
9959 in which case the last occurrence in the last file will
9960 be the one that is output, and earlier duplicate occurrences for a given
9961 unit will be skipped.
9962 @end table
9963
9964 @node Configuration Pragmas
9965 @chapter Configuration Pragmas
9966 @cindex Configuration pragmas
9967 @cindex Pragmas, configuration
9968
9969 @noindent
9970 In Ada 95, configuration pragmas include those pragmas described as
9971 such in the Ada 95 Reference Manual, as well as
9972 implementation-dependent pragmas that are configuration pragmas. See the
9973 individual descriptions of pragmas in the GNAT Reference Manual for
9974 details on these additional GNAT-specific configuration pragmas. Most
9975 notably, the pragma @code{Source_File_Name}, which allows
9976 specifying non-default names for source files, is a configuration
9977 pragma. The following is a complete list of configuration pragmas
9978 recognized by @code{GNAT}:
9979
9980 @smallexample
9981    Ada_83
9982    Ada_95
9983    C_Pass_By_Copy
9984    Component_Alignment
9985    Discard_Names
9986    Elaboration_Checks
9987    Eliminate
9988    Extend_System
9989    Extensions_Allowed
9990    External_Name_Casing
9991    Float_Representation
9992    Initialize_Scalars
9993    License
9994    Locking_Policy
9995    Long_Float
9996    Normalize_Scalars
9997    Polling
9998    Profile
9999    Propagate_Exceptions
10000    Queuing_Policy
10001    Restricted_Run_Time
10002    Restrictions
10003    Reviewable
10004    Source_File_Name
10005    Style_Checks
10006    Suppress
10007    Task_Dispatching_Policy
10008    Universal_Data
10009    Unsuppress
10010    Use_VADS_Size
10011    Warnings
10012    Validity_Checks
10013 @end smallexample
10014
10015 @menu
10016 * Handling of Configuration Pragmas::
10017 * The Configuration Pragmas Files::
10018 @end menu
10019
10020 @node Handling of Configuration Pragmas
10021 @section Handling of Configuration Pragmas
10022
10023 Configuration pragmas may either appear at the start of a compilation
10024 unit, in which case they apply only to that unit, or they may apply to
10025 all compilations performed in a given compilation environment.
10026
10027 GNAT also provides the @code{gnatchop} utility to provide an automatic
10028 way to handle configuration pragmas following the semantics for
10029 compilations (that is, files with multiple units), described in the RM.
10030 See section @pxref{Operating gnatchop in Compilation Mode} for details.
10031 However, for most purposes, it will be more convenient to edit the
10032 @file{gnat.adc} file that contains configuration pragmas directly,
10033 as described in the following section.
10034
10035 @node The Configuration Pragmas Files
10036 @section The Configuration Pragmas Files
10037 @cindex @file{gnat.adc}
10038
10039 @noindent
10040 In GNAT a compilation environment is defined by the current
10041 directory at the time that a compile command is given. This current
10042 directory is searched for a file whose name is @file{gnat.adc}. If
10043 this file is present, it is expected to contain one or more
10044 configuration pragmas that will be applied to the current compilation.
10045 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10046 considered.
10047
10048 Configuration pragmas may be entered into the @file{gnat.adc} file
10049 either by running @code{gnatchop} on a source file that consists only of
10050 configuration pragmas, or more conveniently  by
10051 direct editing of the @file{gnat.adc} file, which is a standard format
10052 source file.
10053
10054 In addition to @file{gnat.adc}, one additional file containing configuration
10055 pragmas may be applied to the current compilation using the switch
10056 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10057 contains only configuration pragmas. These configuration pragmas are
10058 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10059 is present and switch @option{-gnatA} is not used).
10060
10061 It is allowed to specify several switches @option{-gnatec}, however only
10062 the last one on the command line will be taken into account.
10063
10064 If you are using project file, a separate mechanism is provided using
10065 project attributes, see @ref{Specifying Configuration Pragmas} for more
10066 details.
10067
10068 @ifset vms
10069 Of special interest to GNAT OpenVMS Alpha is the following
10070 configuration pragma:
10071
10072 @smallexample @c ada
10073 @cartouche
10074 pragma Extend_System (Aux_DEC);
10075 @end cartouche
10076 @end smallexample
10077
10078 @noindent
10079 In the presence of this pragma, GNAT adds to the definition of the
10080 predefined package SYSTEM all the additional types and subprograms that are
10081 defined in DEC Ada. See @pxref{Compatibility with DEC Ada} for details.
10082 @end ifset
10083
10084 @node Handling Arbitrary File Naming Conventions Using gnatname
10085 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10086 @cindex Arbitrary File Naming Conventions
10087
10088 @menu
10089 * Arbitrary File Naming Conventions::
10090 * Running gnatname::
10091 * Switches for gnatname::
10092 * Examples of gnatname Usage::
10093 @end menu
10094
10095 @node Arbitrary File Naming Conventions
10096 @section Arbitrary File Naming Conventions
10097
10098 @noindent
10099 The GNAT compiler must be able to know the source file name of a compilation
10100 unit.  When using the standard GNAT default file naming conventions
10101 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10102 does not need additional information.
10103
10104 @noindent
10105 When the source file names do not follow the standard GNAT default file naming
10106 conventions, the GNAT compiler must be given additional information through
10107 a configuration pragmas file (see @ref{Configuration Pragmas})
10108 or a project file.
10109 When the non standard file naming conventions are well-defined,
10110 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10111 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
10112 if the file naming conventions are irregular or arbitrary, a number
10113 of pragma @code{Source_File_Name} for individual compilation units
10114 must be defined.
10115 To help maintain the correspondence between compilation unit names and
10116 source file names within the compiler,
10117 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10118 set of files.
10119
10120 @node Running gnatname
10121 @section Running @code{gnatname}
10122
10123 @noindent
10124 The usual form of the @code{gnatname} command is
10125
10126 @smallexample
10127 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10128 @end smallexample
10129
10130 @noindent
10131 All of the arguments are optional. If invoked without any argument,
10132 @code{gnatname} will display its usage.
10133
10134 @noindent
10135 When used with at least one naming pattern, @code{gnatname} will attempt to
10136 find all the compilation units in files that follow at least one of the
10137 naming patterns. To find these compilation units,
10138 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10139 regular files.
10140
10141 @noindent
10142 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10143 Each Naming Pattern is enclosed between double quotes.
10144 A Naming Pattern is a regular expression similar to the wildcard patterns
10145 used in file names by the Unix shells or the DOS prompt.
10146
10147 @noindent
10148 Examples of Naming Patterns are
10149
10150 @smallexample
10151    "*.[12].ada"
10152    "*.ad[sb]*"
10153    "body_*"    "spec_*"
10154 @end smallexample
10155
10156 @noindent
10157 For a more complete description of the syntax of Naming Patterns,
10158 see the second kind of regular expressions described in @file{g-regexp.ads}
10159 (the ``Glob'' regular expressions).
10160
10161 @noindent
10162 When invoked with no switches, @code{gnatname} will create a configuration
10163 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10164 @code{Source_File_Name} for each file that contains a valid Ada unit.
10165
10166 @node Switches for gnatname
10167 @section Switches for @code{gnatname}
10168
10169 @noindent
10170 Switches for @code{gnatname} must precede any specified Naming Pattern.
10171
10172 @noindent
10173 You may specify any of the following switches to @code{gnatname}:
10174
10175 @table @option
10176 @c !sort!
10177
10178 @item ^-c^/CONFIG_FILE=^@file{file}
10179 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10180 Create a configuration pragmas file @file{file} (instead of the default
10181 @file{gnat.adc}).
10182 @ifclear vms
10183 There may be zero, one or more space between @option{-c} and
10184 @file{file}.
10185 @end ifclear
10186 @file{file} may include directory information. @file{file} must be
10187 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10188 When a switch @option{^-c^/CONFIG_FILE^} is
10189 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10190
10191 @item ^-d^/SOURCE_DIRS=^@file{dir}
10192 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10193 Look for source files in directory @file{dir}. There may be zero, one or more
10194 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10195 When a switch @option{^-d^/SOURCE_DIRS^}
10196 is specified, the current working directory will not be searched for source
10197 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10198 or @option{^-D^/DIR_FILES^} switch.
10199 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10200 If @file{dir} is a relative path, it is relative to the directory of
10201 the configuration pragmas file specified with switch
10202 @option{^-c^/CONFIG_FILE^},
10203 or to the directory of the project file specified with switch
10204 @option{^-P^/PROJECT_FILE^} or,
10205 if neither switch @option{^-c^/CONFIG_FILE^}
10206 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10207 current working directory. The directory
10208 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10209
10210 @item ^-D^/DIRS_FILE=^@file{file}
10211 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10212 Look for source files in all directories listed in text file @file{file}.
10213 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10214 and @file{file}.
10215 @file{file} must be an existing, readable text file.
10216 Each non empty line in @file{file} must be a directory.
10217 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10218 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10219 @file{file}.
10220
10221 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10222 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10223 Foreign patterns. Using this switch, it is possible to add sources of languages
10224 other than Ada to the list of sources of a project file.
10225 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10226 For example,
10227 @smallexample
10228 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10229 @end smallexample
10230 @noindent
10231 will look for Ada units in all files with the @file{.ada} extension,
10232 and will add to the list of file for project @file{prj.gpr} the C files
10233 with extension ".^c^C^".
10234
10235 @item ^-h^/HELP^
10236 @cindex @option{^-h^/HELP^} (@code{gnatname})
10237 Output usage (help) information. The output is written to @file{stdout}.
10238
10239 @item ^-P^/PROJECT_FILE=^@file{proj}
10240 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10241 Create or update project file @file{proj}. There may be zero, one or more space
10242 between @option{-P} and @file{proj}. @file{proj} may include directory
10243 information. @file{proj} must be writable.
10244 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10245 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10246 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10247
10248 @item ^-v^/VERBOSE^
10249 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10250 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10251 This includes name of the file written, the name of the directories to search
10252 and, for each file in those directories whose name matches at least one of
10253 the Naming Patterns, an indication of whether the file contains a unit,
10254 and if so the name of the unit.
10255
10256 @item ^-v -v^/VERBOSE /VERBOSE^
10257 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10258 Very Verbose mode. In addition to the output produced in verbose mode,
10259 for each file in the searched directories whose name matches none of
10260 the Naming Patterns, an indication is given that there is no match.
10261
10262 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10263 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10264 Excluded patterns. Using this switch, it is possible to exclude some files
10265 that would match the name patterns. For example,
10266 @smallexample
10267 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10268 @end smallexample
10269 @noindent
10270 will look for Ada units in all files with the @file{.ada} extension,
10271 except those whose names end with @file{_nt.ada}.
10272
10273 @end table
10274
10275 @node Examples of gnatname Usage
10276 @section Examples of @code{gnatname} Usage
10277
10278 @ifset vms
10279 @smallexample
10280 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10281 @end smallexample
10282 @end ifset
10283
10284 @ifclear vms
10285 @smallexample
10286 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10287 @end smallexample
10288 @end ifclear
10289
10290 @noindent
10291 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10292 and be writable. In addition, the directory
10293 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10294 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10295
10296 @ifclear vms
10297 Note the optional spaces after @option{-c} and @option{-d}.
10298 @end ifclear
10299
10300 @smallexample
10301 @ifclear vms
10302 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10303   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10304 @end ifclear
10305 @ifset vms
10306 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
10307   /EXCLUDED_PATTERN=*_nt_body.ada
10308   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10309   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10310 @end ifset
10311 @end smallexample
10312
10313 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10314 even in conjunction with one or several switches
10315 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10316 are used in this example.
10317
10318
10319 @c *****************************************
10320 @c * G N A T  P r o j e c t  M a n a g e r *
10321 @c *****************************************
10322 @node GNAT Project Manager
10323 @chapter GNAT Project Manager
10324
10325 @menu
10326 * Introduction::
10327 * Examples of Project Files::
10328 * Project File Syntax::
10329 * Objects and Sources in Project Files::
10330 * Importing Projects::
10331 * Project Extension::
10332 * External References in Project Files::
10333 * Packages in Project Files::
10334 * Variables from Imported Projects::
10335 * Naming Schemes::
10336 * Library Projects::
10337 * Using Third-Party Libraries through Projects::
10338 * Stand-alone Library Projects::
10339 * Switches Related to Project Files::
10340 * Tools Supporting Project Files::
10341 * An Extended Example::
10342 * Project File Complete Syntax::
10343 @end menu
10344
10345 @c ****************
10346 @c * Introduction *
10347 @c ****************
10348
10349 @node Introduction
10350 @section Introduction
10351
10352 @noindent
10353 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10354 you to manage complex builds involving a number of source files, directories,
10355 and compilation options for different system configurations. In particular,
10356 project files allow you to specify:
10357 @itemize @bullet
10358 @item
10359 The directory or set of directories containing the source files, and/or the
10360 names of the specific source files themselves
10361 @item
10362 The directory in which the compiler's output
10363 (@file{ALI} files, object files, tree files) is to be placed
10364 @item
10365 The directory in which the executable programs is to be placed
10366 @item
10367 ^Switch^Switch^ settings for any of the project-enabled tools
10368 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10369 @code{gnatfind}); you can apply these settings either globally or to individual
10370 compilation units.
10371 @item
10372 The source files containing the main subprogram(s) to be built
10373 @item
10374 The source programming language(s) (currently Ada and/or C)
10375 @item
10376 Source file naming conventions; you can specify these either globally or for
10377 individual compilation units
10378 @end itemize
10379
10380 @menu
10381 * Project Files::
10382 @end menu
10383
10384 @node Project Files
10385 @subsection Project Files
10386
10387 @noindent
10388 Project files are written in a syntax close to that of Ada, using  familiar
10389 notions such as packages, context clauses, declarations, default values,
10390 assignments, and inheritance. Finally, project files can be built
10391 hierarchically from other project files, simplifying complex system
10392 integration and project reuse.
10393
10394 A @dfn{project} is a specific set of values for various compilation properties.
10395 The settings for a given project are described by means of
10396 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10397 Property values in project files are either strings or lists of strings.
10398 Properties that are not explicitly set receive default values.  A project
10399 file may interrogate the values of @dfn{external variables} (user-defined
10400 command-line switches or environment variables), and it may specify property
10401 settings conditionally, based on the value of such variables.
10402
10403 In simple cases, a project's source files depend only on other source files
10404 in the same project, or on the predefined libraries.  (@emph{Dependence} is
10405 used in
10406 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10407 the Project Manager also allows more sophisticated arrangements,
10408 where the source files in one project depend on source files in other
10409 projects:
10410 @itemize @bullet
10411 @item
10412 One project can @emph{import} other projects containing needed source files.
10413 @item
10414 You can organize GNAT projects in a hierarchy: a @emph{child} project
10415 can extend a @emph{parent} project, inheriting the parent's source files and
10416 optionally overriding any of them with alternative versions
10417 @end itemize
10418
10419 @noindent
10420 More generally, the Project Manager lets you structure large development
10421 efforts into hierarchical subsystems, where build decisions are delegated
10422 to the subsystem level, and thus different compilation environments
10423 (^switch^switch^ settings) used for different subsystems.
10424
10425 The Project Manager is invoked through the
10426 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10427 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10428 @ifclear vms
10429 There may be zero, one or more spaces between @option{-P} and
10430 @option{@emph{projectfile}}.
10431 @end ifclear
10432 If you want to define (on the command line) an external variable that is
10433 queried by the project file, you must use the
10434 @option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10435 The Project Manager parses and interprets the project file, and drives the
10436 invoked tool based on the project settings.
10437
10438 The Project Manager supports a wide range of development strategies,
10439 for systems of all sizes.  Here are some typical practices that are
10440 easily handled:
10441 @itemize @bullet
10442 @item
10443 Using a common set of source files, but generating object files in different
10444 directories via different ^switch^switch^ settings
10445 @item
10446 Using a mostly-shared set of source files, but with different versions of
10447 some unit or units
10448 @end itemize
10449
10450 @noindent
10451 The destination of an executable can be controlled inside a project file
10452 using the @option{^-o^-o^}
10453 ^switch^switch^.
10454 In the absence of such a ^switch^switch^ either inside
10455 the project file or on the command line, any executable files generated by
10456 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10457 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10458 in the object directory of the project.
10459
10460 You can use project files to achieve some of the effects of a source
10461 versioning system (for example, defining separate projects for
10462 the different sets of sources that comprise different releases) but the
10463 Project Manager is independent of any source configuration management tools
10464 that might be used by the developers.
10465
10466 The next section introduces the main features of GNAT's project facility
10467 through a sequence of examples; subsequent sections will present the syntax
10468 and semantics in more detail. A more formal description of the project
10469 facility appears in the GNAT Reference Manual.
10470
10471 @c *****************************
10472 @c * Examples of Project Files *
10473 @c *****************************
10474
10475 @node Examples of Project Files
10476 @section Examples of Project Files
10477 @noindent
10478 This section illustrates some of the typical uses of project files and
10479 explains their basic structure and behavior.
10480
10481 @menu
10482 * Common Sources with Different ^Switches^Switches^ and Directories::
10483 * Using External Variables::
10484 * Importing Other Projects::
10485 * Extending a Project::
10486 @end menu
10487
10488 @node Common Sources with Different ^Switches^Switches^ and Directories
10489 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10490
10491 @menu
10492 * Source Files::
10493 * Specifying the Object Directory::
10494 * Specifying the Exec Directory::
10495 * Project File Packages::
10496 * Specifying ^Switch^Switch^ Settings::
10497 * Main Subprograms::
10498 * Executable File Names::
10499 * Source File Naming Conventions::
10500 * Source Language(s)::
10501 @end menu
10502
10503 @noindent
10504 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10505 @file{proc.adb} are in the @file{/common} directory.  The file
10506 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10507 package @code{Pack}.  We want to compile these source files under two sets
10508 of ^switches^switches^:
10509 @itemize @bullet
10510 @item
10511 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10512 and the @option{^-gnata^-gnata^},
10513 @option{^-gnato^-gnato^},
10514 and @option{^-gnatE^-gnatE^} switches to the
10515 compiler; the compiler's output is to appear in @file{/common/debug}
10516 @item
10517 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10518 to the compiler; the compiler's output is to appear in @file{/common/release}
10519 @end itemize
10520
10521 @noindent
10522 The GNAT project files shown below, respectively @file{debug.gpr} and
10523 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10524
10525 Schematically:
10526 @smallexample
10527 @group
10528 ^/common^[COMMON]^
10529   debug.gpr
10530   release.gpr
10531   pack.ads
10532   pack.adb
10533   proc.adb
10534 @end group
10535 @group
10536 ^/common/debug^[COMMON.DEBUG]^
10537   proc.ali, proc.o
10538   pack.ali, pack.o
10539 @end group
10540 @group
10541 ^/common/release^[COMMON.RELEASE]^
10542   proc.ali, proc.o
10543   pack.ali, pack.o
10544 @end group
10545 @end smallexample
10546 Here are the corresponding project files:
10547
10548 @smallexample @c projectfile
10549 @group
10550 project Debug is
10551   for Object_Dir use "debug";
10552   for Main use ("proc");
10553
10554   package Builder is
10555     for ^Default_Switches^Default_Switches^ ("Ada")
10556         use ("^-g^-g^");
10557     for Executable ("proc.adb") use "proc1";
10558   end Builder;
10559 @end group
10560
10561 @group
10562   package Compiler is
10563     for ^Default_Switches^Default_Switches^ ("Ada")
10564        use ("-fstack-check",
10565             "^-gnata^-gnata^",
10566             "^-gnato^-gnato^",
10567             "^-gnatE^-gnatE^");
10568   end Compiler;
10569 end Debug;
10570 @end group
10571 @end smallexample
10572
10573 @smallexample @c projectfile
10574 @group
10575 project Release is
10576   for Object_Dir use "release";
10577   for Exec_Dir use ".";
10578   for Main use ("proc");
10579
10580   package Compiler is
10581     for ^Default_Switches^Default_Switches^ ("Ada")
10582         use ("^-O2^-O2^");
10583   end Compiler;
10584 end Release;
10585 @end group
10586 @end smallexample
10587
10588 @noindent
10589 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10590 insensitive), and analogously the project defined by @file{release.gpr} is
10591 @code{"Release"}.  For consistency the file should have the same name as the
10592 project, and the project file's extension should be @code{"gpr"}. These
10593 conventions are not required, but a warning is issued if they are not followed.
10594
10595 If the current directory is @file{^/temp^[TEMP]^}, then the command
10596 @smallexample
10597 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10598 @end smallexample
10599
10600 @noindent
10601 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10602 as well as the @code{^proc1^PROC1.EXE^} executable,
10603 using the ^switch^switch^ settings defined in the project file.
10604
10605 Likewise, the command
10606 @smallexample
10607 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10608 @end smallexample
10609
10610 @noindent
10611 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10612 and the @code{^proc^PROC.EXE^}
10613 executable in @file{^/common^[COMMON]^},
10614 using the ^switch^switch^ settings from the project file.
10615
10616 @node Source Files
10617 @unnumberedsubsubsec Source Files
10618
10619 @noindent
10620 If a project file does not explicitly specify a set of source directories or
10621 a set of source files, then by default the project's source files are the
10622 Ada source files in the project file directory.  Thus @file{pack.ads},
10623 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10624
10625 @node Specifying the Object Directory
10626 @unnumberedsubsubsec Specifying the Object Directory
10627
10628 @noindent
10629 Several project properties are modeled by Ada-style @emph{attributes};
10630 a property is defined by supplying the equivalent of an Ada attribute
10631 definition clause in the project file.
10632 A project's object directory is another such a property; the corresponding
10633 attribute is @code{Object_Dir}, and its value is also a string expression,
10634 specified either as absolute or relative. In the later case,
10635 it is relative to the project file directory. Thus the compiler's
10636 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10637 (for the @code{Debug} project)
10638 and to @file{^/common/release^[COMMON.RELEASE]^}
10639 (for the @code{Release} project).
10640 If @code{Object_Dir} is not specified, then the default is the project file
10641 directory itself.
10642
10643 @node Specifying the Exec Directory
10644 @unnumberedsubsubsec Specifying the Exec Directory
10645
10646 @noindent
10647 A project's exec directory is another property; the corresponding
10648 attribute is @code{Exec_Dir}, and its value is also a string expression,
10649 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10650 then the default is the object directory (which may also be the project file
10651 directory if attribute @code{Object_Dir} is not specified). Thus the executable
10652 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10653 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10654 and in @file{^/common^[COMMON]^} for the @code{Release} project.
10655
10656 @node Project File Packages
10657 @unnumberedsubsubsec Project File Packages
10658
10659 @noindent
10660 A GNAT tool that is integrated with the Project Manager is modeled by a
10661 corresponding package in the project file. In the example above,
10662 The @code{Debug} project defines the packages @code{Builder}
10663 (for @command{gnatmake}) and @code{Compiler};
10664 the @code{Release} project defines only the @code{Compiler} package.
10665
10666 The Ada-like package syntax is not to be taken literally.  Although packages in
10667 project files bear a surface resemblance to packages in Ada source code, the
10668 notation is simply a way to convey a grouping of properties for a named
10669 entity.  Indeed, the package names permitted in project files are restricted
10670 to a predefined set, corresponding to the project-aware tools, and the contents
10671 of packages are limited to a small set of constructs.
10672 The packages in the example above contain attribute definitions.
10673
10674 @node Specifying ^Switch^Switch^ Settings
10675 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10676
10677 @noindent
10678 ^Switch^Switch^ settings for a project-aware tool can be specified through
10679 attributes in the package that corresponds to the tool.
10680 The example above illustrates one of the relevant attributes,
10681 @code{^Default_Switches^Default_Switches^}, which is defined in packages
10682 in both project files.
10683 Unlike simple attributes like @code{Source_Dirs},
10684 @code{^Default_Switches^Default_Switches^} is
10685 known as an @emph{associative array}.  When you define this attribute, you must
10686 supply an ``index'' (a literal string), and the effect of the attribute
10687 definition is to set the value of the array at the specified index.
10688 For the @code{^Default_Switches^Default_Switches^} attribute,
10689 the index is a programming language (in our case, Ada),
10690 and the value specified (after @code{use}) must be a list
10691 of string expressions.
10692
10693 The attributes permitted in project files are restricted to a predefined set.
10694 Some may appear at project level, others in packages.
10695 For any attribute that is an associative array, the index must always be a
10696 literal string, but the restrictions on this string (e.g., a file name or a
10697 language name) depend on the individual attribute.
10698 Also depending on the attribute, its specified value will need to be either a
10699 string or a string list.
10700
10701 In the @code{Debug} project, we set the switches for two tools,
10702 @command{gnatmake} and the compiler, and thus we include the two corresponding
10703 packages; each package defines the @code{^Default_Switches^Default_Switches^}
10704 attribute with index @code{"Ada"}.
10705 Note that the package corresponding to
10706 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
10707 similar, but only includes the @code{Compiler} package.
10708
10709 In project @code{Debug} above, the ^switches^switches^ starting with
10710 @option{-gnat} that are specified in package @code{Compiler}
10711 could have been placed in package @code{Builder}, since @command{gnatmake}
10712 transmits all such ^switches^switches^ to the compiler.
10713
10714 @node Main Subprograms
10715 @unnumberedsubsubsec Main Subprograms
10716
10717 @noindent
10718 One of the specifiable properties of a project is a list of files that contain
10719 main subprograms.  This property is captured in the @code{Main} attribute,
10720 whose value is a list of strings.  If a project defines the @code{Main}
10721 attribute, it is not necessary to identify the main subprogram(s) when
10722 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
10723
10724 @node Executable File Names
10725 @unnumberedsubsubsec Executable File Names
10726
10727 @noindent
10728 By default, the executable file name corresponding to a main source is
10729 deducted from the main source file name. Through the attributes
10730 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10731 it is possible to change this default.
10732 In project @code{Debug} above, the executable file name
10733 for main source @file{^proc.adb^PROC.ADB^} is
10734 @file{^proc1^PROC1.EXE^}.
10735 Attribute @code{Executable_Suffix}, when specified, may change the suffix
10736 of the the executable files, when no attribute @code{Executable} applies:
10737 its value replace the platform-specific executable suffix.
10738 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10739 specify a non default executable file name when several mains are built at once
10740 in a single @command{gnatmake} command.
10741
10742 @node Source File Naming Conventions
10743 @unnumberedsubsubsec Source File Naming Conventions
10744
10745 @noindent
10746 Since the project files above do not specify any source file naming
10747 conventions, the GNAT defaults are used.  The mechanism for defining source
10748 file naming conventions -- a package named @code{Naming} --
10749 is described below (@pxref{Naming Schemes}).
10750
10751 @node Source Language(s)
10752 @unnumberedsubsubsec Source Language(s)
10753
10754 @noindent
10755 Since the project files do not specify a @code{Languages} attribute, by
10756 default the GNAT tools assume that the language of the project file is Ada.
10757 More generally, a project can comprise source files
10758 in Ada, C, and/or other languages.
10759
10760 @node Using External Variables
10761 @subsection Using External Variables
10762
10763 @noindent
10764 Instead of supplying different project files for debug and release, we can
10765 define a single project file that queries an external variable (set either
10766 on the command line or via an ^environment variable^logical name^) in order to
10767 conditionally define the appropriate settings.  Again, assume that the
10768 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
10769 located in directory @file{^/common^[COMMON]^}.  The following project file,
10770 @file{build.gpr}, queries the external variable named @code{STYLE} and
10771 defines an object directory and ^switch^switch^ settings based on whether
10772 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
10773 the default is @code{"deb"}.
10774
10775 @smallexample @c projectfile
10776 @group
10777 project Build is
10778   for Main use ("proc");
10779
10780   type Style_Type is ("deb", "rel");
10781   Style : Style_Type := external ("STYLE", "deb");
10782
10783   case Style is
10784     when "deb" =>
10785       for Object_Dir use "debug";
10786
10787     when "rel" =>
10788       for Object_Dir use "release";
10789       for Exec_Dir use ".";
10790   end case;
10791 @end group
10792
10793 @group
10794   package Builder is
10795
10796     case Style is
10797       when "deb" =>
10798         for ^Default_Switches^Default_Switches^ ("Ada")
10799             use ("^-g^-g^");
10800         for Executable ("proc") use "proc1";
10801     end case;
10802
10803   end Builder;
10804 @end group
10805
10806 @group
10807   package Compiler is
10808
10809     case Style is
10810       when "deb" =>
10811         for ^Default_Switches^Default_Switches^ ("Ada")
10812             use ("^-gnata^-gnata^",
10813                  "^-gnato^-gnato^",
10814                  "^-gnatE^-gnatE^");
10815
10816       when "rel" =>
10817         for ^Default_Switches^Default_Switches^ ("Ada")
10818             use ("^-O2^-O2^");
10819     end case;
10820
10821   end Compiler;
10822
10823 end Build;
10824 @end group
10825 @end smallexample
10826
10827 @noindent
10828 @code{Style_Type} is an example of a @emph{string type}, which is the project
10829 file analog of an Ada enumeration type but whose components are string literals
10830 rather than identifiers.  @code{Style} is declared as a variable of this type.
10831
10832 The form @code{external("STYLE", "deb")} is known as an
10833 @emph{external reference}; its first argument is the name of an
10834 @emph{external variable}, and the second argument is a default value to be
10835 used if the external variable doesn't exist.  You can define an external
10836 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
10837 or you can use ^an environment variable^a logical name^
10838 as an external variable.
10839
10840 Each @code{case} construct is expanded by the Project Manager based on the
10841 value of @code{Style}. Thus the command
10842 @ifclear vms
10843 @smallexample
10844 gnatmake -P/common/build.gpr -XSTYLE=deb
10845 @end smallexample
10846 @end ifclear
10847
10848 @ifset vms
10849 @smallexample
10850 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
10851 @end smallexample
10852 @end ifset
10853
10854 @noindent
10855 is equivalent to the @command{gnatmake} invocation using the project file
10856 @file{debug.gpr} in the earlier example.  So is the command
10857 @smallexample
10858 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
10859 @end smallexample
10860
10861 @noindent
10862 since @code{"deb"} is the default for @code{STYLE}.
10863
10864 Analogously,
10865
10866 @ifclear vms
10867 @smallexample
10868 gnatmake -P/common/build.gpr -XSTYLE=rel
10869 @end smallexample
10870 @end ifclear
10871
10872 @ifset vms
10873 @smallexample
10874 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
10875 @end smallexample
10876 @end ifset
10877
10878 @noindent
10879 is equivalent to the @command{gnatmake} invocation using the project file
10880 @file{release.gpr} in the earlier example.
10881
10882 @node Importing Other Projects
10883 @subsection Importing Other Projects
10884
10885 @noindent
10886 A compilation unit in a source file in one project may depend on compilation
10887 units in source files in other projects.  To compile this unit under
10888 control of a project file, the
10889 dependent project must @emph{import} the projects containing the needed source
10890 files.
10891 This effect is obtained using syntax similar to an Ada @code{with} clause,
10892 but where @code{with}ed entities are strings that denote project files.
10893
10894 As an example, suppose that the two projects @code{GUI_Proj} and
10895 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
10896 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
10897 and @file{^/comm^[COMM]^}, respectively.
10898 Suppose that the source files for @code{GUI_Proj} are
10899 @file{gui.ads} and @file{gui.adb}, and that the source files for
10900 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
10901 files is located in its respective project file directory.  Schematically:
10902
10903 @smallexample
10904 @group
10905 ^/gui^[GUI]^
10906   gui_proj.gpr
10907   gui.ads
10908   gui.adb
10909 @end group
10910
10911 @group
10912 ^/comm^[COMM]^
10913   comm_proj.gpr
10914   comm.ads
10915   comm.adb
10916 @end group
10917 @end smallexample
10918
10919 @noindent
10920 We want to develop an application in directory @file{^/app^[APP]^} that
10921 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
10922 the corresponding project files (e.g. the ^switch^switch^ settings
10923 and object directory).
10924 Skeletal code for a main procedure might be something like the following:
10925
10926 @smallexample @c ada
10927 @group
10928 with GUI, Comm;
10929 procedure App_Main is
10930    ...
10931 begin
10932    ...
10933 end App_Main;
10934 @end group
10935 @end smallexample
10936
10937 @noindent
10938 Here is a project file, @file{app_proj.gpr}, that achieves the desired
10939 effect:
10940
10941 @smallexample @c projectfile
10942 @group
10943 with "/gui/gui_proj", "/comm/comm_proj";
10944 project App_Proj is
10945    for Main use ("app_main");
10946 end App_Proj;
10947 @end group
10948 @end smallexample
10949
10950 @noindent
10951 Building an executable is achieved through the command:
10952 @smallexample
10953 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
10954 @end smallexample
10955 @noindent
10956 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
10957 in the directory where @file{app_proj.gpr} resides.
10958
10959 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
10960 (as illustrated above) the @code{with} clause can omit the extension.
10961
10962 Our example specified an absolute path for each imported project file.
10963 Alternatively, the directory name of an imported object can be omitted
10964 if either
10965 @itemize @bullet
10966 @item
10967 The imported project file is in the same directory as the importing project
10968 file, or
10969 @item
10970 You have defined ^an environment variable^a logical name^
10971 that includes the directory containing
10972 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
10973 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
10974 directory names separated by colons (semicolons on Windows).
10975 @end itemize
10976
10977 @noindent
10978 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
10979 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
10980 as follows:
10981
10982 @smallexample @c projectfile
10983 @group
10984 with "gui_proj", "comm_proj";
10985 project App_Proj is
10986    for Main use ("app_main");
10987 end App_Proj;
10988 @end group
10989 @end smallexample
10990
10991 @noindent
10992 Importing other projects can create ambiguities.
10993 For example, the same unit might be present in different imported projects, or
10994 it might be present in both the importing project and in an imported project.
10995 Both of these conditions are errors.  Note that in the current version of
10996 the Project Manager, it is illegal to have an ambiguous unit even if the
10997 unit is never referenced by the importing project.  This restriction may be
10998 relaxed in a future release.
10999
11000 @node Extending a Project
11001 @subsection Extending a Project
11002
11003 @noindent
11004 In large software systems it is common to have multiple
11005 implementations of a common interface; in Ada terms, multiple versions of a
11006 package body for the same specification.  For example, one implementation
11007 might be safe for use in tasking programs, while another might only be used
11008 in sequential applications.  This can be modeled in GNAT using the concept
11009 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
11010 another project (the ``parent'') then by default all source files of the
11011 parent project are inherited by the child, but the child project can
11012 override any of the parent's source files with new versions, and can also
11013 add new files.  This facility is the project analog of a type extension in
11014 Object-Oriented Programming.  Project hierarchies are permitted (a child
11015 project may be the parent of yet another project), and a project that
11016 inherits one project can also import other projects.
11017
11018 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11019 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11020 @file{pack.adb}, and @file{proc.adb}:
11021
11022 @smallexample
11023 @group
11024 ^/seq^[SEQ]^
11025   pack.ads
11026   pack.adb
11027   proc.adb
11028   seq_proj.gpr
11029 @end group
11030 @end smallexample
11031
11032 @noindent
11033 Note that the project file can simply be empty (that is, no attribute or
11034 package is defined):
11035
11036 @smallexample @c projectfile
11037 @group
11038 project Seq_Proj is
11039 end Seq_Proj;
11040 @end group
11041 @end smallexample
11042
11043 @noindent
11044 implying that its source files are all the Ada source files in the project
11045 directory.
11046
11047 Suppose we want to supply an alternate version of @file{pack.adb}, in
11048 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11049 @file{pack.ads} and @file{proc.adb}.  We can define a project
11050 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11051
11052 @smallexample
11053 @group
11054 ^/tasking^[TASKING]^
11055   pack.adb
11056   tasking_proj.gpr
11057 @end group
11058
11059 @group
11060 project Tasking_Proj extends "/seq/seq_proj" is
11061 end Tasking_Proj;
11062 @end group
11063 @end smallexample
11064
11065 @noindent
11066 The version of @file{pack.adb} used in a build depends on which project file
11067 is specified.
11068
11069 Note that we could have obtained the desired behavior using project import
11070 rather than project inheritance; a @code{base} project would contain the
11071 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11072 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11073 would import @code{base} and add a different version of @file{pack.adb}.  The
11074 choice depends on whether other sources in the original project need to be
11075 overridden.  If they do, then project extension is necessary, otherwise,
11076 importing is sufficient.
11077
11078 @noindent
11079 In a project file that extends another project file, it is possible to
11080 indicate that an inherited source is not part of the sources of the extending
11081 project. This is necessary sometimes when a package spec has been overloaded
11082 and no longer requires a body: in this case, it is necessary to indicate that
11083 the inherited body is not part of the sources of the project, otherwise there
11084 will be a compilation error when compiling the spec.
11085
11086 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11087 Its value is a string list: a list of file names.
11088
11089 @smallexample @c @projectfile
11090 project B extends "a" is
11091    for Source_Files use ("pkg.ads");
11092    --  New spec of Pkg does not need a completion
11093    for Locally_Removed_Files use ("pkg.adb");
11094 end B;
11095 @end smallexample
11096
11097 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11098 is still needed: if it is possible to build using @code{gnatmake} when such
11099 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11100 it is possible to remove the source completely from a system that includes
11101 project P.
11102
11103 @c ***********************
11104 @c * Project File Syntax *
11105 @c ***********************
11106
11107 @node Project File Syntax
11108 @section Project File Syntax
11109
11110 @menu
11111 * Basic Syntax::
11112 * Packages::
11113 * Expressions::
11114 * String Types::
11115 * Variables::
11116 * Attributes::
11117 * Associative Array Attributes::
11118 * case Constructions::
11119 @end menu
11120
11121 @noindent
11122 This section describes the structure of project files.
11123
11124 A project may be an @emph{independent project}, entirely defined by a single
11125 project file. Any Ada source file in an independent project depends only
11126 on the predefined library and other Ada source files in the same project.
11127
11128 @noindent
11129 A project may also @dfn{depend on} other projects, in either or both of
11130 the following ways:
11131 @itemize @bullet
11132 @item It may import any number of projects
11133 @item It may extend at most one other project
11134 @end itemize
11135
11136 @noindent
11137 The dependence relation is a directed acyclic graph (the subgraph reflecting
11138 the ``extends'' relation is a tree).
11139
11140 A project's @dfn{immediate sources} are the source files directly defined by
11141 that project, either implicitly by residing in the project file's directory,
11142 or explicitly through any of the source-related attributes described below.
11143 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11144 of @var{proj} together with the immediate sources (unless overridden) of any
11145 project on which @var{proj} depends (either directly or indirectly).
11146
11147 @node Basic Syntax
11148 @subsection Basic Syntax
11149
11150 @noindent
11151 As seen in the earlier examples, project files have an Ada-like syntax.
11152 The minimal project file is:
11153 @smallexample @c projectfile
11154 @group
11155 project Empty is
11156
11157 end Empty;
11158 @end group
11159 @end smallexample
11160
11161 @noindent
11162 The identifier @code{Empty} is the name of the project.
11163 This project name must be present after the reserved
11164 word @code{end} at the end of the project file, followed by a semi-colon.
11165
11166 Any name in a project file, such as the project name or a variable name,
11167 has the same syntax as an Ada identifier.
11168
11169 The reserved words of project files are the Ada reserved words plus
11170 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11171 reserved words currently used in project file syntax are:
11172
11173 @itemize @bullet
11174 @item
11175 @code{case}
11176 @item
11177 @code{end}
11178 @item
11179 @code{for}
11180 @item
11181 @code{is}
11182 @item
11183 @code{others}
11184 @item
11185 @code{package}
11186 @item
11187 @code{renames}
11188 @item
11189 @code{type}
11190 @item
11191 @code{use}
11192 @item
11193 @code{when}
11194 @item
11195 @code{with}
11196 @end itemize
11197
11198 @noindent
11199 Comments in project files have the same syntax as in Ada, two consecutives
11200 hyphens through the end of the line.
11201
11202 @node Packages
11203 @subsection Packages
11204
11205 @noindent
11206 A project file may contain @emph{packages}. The name of a package must be one
11207 of the identifiers from the following list. A package
11208 with a given name may only appear once in a project file. Package names are
11209 case insensitive. The following package names are legal:
11210
11211 @itemize @bullet
11212 @item
11213 @code{Naming}
11214 @item
11215 @code{Builder}
11216 @item
11217 @code{Compiler}
11218 @item
11219 @code{Binder}
11220 @item
11221 @code{Linker}
11222 @item
11223 @code{Finder}
11224 @item
11225 @code{Cross_Reference}
11226 @item
11227 @code{Eliminate}
11228 @item
11229 @code{gnatls}
11230 @item
11231 @code{gnatstub}
11232 @item
11233 @code{IDE}
11234 @end itemize
11235
11236 @noindent
11237 In its simplest form, a package may be empty:
11238
11239 @smallexample @c projectfile
11240 @group
11241 project Simple is
11242   package Builder is
11243   end Builder;
11244 end Simple;
11245 @end group
11246 @end smallexample
11247
11248 @noindent
11249 A package may contain @emph{attribute declarations},
11250 @emph{variable declarations} and @emph{case constructions}, as will be
11251 described below.
11252
11253 When there is ambiguity between a project name and a package name,
11254 the name always designates the project. To avoid possible confusion, it is
11255 always a good idea to avoid naming a project with one of the
11256 names allowed for packages or any name that starts with @code{gnat}.
11257
11258 @node Expressions
11259 @subsection Expressions
11260
11261 @noindent
11262 An @emph{expression} is either a @emph{string expression} or a
11263 @emph{string list expression}.
11264
11265 A @emph{string expression} is either a @emph{simple string expression} or a
11266 @emph{compound string expression}.
11267
11268 A @emph{simple string expression} is one of the following:
11269 @itemize @bullet
11270 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11271 @item A string-valued variable reference (see @ref{Variables})
11272 @item A string-valued attribute reference (see @ref{Attributes})
11273 @item An external reference (see @ref{External References in Project Files})
11274 @end itemize
11275
11276 @noindent
11277 A @emph{compound string expression} is a concatenation of string expressions,
11278 using the operator @code{"&"}
11279 @smallexample
11280        Path & "/" & File_Name & ".ads"
11281 @end smallexample
11282
11283 @noindent
11284 A @emph{string list expression} is either a
11285 @emph{simple string list expression} or a
11286 @emph{compound string list expression}.
11287
11288 A @emph{simple string list expression} is one of the following:
11289 @itemize @bullet
11290 @item A parenthesized list of zero or more string expressions,
11291 separated by commas
11292 @smallexample
11293    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11294    Empty_List := ();
11295 @end smallexample
11296 @item A string list-valued variable reference
11297 @item A string list-valued attribute reference
11298 @end itemize
11299
11300 @noindent
11301 A @emph{compound string list expression} is the concatenation (using
11302 @code{"&"}) of a simple string list expression and an expression.  Note that
11303 each term in a compound string list expression, except the first, may be
11304 either a string expression or a string list expression.
11305
11306 @smallexample @c projectfile
11307 @group
11308    File_Name_List := () & File_Name; --  One string in this list
11309    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11310    --  Two strings
11311    Big_List := File_Name_List & Extended_File_Name_List;
11312    --  Concatenation of two string lists: three strings
11313    Illegal_List := "gnat.adc" & Extended_File_Name_List;
11314    --  Illegal: must start with a string list
11315 @end group
11316 @end smallexample
11317
11318 @node String Types
11319 @subsection String Types
11320
11321 @noindent
11322 A @emph{string type declaration} introduces a discrete set of string literals.
11323 If a string variable is declared to have this type, its value
11324 is restricted to the given set of literals.
11325
11326 Here is an example of a string type declaration:
11327
11328 @smallexample @c projectfile
11329    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11330 @end smallexample
11331
11332 @noindent
11333 Variables of a string type are called @emph{typed variables}; all other
11334 variables are called @emph{untyped variables}. Typed variables are
11335 particularly useful in @code{case} constructions, to support conditional
11336 attribute declarations.
11337 (see @ref{case Constructions}).
11338
11339 The string literals in the list are case sensitive and must all be different.
11340 They may include any graphic characters allowed in Ada, including spaces.
11341
11342 A string type may only be declared at the project level, not inside a package.
11343
11344 A string type may be referenced by its name if it has been declared in the same
11345 project file, or by an expanded name whose prefix is the name of the project
11346 in which it is declared.
11347
11348 @node Variables
11349 @subsection Variables
11350
11351 @noindent
11352 A variable may be declared at the project file level, or within a package.
11353 Here are some examples of variable declarations:
11354
11355 @smallexample @c projectfile
11356 @group
11357    This_OS : OS := external ("OS"); --  a typed variable declaration
11358    That_OS := "GNU/Linux";          --  an untyped variable declaration
11359 @end group
11360 @end smallexample
11361
11362 @noindent
11363 The syntax of a @emph{typed variable declaration} is identical to the Ada
11364 syntax for an object declaration. By contrast, the syntax of an untyped
11365 variable declaration is identical to an Ada assignment statement. In fact,
11366 variable declarations in project files have some of the characteristics of
11367 an assignment, in that successive declarations for the same variable are
11368 allowed. Untyped variable declarations do establish the expected kind of the
11369 variable (string or string list), and successive declarations for it must
11370 respect the initial kind.
11371
11372 @noindent
11373 A string variable declaration (typed or untyped) declares a variable
11374 whose value is a string. This variable may be used as a string expression.
11375 @smallexample @c projectfile
11376    File_Name       := "readme.txt";
11377    Saved_File_Name := File_Name & ".saved";
11378 @end smallexample
11379
11380 @noindent
11381 A string list variable declaration declares a variable whose value is a list
11382 of strings. The list may contain any number (zero or more) of strings.
11383
11384 @smallexample @c projectfile
11385    Empty_List := ();
11386    List_With_One_Element := ("^-gnaty^-gnaty^");
11387    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11388    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11389                  "pack2.ada", "util_.ada", "util.ada");
11390 @end smallexample
11391
11392 @noindent
11393 The same typed variable may not be declared more than once at project level,
11394 and it may not be declared more than once in any package; it is in effect
11395 a constant.
11396
11397 The same untyped variable may be declared several times. Declarations are
11398 elaborated in the order in which they appear, so  the new value replaces
11399 the old one, and any subsequent reference to the variable uses the new value.
11400 However, as noted above, if a variable has been declared as a string, all
11401 subsequent
11402 declarations must give it a string value. Similarly, if a variable has
11403 been declared as a string list, all subsequent declarations
11404 must give it a string list value.
11405
11406 A @emph{variable reference} may take several forms:
11407
11408 @itemize @bullet
11409 @item The simple variable name, for a variable in the current package (if any)
11410 or in the current project
11411 @item An expanded name, whose prefix is a context name.
11412 @end itemize
11413
11414 @noindent
11415 A @emph{context} may be one of the following:
11416
11417 @itemize @bullet
11418 @item The name of an existing package in the current project
11419 @item The name of an imported project of the current project
11420 @item The name of an ancestor project (i.e., a project extended by the current
11421 project, either directly or indirectly)
11422 @item An expanded name whose prefix is an imported/parent project name, and
11423 whose selector is a package name in that project.
11424 @end itemize
11425
11426 @noindent
11427 A variable reference may be used in an expression.
11428
11429 @node Attributes
11430 @subsection Attributes
11431
11432 @noindent
11433 A project (and its packages) may have @emph{attributes} that define
11434 the project's properties.  Some attributes have values that are strings;
11435 others have values that are string lists.
11436
11437 There are two categories of attributes: @emph{simple attributes}
11438 and @emph{associative arrays} (see @ref{Associative Array Attributes}).
11439
11440 Legal project attribute names, and attribute names for each legal package are
11441 listed below. Attributes names are case-insensitive.
11442
11443 The following attributes are defined on projects (all are simple attributes):
11444
11445 @multitable @columnfractions .4 .3
11446 @item @emph{Attribute Name}
11447 @tab @emph{Value}
11448 @item @code{Source_Files}
11449 @tab string list
11450 @item @code{Source_Dirs}
11451 @tab string list
11452 @item @code{Source_List_File}
11453 @tab string
11454 @item @code{Object_Dir}
11455 @tab string
11456 @item @code{Exec_Dir}
11457 @tab string
11458 @item @code{Locally_Removed_Files}
11459 @tab string list
11460 @item @code{Main}
11461 @tab string list
11462 @item @code{Languages}
11463 @tab string list
11464 @item @code{Main_Language}
11465 @tab string
11466 @item @code{Library_Dir}
11467 @tab string
11468 @item @code{Library_Name}
11469 @tab string
11470 @item @code{Library_Kind}
11471 @tab string
11472 @item @code{Library_Version}
11473 @tab string
11474 @item @code{Library_Interface}
11475 @tab string
11476 @item @code{Library_Auto_Init}
11477 @tab string
11478 @item @code{Library_Options}
11479 @tab string list
11480 @item @code{Library_GCC}
11481 @tab string
11482 @end multitable
11483
11484 @noindent
11485 The following attributes are defined for package  @code{Naming}
11486 (see @ref{Naming Schemes}):
11487
11488 @multitable @columnfractions .4 .2 .2 .2
11489 @item Attribute Name @tab Category @tab Index @tab Value
11490 @item @code{Spec_Suffix}
11491 @tab associative array
11492 @tab language name
11493 @tab string
11494 @item @code{Body_Suffix}
11495 @tab associative array
11496 @tab language name
11497 @tab string
11498 @item @code{Separate_Suffix}
11499 @tab simple attribute
11500 @tab n/a
11501 @tab string
11502 @item @code{Casing}
11503 @tab simple attribute
11504 @tab n/a
11505 @tab string
11506 @item @code{Dot_Replacement}
11507 @tab simple attribute
11508 @tab n/a
11509 @tab string
11510 @item @code{Spec}
11511 @tab associative array
11512 @tab Ada unit name
11513 @tab string
11514 @item @code{Body}
11515 @tab associative array
11516 @tab Ada unit name
11517 @tab string
11518 @item @code{Specification_Exceptions}
11519 @tab associative array
11520 @tab language name
11521 @tab string list
11522 @item @code{Implementation_Exceptions}
11523 @tab associative array
11524 @tab language name
11525 @tab string list
11526 @end multitable
11527
11528 @noindent
11529 The following attributes are defined for packages @code{Builder},
11530 @code{Compiler}, @code{Binder},
11531 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
11532 (see @ref{^Switches^Switches^ and Project Files}).
11533
11534 @multitable @columnfractions .4 .2 .2 .2
11535 @item Attribute Name @tab Category @tab Index @tab Value
11536 @item @code{^Default_Switches^Default_Switches^}
11537 @tab associative array
11538 @tab language name
11539 @tab string list
11540 @item @code{^Switches^Switches^}
11541 @tab associative array
11542 @tab file name
11543 @tab string list
11544 @end multitable
11545
11546 @noindent
11547 In addition, package @code{Compiler} has a single string attribute
11548 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11549 string attribute @code{Global_Configuration_Pragmas}.
11550
11551 @noindent
11552 Each simple attribute has a default value: the empty string (for string-valued
11553 attributes) and the empty list (for string list-valued attributes).
11554
11555 An attribute declaration defines a new value for an attribute.
11556
11557 Examples of simple attribute declarations:
11558
11559 @smallexample @c projectfile
11560    for Object_Dir use "objects";
11561    for Source_Dirs use ("units", "test/drivers");
11562 @end smallexample
11563
11564 @noindent
11565 The syntax of a @dfn{simple attribute declaration} is similar to that of an
11566 attribute definition clause in Ada.
11567
11568 Attributes references may be appear in expressions.
11569 The general form for such a reference is @code{<entity>'<attribute>}:
11570 Associative array attributes are functions. Associative
11571 array attribute references must have an argument that is a string literal.
11572
11573 Examples are:
11574
11575 @smallexample @c projectfile
11576   project'Object_Dir
11577   Naming'Dot_Replacement
11578   Imported_Project'Source_Dirs
11579   Imported_Project.Naming'Casing
11580   Builder'^Default_Switches^Default_Switches^("Ada")
11581 @end smallexample
11582
11583 @noindent
11584 The prefix of an attribute may be:
11585 @itemize @bullet
11586 @item @code{project} for an attribute of the current project
11587 @item The name of an existing package of the current project
11588 @item The name of an imported project
11589 @item The name of a parent project that is extended by the current project
11590 @item An expanded name whose prefix is imported/parent project name,
11591       and whose selector is a package name
11592 @end itemize
11593
11594 @noindent
11595 Example:
11596 @smallexample @c projectfile
11597 @group
11598    project Prj is
11599      for Source_Dirs use project'Source_Dirs & "units";
11600      for Source_Dirs use project'Source_Dirs & "test/drivers"
11601    end Prj;
11602 @end group
11603 @end smallexample
11604
11605 @noindent
11606 In the first attribute declaration, initially the attribute @code{Source_Dirs}
11607 has the default value: an empty string list. After this declaration,
11608 @code{Source_Dirs} is a string list of one element: @code{"units"}.
11609 After the second attribute declaration @code{Source_Dirs} is a string list of
11610 two elements: @code{"units"} and @code{"test/drivers"}.
11611
11612 Note: this example is for illustration only. In practice,
11613 the project file would contain only one attribute declaration:
11614
11615 @smallexample @c projectfile
11616    for Source_Dirs use ("units", "test/drivers");
11617 @end smallexample
11618
11619 @node Associative Array Attributes
11620 @subsection Associative Array Attributes
11621
11622 @noindent
11623 Some attributes are defined as @emph{associative arrays}. An associative
11624 array may be regarded as a function that takes a string as a parameter
11625 and delivers a string or string list value as its result.
11626
11627 Here are some examples of single associative array attribute associations:
11628
11629 @smallexample @c projectfile
11630    for Body ("main") use "Main.ada";
11631    for ^Switches^Switches^ ("main.ada")
11632        use ("^-v^-v^",
11633             "^-gnatv^-gnatv^");
11634    for ^Switches^Switches^ ("main.ada")
11635             use Builder'^Switches^Switches^ ("main.ada")
11636               & "^-g^-g^";
11637 @end smallexample
11638
11639 @noindent
11640 Like untyped variables and simple attributes, associative array attributes
11641 may be declared several times. Each declaration supplies a new value for the
11642 attribute, and replaces the previous setting.
11643
11644 @noindent
11645 An associative array attribute may be declared as a full associative array
11646 declaration, with the value of the same attribute in an imported or extended
11647 project.
11648
11649 @smallexample @c projectfile
11650    package Builder is
11651       for Default_Switches use Default.Builder'Default_Switches;
11652    end Builder;
11653 @end smallexample
11654
11655 @noindent
11656 In this example, @code{Default} must be either an project imported by the
11657 current project, or the project that the current project extends. If the
11658 attribute is in a package (in this case, in package @code{Builder}), the same
11659 package needs to be specified.
11660
11661 @noindent
11662 A full associative array declaration replaces any other declaration for the
11663 attribute, including other full associative array declaration. Single
11664 associative array associations may be declare after a full associative
11665 declaration, modifying the value for a single association of the attribute.
11666
11667 @node case Constructions
11668 @subsection @code{case} Constructions
11669
11670 @noindent
11671 A @code{case} construction is used in a project file to effect conditional
11672 behavior.
11673 Here is a typical example:
11674
11675 @smallexample @c projectfile
11676 @group
11677 project MyProj is
11678    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11679
11680    OS : OS_Type := external ("OS", "GNU/Linux");
11681 @end group
11682
11683 @group
11684    package Compiler is
11685      case OS is
11686        when "GNU/Linux" | "Unix" =>
11687          for ^Default_Switches^Default_Switches^ ("Ada")
11688              use ("^-gnath^-gnath^");
11689        when "NT" =>
11690          for ^Default_Switches^Default_Switches^ ("Ada")
11691              use ("^-gnatP^-gnatP^");
11692        when others =>
11693      end case;
11694    end Compiler;
11695 end MyProj;
11696 @end group
11697 @end smallexample
11698
11699 @noindent
11700 The syntax of a @code{case} construction is based on the Ada case statement
11701 (although there is no @code{null} construction for empty alternatives).
11702
11703 The case expression must a typed string variable.
11704 Each alternative comprises the reserved word @code{when}, either a list of
11705 literal strings separated by the @code{"|"} character or the reserved word
11706 @code{others},  and the @code{"=>"} token.
11707 Each literal string must belong to the string type that is the type of the
11708 case variable.
11709 An @code{others} alternative, if present, must occur last.
11710
11711 After each @code{=>}, there are zero or more constructions.  The only
11712 constructions allowed in a case construction are other case constructions and
11713 attribute declarations. String type declarations, variable declarations and
11714 package declarations are not allowed.
11715
11716 The value of the case variable is often given by an external reference
11717 (see @ref{External References in Project Files}).
11718
11719 @c ****************************************
11720 @c * Objects and Sources in Project Files *
11721 @c ****************************************
11722
11723 @node Objects and Sources in Project Files
11724 @section Objects and Sources in Project Files
11725
11726 @menu
11727 * Object Directory::
11728 * Exec Directory::
11729 * Source Directories::
11730 * Source File Names::
11731 @end menu
11732
11733 @noindent
11734 Each project has exactly one object directory and one or more source
11735 directories. The source directories must contain at least one source file,
11736 unless  the project file explicitly specifies that no source files are present
11737 (see @ref{Source File Names}).
11738
11739 @node Object Directory
11740 @subsection Object Directory
11741
11742 @noindent
11743 The object directory for a project is the directory containing the compiler's
11744 output (such as @file{ALI} files and object files) for the project's immediate
11745 sources.
11746
11747 The object directory is given by the value of the attribute @code{Object_Dir}
11748 in the project file.
11749
11750 @smallexample @c projectfile
11751    for Object_Dir use "objects";
11752 @end smallexample
11753
11754 @noindent
11755 The attribute @var{Object_Dir} has a string value, the path name of the object
11756 directory. The path name may be absolute or relative to the directory of the
11757 project file. This directory must already exist, and be readable and writable.
11758
11759 By default, when the attribute @code{Object_Dir} is not given an explicit value
11760 or when its value is the empty string, the object directory is the same as the
11761 directory containing the project file.
11762
11763 @node Exec Directory
11764 @subsection Exec Directory
11765
11766 @noindent
11767 The exec directory for a project is the directory containing the executables
11768 for the project's main subprograms.
11769
11770 The exec directory is given by the value of the attribute @code{Exec_Dir}
11771 in the project file.
11772
11773 @smallexample @c projectfile
11774    for Exec_Dir use "executables";
11775 @end smallexample
11776
11777 @noindent
11778 The attribute @var{Exec_Dir} has a string value, the path name of the exec
11779 directory. The path name may be absolute or relative to the directory of the
11780 project file. This directory must already exist, and be writable.
11781
11782 By default, when the attribute @code{Exec_Dir} is not given an explicit value
11783 or when its value is the empty string, the exec directory is the same as the
11784 object directory of the project file.
11785
11786 @node Source Directories
11787 @subsection Source Directories
11788
11789 @noindent
11790 The source directories of a project are specified by the project file
11791 attribute @code{Source_Dirs}.
11792
11793 This attribute's value is a string list. If the attribute is not given an
11794 explicit value, then there is only one source directory, the one where the
11795 project file resides.
11796
11797 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
11798 as in
11799
11800 @smallexample @c projectfile
11801     for Source_Dirs use ();
11802 @end smallexample
11803
11804 @noindent
11805 indicates that the project contains no source files.
11806
11807 Otherwise, each string in the string list designates one or more
11808 source directories.
11809
11810 @smallexample @c projectfile
11811    for Source_Dirs use ("sources", "test/drivers");
11812 @end smallexample
11813
11814 @noindent
11815 If a string in the list ends with @code{"/**"},  then the directory whose path
11816 name precedes the two asterisks, as well as all its subdirectories
11817 (recursively), are source directories.
11818
11819 @smallexample @c projectfile
11820    for Source_Dirs use ("/system/sources/**");
11821 @end smallexample
11822
11823 @noindent
11824 Here the directory @code{/system/sources} and all of its subdirectories
11825 (recursively) are source directories.
11826
11827 To specify that the source directories are the directory of the project file
11828 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
11829 @smallexample @c projectfile
11830    for Source_Dirs use ("./**");
11831 @end smallexample
11832
11833 @noindent
11834 Each of the source directories must exist and be readable.
11835
11836 @node Source File Names
11837 @subsection Source File Names
11838
11839 @noindent
11840 In a project that contains source files, their names may be specified by the
11841 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
11842 (a string). Source file names never include any directory information.
11843
11844 If the attribute @code{Source_Files} is given an explicit value, then each
11845 element of the list is a source file name.
11846
11847 @smallexample @c projectfile
11848    for Source_Files use ("main.adb");
11849    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
11850 @end smallexample
11851
11852 @noindent
11853 If the attribute @code{Source_Files} is not given an explicit value,
11854 but the attribute @code{Source_List_File} is given a string value,
11855 then the source file names are contained in the text file whose path name
11856 (absolute or relative to the directory of the project file) is the
11857 value of the attribute @code{Source_List_File}.
11858
11859 Each line in the file that is not empty or is not a comment
11860 contains a source file name.
11861
11862 @smallexample @c projectfile
11863    for Source_List_File use "source_list.txt";
11864 @end smallexample
11865
11866 @noindent
11867 By default, if neither the attribute @code{Source_Files} nor the attribute
11868 @code{Source_List_File} is given an explicit value, then each file in the
11869 source directories that conforms to the project's naming scheme
11870 (see @ref{Naming Schemes}) is an immediate source of the project.
11871
11872 A warning is issued if both attributes @code{Source_Files} and
11873 @code{Source_List_File} are given explicit values. In this case, the attribute
11874 @code{Source_Files} prevails.
11875
11876 Each source file name must be the name of one existing source file
11877 in one of the source directories.
11878
11879 A @code{Source_Files} attribute whose value is an empty list
11880 indicates that there are no source files in the project.
11881
11882 If the order of the source directories is known statically, that is if
11883 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
11884 be several files with the same source file name. In this case, only the file
11885 in the first directory is considered as an immediate source of the project
11886 file. If the order of the source directories is not known statically, it is
11887 an error to have several files with the same source file name.
11888
11889 Projects can be specified to have no Ada source
11890 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
11891 list, or the @code{"Ada"} may be absent from @code{Languages}:
11892
11893 @smallexample @c projectfile
11894    for Source_Dirs use ();
11895    for Source_Files use ();
11896    for Languages use ("C", "C++");
11897 @end smallexample
11898
11899 @noindent
11900 Otherwise, a project must contain at least one immediate source.
11901
11902 Projects with no source files are useful as template packages
11903 (see @ref{Packages in Project Files}) for other projects; in particular to
11904 define a package @code{Naming} (see @ref{Naming Schemes}).
11905
11906 @c ****************************
11907 @c * Importing Projects *
11908 @c ****************************
11909
11910 @node  Importing Projects
11911 @section Importing Projects
11912
11913 @noindent
11914 An immediate source of a project P may depend on source files that
11915 are neither immediate sources of P nor in the predefined library.
11916 To get this effect, P must @emph{import} the projects that contain the needed
11917 source files.
11918
11919 @smallexample @c projectfile
11920 @group
11921   with "project1", "utilities.gpr";
11922   with "/namings/apex.gpr";
11923   project Main is
11924     ...
11925 @end group
11926 @end smallexample
11927
11928 @noindent
11929 As can be seen in this example, the syntax for importing projects is similar
11930 to the syntax for importing compilation units in Ada. However, project files
11931 use literal strings instead of names, and the @code{with} clause identifies
11932 project files rather than packages.
11933
11934 Each literal string is the file name or path name (absolute or relative) of a
11935 project file. If a string is simply a file name, with no path, then its
11936 location is determined by the @emph{project path}:
11937
11938 @itemize @bullet
11939 @item
11940 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} exists,
11941 then the project path includes all the directories in this
11942 ^environment variable^logical name^, plus the directory of the project file.
11943
11944 @item
11945 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} does not
11946 exist, then the project path contains only one directory, namely the one where
11947 the project file is located.
11948 @end itemize
11949
11950 @noindent
11951 If a relative pathname is used, as in
11952
11953 @smallexample @c projectfile
11954   with "tests/proj";
11955 @end smallexample
11956
11957 @noindent
11958 then the path is relative to the directory where the importing project file is
11959 located. Any symbolic link will be fully resolved in the directory
11960 of the importing project file before the imported project file is examined.
11961
11962 If the @code{with}'ed project file name does not have an extension,
11963 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
11964 then the file name as specified in the @code{with} clause (no extension) will
11965 be used. In the above example, if a file @code{project1.gpr} is found, then it
11966 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
11967 then it will be used; if neither file exists, this is an error.
11968
11969 A warning is issued if the name of the project file does not match the
11970 name of the project; this check is case insensitive.
11971
11972 Any source file that is an immediate source of the imported project can be
11973 used by the immediate sources of the importing project, transitively. Thus
11974 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
11975 sources of @code{A} may depend on the immediate sources of @code{C}, even if
11976 @code{A} does not import @code{C} explicitly. However, this is not recommended,
11977 because if and when @code{B} ceases to import @code{C}, some sources in
11978 @code{A} will no longer compile.
11979
11980 A side effect of this capability is that normally cyclic dependencies are not
11981 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
11982 is not allowed to import @code{A}. However, there are cases when cyclic
11983 dependencies would be beneficial. For these cases, another form of import
11984 between projects exists, the @code{limited with}: a project @code{A} that
11985 imports a project @code{B} with a straigh @code{with} may also be imported,
11986 directly or indirectly, by @code{B} on the condition that imports from @code{B}
11987 to @code{A} include at least one @code{limited with}.
11988
11989 @smallexample @c 0projectfile
11990 with "../b/b.gpr";
11991 with "../c/c.gpr";
11992 project A is
11993 end A;
11994
11995 limited with "../a/a.gpr";
11996 project B is
11997 end B;
11998
11999 with "../d/d.gpr";
12000 project C is
12001 end C;
12002
12003 limited with "../a/a.gpr";
12004 project D is
12005 end D;
12006 @end smallexample
12007
12008 @noindent
12009 In the above legal example, there are two project cycles:
12010 @itemize @bullet
12011 @item A-> B-> A
12012 @item A -> C -> D -> A
12013 @end itemize
12014
12015 @noindent
12016 In each of these cycle there is one @code{limited with}: import of @code{A}
12017 from @code{B} and import of @code{A} from @code{D}.
12018
12019 The difference between straight @code{with} and @code{limited with} is that
12020 the name of a project imported with a @code{limited with} cannot be used in the
12021 project that imports it. In particular, its packages cannot be renamed and
12022 its variables cannot be referred to.
12023
12024 An exception to the above rules for @code{limited with} is that for the main
12025 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12026 @code{limited with} is equivalent to a straight @code{with}. For example,
12027 in the example above, projects @code{B} and @code{D} could not be main
12028 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12029 each have a @code{limited with} that is the only one in a cycle of importing
12030 projects.
12031
12032 @c *********************
12033 @c * Project Extension *
12034 @c *********************
12035
12036 @node Project Extension
12037 @section Project Extension
12038
12039 @noindent
12040 During development of a large system, it is sometimes necessary to use
12041 modified versions of some of the source files, without changing the original
12042 sources. This can be achieved through the @emph{project extension} facility.
12043
12044 @smallexample @c projectfile
12045    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12046 @end smallexample
12047
12048 @noindent
12049 A project extension declaration introduces an extending project
12050 (the @emph{child}) and a project being extended (the @emph{parent}).
12051
12052 By default, a child project inherits all the sources of its parent.
12053 However, inherited sources can be overridden: a unit in a parent is hidden
12054 by a unit of the same name in the child.
12055
12056 Inherited sources are considered to be sources (but not immediate sources)
12057 of the child project; see @ref{Project File Syntax}.
12058
12059 An inherited source file retains any switches specified in the parent project.
12060
12061 For example if the project @code{Utilities} contains the specification and the
12062 body of an Ada package @code{Util_IO}, then the project
12063 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12064 The original body of @code{Util_IO} will not be considered in program builds.
12065 However, the package specification will still be found in the project
12066 @code{Utilities}.
12067
12068 A child project can have only one parent but it may import any number of other
12069 projects.
12070
12071 A project is not allowed to import directly or indirectly at the same time a
12072 child project and any of its ancestors.
12073
12074 @c ****************************************
12075 @c * External References in Project Files *
12076 @c ****************************************
12077
12078 @node  External References in Project Files
12079 @section External References in Project Files
12080
12081 @noindent
12082 A project file may contain references to external variables; such references
12083 are called @emph{external references}.
12084
12085 An external variable is either defined as part of the environment (an
12086 environment variable in Unix, for example) or else specified on the command
12087 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12088 If both, then the command line value is used.
12089
12090 The value of an external reference is obtained by means of the built-in
12091 function @code{external}, which returns a string value.
12092 This function has two forms:
12093 @itemize @bullet
12094 @item @code{external (external_variable_name)}
12095 @item @code{external (external_variable_name, default_value)}
12096 @end itemize
12097
12098 @noindent
12099 Each parameter must be a string literal.  For example:
12100
12101 @smallexample @c projectfile
12102    external ("USER")
12103    external ("OS", "GNU/Linux")
12104 @end smallexample
12105
12106 @noindent
12107 In the form with one parameter, the function returns the value of
12108 the external variable given as parameter. If this name is not present in the
12109 environment, the function returns an empty string.
12110
12111 In the form with two string parameters, the second argument is
12112 the value returned when the variable given as the first argument is not
12113 present in the environment. In the example above, if @code{"OS"} is not
12114 the name of ^an environment variable^a logical name^ and is not passed on
12115 the command line, then the returned value is @code{"GNU/Linux"}.
12116
12117 An external reference may be part of a string expression or of a string
12118 list expression, and can therefore appear in a variable declaration or
12119 an attribute declaration.
12120
12121 @smallexample @c projectfile
12122 @group
12123    type Mode_Type is ("Debug", "Release");
12124    Mode : Mode_Type := external ("MODE");
12125    case Mode is
12126      when "Debug" =>
12127         ...
12128 @end group
12129 @end smallexample
12130
12131 @c *****************************
12132 @c * Packages in Project Files *
12133 @c *****************************
12134
12135 @node  Packages in Project Files
12136 @section Packages in Project Files
12137
12138 @noindent
12139 A @emph{package} defines the settings for project-aware tools within a
12140 project.
12141 For each such tool one can declare a package; the names for these
12142 packages are preset (see @ref{Packages}).
12143 A package may contain variable declarations, attribute declarations, and case
12144 constructions.
12145
12146 @smallexample @c projectfile
12147 @group
12148    project Proj is
12149       package Builder is  -- used by gnatmake
12150          for ^Default_Switches^Default_Switches^ ("Ada")
12151              use ("^-v^-v^",
12152                   "^-g^-g^");
12153       end Builder;
12154    end Proj;
12155 @end group
12156 @end smallexample
12157
12158 @noindent
12159 The syntax of package declarations mimics that of package in Ada.
12160
12161 Most of the packages have an attribute
12162 @code{^Default_Switches^Default_Switches^}.
12163 This attribute is an associative array, and its value is a string list.
12164 The index of the associative array is the name of a programming language (case
12165 insensitive). This attribute indicates the ^switch^switch^
12166 or ^switches^switches^ to be used
12167 with the corresponding tool.
12168
12169 Some packages also have another attribute, @code{^Switches^Switches^},
12170 an associative array whose value is a string list.
12171 The index is the name of a source file.
12172 This attribute indicates the ^switch^switch^
12173 or ^switches^switches^ to be used by the corresponding
12174 tool when dealing with this specific file.
12175
12176 Further information on these ^switch^switch^-related attributes is found in
12177 @ref{^Switches^Switches^ and Project Files}.
12178
12179 A package may be declared as a @emph{renaming} of another package; e.g., from
12180 the project file for an imported project.
12181
12182 @smallexample @c projectfile
12183 @group
12184   with "/global/apex.gpr";
12185   project Example is
12186     package Naming renames Apex.Naming;
12187     ...
12188   end Example;
12189 @end group
12190 @end smallexample
12191
12192 @noindent
12193 Packages that are renamed in other project files often come from project files
12194 that have no sources: they are just used as templates. Any modification in the
12195 template will be reflected automatically in all the project files that rename
12196 a package from the template.
12197
12198 In addition to the tool-oriented packages, you can also declare a package
12199 named @code{Naming} to establish specialized source file naming conventions
12200 (see @ref{Naming Schemes}).
12201
12202 @c ************************************
12203 @c * Variables from Imported Projects *
12204 @c ************************************
12205
12206 @node Variables from Imported Projects
12207 @section Variables from Imported Projects
12208
12209 @noindent
12210 An attribute or variable defined in an imported or parent project can
12211 be used in expressions in the importing / extending project.
12212 Such an attribute or variable is denoted by an expanded name whose prefix
12213 is either the name of the project or the expanded name of a package within
12214 a project.
12215
12216 @smallexample @c projectfile
12217 @group
12218   with "imported";
12219   project Main extends "base" is
12220      Var1 := Imported.Var;
12221      Var2 := Base.Var & ".new";
12222 @end group
12223
12224 @group
12225      package Builder is
12226         for ^Default_Switches^Default_Switches^ ("Ada")
12227             use Imported.Builder.Ada_^Switches^Switches^ &
12228                 "^-gnatg^-gnatg^" &
12229                 "^-v^-v^";
12230      end Builder;
12231 @end group
12232
12233 @group
12234      package Compiler is
12235         for ^Default_Switches^Default_Switches^ ("Ada")
12236             use Base.Compiler.Ada_^Switches^Switches^;
12237      end Compiler;
12238   end Main;
12239 @end group
12240 @end smallexample
12241
12242 @noindent
12243 In this example:
12244
12245 @itemize @bullet
12246 @item
12247 The value of @code{Var1} is a copy of the variable @code{Var} defined
12248 in the project file @file{"imported.gpr"}
12249 @item
12250 the value of @code{Var2} is a copy of the value of variable @code{Var}
12251 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12252 @item
12253 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12254 @code{Builder} is a string list that includes in its value a copy of the value
12255 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12256 in project file @file{imported.gpr} plus two new elements:
12257 @option{"^-gnatg^-gnatg^"}
12258 and @option{"^-v^-v^"};
12259 @item
12260 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12261 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12262 defined in the @code{Compiler} package in project file @file{base.gpr},
12263 the project being extended.
12264 @end itemize
12265
12266 @c ******************
12267 @c * Naming Schemes *
12268 @c ******************
12269
12270 @node  Naming Schemes
12271 @section Naming Schemes
12272
12273 @noindent
12274 Sometimes an Ada software system is ported from a foreign compilation
12275 environment to GNAT, and the file names do not use the default GNAT
12276 conventions. Instead of changing all the file names (which for a variety
12277 of reasons might not be possible), you can define the relevant file
12278 naming scheme in the @code{Naming} package in your project file.
12279
12280 @noindent
12281 Note that the use of pragmas described in @ref{Alternative
12282 File Naming Schemes} by mean of a configuration pragmas file is not
12283 supported when using project files. You must use the features described
12284 in this paragraph. You can however use specify other configuration
12285 pragmas (see @ref{Specifying Configuration Pragmas}).
12286
12287 @ifclear vms
12288 For example, the following
12289 package models the Apex file naming rules:
12290
12291 @smallexample @c projectfile
12292 @group
12293   package Naming is
12294     for Casing               use "lowercase";
12295     for Dot_Replacement      use ".";
12296     for Spec_Suffix ("Ada")  use ".1.ada";
12297     for Body_Suffix ("Ada")  use ".2.ada";
12298   end Naming;
12299 @end group
12300 @end smallexample
12301 @end ifclear
12302
12303 @ifset vms
12304 For example, the following package models the DEC Ada file naming rules:
12305
12306 @smallexample @c projectfile
12307 @group
12308   package Naming is
12309     for Casing               use "lowercase";
12310     for Dot_Replacement      use "__";
12311     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12312     for Body_Suffix ("Ada")  use ".^ada^ada^";
12313   end Naming;
12314 @end group
12315 @end smallexample
12316
12317 @noindent
12318 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12319 names in lower case)
12320 @end ifset
12321
12322 @noindent
12323 You can define the following attributes in package @code{Naming}:
12324
12325 @table @code
12326
12327 @item @var{Casing}
12328 This must be a string with one of the three values @code{"lowercase"},
12329 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12330
12331 @noindent
12332 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12333
12334 @item @var{Dot_Replacement}
12335 This must be a string whose value satisfies the following conditions:
12336
12337 @itemize @bullet
12338 @item It must not be empty
12339 @item It cannot start or end with an alphanumeric character
12340 @item It cannot be a single underscore
12341 @item It cannot start with an underscore followed by an alphanumeric
12342 @item It cannot contain a dot @code{'.'} except if the entire string
12343 is @code{"."}
12344 @end itemize
12345
12346 @noindent
12347 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12348
12349 @item @var{Spec_Suffix}
12350 This is an associative array (indexed by the programming language name, case
12351 insensitive) whose value is a string that must satisfy the following
12352 conditions:
12353
12354 @itemize @bullet
12355 @item It must not be empty
12356 @item It must include at least one dot
12357 @end itemize
12358 @noindent
12359 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12360 @code{"^.ads^.ADS^"}.
12361
12362 @item @var{Body_Suffix}
12363 This is an associative array (indexed by the programming language name, case
12364 insensitive) whose value is a string that must satisfy the following
12365 conditions:
12366
12367 @itemize @bullet
12368 @item It must not be empty
12369 @item It must include at least one dot
12370 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12371 @end itemize
12372 @noindent
12373 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12374 @code{"^.adb^.ADB^"}.
12375
12376 @item @var{Separate_Suffix}
12377 This must be a string whose value satisfies the same conditions as
12378 @code{Body_Suffix}.
12379
12380 @noindent
12381 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12382 value as @code{Body_Suffix ("Ada")}.
12383
12384 @item @var{Spec}
12385 @noindent
12386 You can use the associative array attribute @code{Spec}  to define
12387 the source file name for an individual Ada compilation unit's spec. The array
12388 index must be a string literal that identifies the Ada unit (case insensitive).
12389 The value of this attribute must be a string that identifies the file that
12390 contains this unit's spec (case sensitive or insensitive depending on the
12391 operating system).
12392
12393 @smallexample @c projectfile
12394    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12395 @end smallexample
12396
12397 @item @var{Body}
12398
12399 You can use the associative array attribute @code{Body} to
12400 define the source file name for an individual Ada compilation unit's body
12401 (possibly a subunit).  The array index must be a string literal that identifies
12402 the Ada unit (case insensitive).  The value of this attribute must be a string
12403 that identifies the file that contains this unit's body or subunit (case
12404 sensitive or insensitive depending on the operating system).
12405
12406 @smallexample @c projectfile
12407    for Body ("MyPack.MyChild") use "mypack.mychild.body";
12408 @end smallexample
12409 @end table
12410
12411 @c ********************
12412 @c * Library Projects *
12413 @c ********************
12414
12415 @node Library Projects
12416 @section Library Projects
12417
12418 @noindent
12419 @emph{Library projects} are projects whose object code is placed in a library.
12420 (Note that this facility is not yet supported on all platforms)
12421
12422 To create a library project, you need to define in its project file
12423 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12424 Additionally, you may define the library-related attributes
12425 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12426 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12427
12428 The @code{Library_Name} attribute has a string value. There is no restriction
12429 on the name of a library. It is the responsability of the developer to
12430 choose a name that will be accepted by the platform. It is recommanded to
12431 choose names that could be Ada identifiers; such names are almost guaranteed
12432 to be acceptable on all platforms.
12433
12434 The @code{Library_Dir} attribute has a string value that designates the path
12435 (absolute or relative) of the directory where the library will reside.
12436 It must designate an existing directory, and this directory must be
12437 different from the project's object directory. It also needs to be writable.
12438
12439 If both @code{Library_Name} and @code{Library_Dir} are specified and
12440 are legal, then the project file defines a library project.  The optional
12441 library-related attributes are checked only for such project files.
12442
12443 The @code{Library_Kind} attribute has a string value that must be one of the
12444 following (case insensitive): @code{"static"}, @code{"dynamic"} or
12445 @code{"relocatable"}. If this attribute is not specified, the library is a
12446 static library, that is an archive of object files that can be potentially
12447 linked into an static executable. Otherwise, the library may be dynamic or
12448 relocatable, that is a library that is loaded only at the start of execution.
12449 Depending on the operating system, there may or may not be a distinction
12450 between dynamic and relocatable libraries. For Unix and VMS Unix there is no
12451 such distinction.
12452
12453 If you need to build both a static and a dynamic library, you should use two
12454 different object directories, since in some cases some extra code needs to
12455 be generated for the latter. For such cases, it is recommended to either use
12456 two different project files, or a single one which uses external variables
12457 to indicate what kind of library should be build.
12458
12459 The @code{Library_Version} attribute has a string value whose interpretation
12460 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12461 used only for dynamic/relocatable libraries as the internal name of the
12462 library (the @code{"soname"}). If the library file name (built from the
12463 @code{Library_Name}) is different from the @code{Library_Version}, then the
12464 library file will be a symbolic link to the actual file whose name will be
12465 @code{Library_Version}.
12466
12467 Example (on Unix):
12468
12469 @smallexample @c projectfile
12470 @group
12471 project Plib is
12472
12473    Version := "1";
12474
12475    for Library_Dir use "lib_dir";
12476    for Library_Name use "dummy";
12477    for Library_Kind use "relocatable";
12478    for Library_Version use "libdummy.so." & Version;
12479
12480 end Plib;
12481 @end group
12482 @end smallexample
12483
12484 @noindent
12485 Directory @file{lib_dir} will contain the internal library file whose name
12486 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12487 @file{libdummy.so.1}.
12488
12489 When @command{gnatmake} detects that a project file
12490 is a library project file, it will check all immediate sources of the project
12491 and rebuild the library if any of the sources have been recompiled.
12492
12493 Standard project files can import library project files. In such cases,
12494 the libraries will only be rebuild if some of its sources are recompiled
12495 because they are in the closure of some other source in an importing project.
12496 Sources of the library project files that are not in such a closure will
12497 not be checked, unless the full library is checked, because one of its sources
12498 needs to be recompiled.
12499
12500 For instance, assume the project file @code{A} imports the library project file
12501 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
12502 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
12503 @file{l2.ads}, @file{l2.adb}.
12504
12505 If @file{l1.adb} has been modified, then the library associated with @code{L}
12506 will be rebuild when compiling all the immediate sources of @code{A} only
12507 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
12508 @code{"with L1;"}.
12509
12510 To be sure that all the sources in the library associated with @code{L} are
12511 up to date, and that all the sources of parject @code{A} are also up to date,
12512 the following two commands needs to be used:
12513
12514 @smallexample
12515 gnatmake -Pl.gpr
12516 gnatmake -Pa.gpr
12517 @end smallexample
12518
12519 When a library is built or rebuilt, an attempt is made first to delete all
12520 files in the library directory.
12521 All @file{ALI} files will also be copied from the object directory to the
12522 library directory. To build executables, @command{gnatmake} will use the
12523 library rather than the individual object files.
12524
12525
12526 @c **********************************************
12527 @c * Using Third-Party Libraries through Projects
12528 @c **********************************************
12529 @node Using Third-Party Libraries through Projects
12530 @section Using Third-Party Libraries through Projects
12531
12532 Whether you are exporting your own library to make it available to
12533 clients, or you are using a library provided by a third party, it is
12534 convenient to have project files that automatically set the correct
12535 command line switches for the compiler and linker.
12536
12537 Such project files are very similar to the library project files;
12538 @xref{Library Projects}. The only difference is that you set the
12539 @code{Source_Dirs} and @code{Object_Dir} attribute so that they point to the
12540 directories where, respectively, the sources and the read-only ALI files have
12541 been installed.
12542
12543 If you need to interface with a set of libraries, as opposed to a
12544 single one, you need to create one library project for each of the
12545 libraries. In addition, a top-level project that imports all these
12546 library projects should be provided, so that the user of your library
12547 has a single @code{with} clause to add to his own projects.
12548
12549 For instance, let's assume you are providing two static libraries
12550 @file{liba.a} and @file{libb.a}. The user needs to link with
12551 both of these libraries. Each of these is associated with its
12552 own set of header files. Let's assume furthermore that all the
12553 header files for the two libraries have been installed in the same
12554 directory @file{headers}. The @file{ALI} files are found in the same
12555 @file{headers} directory.
12556
12557 In this case, you should provide the following three projects:
12558
12559 @smallexample @c projectfile
12560 @group
12561 with "liba", "libb";
12562 project My_Library is
12563   for Source_Dirs use ("headers");
12564   for Object_Dir  use "headers";
12565 end My_Library;
12566 @end group
12567
12568 @group
12569 project Liba is
12570    for Source_Dirs use ();
12571    for Library_Dir use "lib";
12572    for Library_Name use "a";
12573    for Library_Kind use "static";
12574 end Liba;
12575 @end group
12576
12577 @group
12578 project Libb is
12579    for Source_Dirs use ();
12580    for Library_Dir use "lib";
12581    for Library_Name use "b";
12582    for Library_Kind use "static";
12583 end Libb;
12584 @end group
12585 @end smallexample
12586
12587 @c *******************************
12588 @c * Stand-alone Library Projects *
12589 @c *******************************
12590
12591 @node Stand-alone Library Projects
12592 @section Stand-alone Library Projects
12593
12594 @noindent
12595 A Stand-alone Library is a library that contains the necessary code to
12596 elaborate the Ada units that are included in the library. A Stand-alone
12597 Library is suitable to be used in an executable when the main is not
12598 in Ada. However, Stand-alone Libraries may also be used with an Ada main
12599 subprogram.
12600
12601 A Stand-alone Library Project is a Library Project where the library is
12602 a Stand-alone Library.
12603
12604 To be a Stand-alone Library Project, in addition to the two attributes
12605 that make a project a Library Project (@code{Library_Name} and
12606 @code{Library_Dir}, see @ref{Library Projects}), the attribute
12607 @code{Library_Interface} must be defined.
12608
12609 @smallexample @c projectfile
12610 @group
12611    for Library_Dir use "lib_dir";
12612    for Library_Name use "dummy";
12613    for Library_Interface use ("int1", "int1.child");
12614 @end group
12615 @end smallexample
12616
12617 Attribute @code{Library_Interface} has a non empty string list value,
12618 each string in the list designating a unit contained in an immediate source
12619 of the project file.
12620
12621 When a Stand-alone Library is built, first the binder is invoked to build
12622 a package whose name depends on the library name
12623 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12624 This binder-generated package includes initialization and
12625 finalization procedures whose
12626 names depend on the library name (dummyinit and dummyfinal in the example
12627 above). The object corresponding to this package is included in the library.
12628
12629 A dynamic or relocatable Stand-alone Library is automatically initialized
12630 if automatic initialization of Stand-alone Libraries is supported on the
12631 platform and if attribute @code{Library_Auto_Init} is not specified or
12632 is specified with the value "true". A static Stand-alone Library is never
12633 automatically initialized.
12634
12635 Single string attribute @code{Library_Auto_Init} may be specified with only
12636 two possible values: "false" or "true" (case-insensitive). Specifying
12637 "false" for attribute @code{Library_Auto_Init} will prevent automatic
12638 initialization of dynamic or relocatable libraries.
12639
12640 When a non automatically initialized Stand-alone Library is used
12641 in an executable, its initialization procedure must be called before
12642 any service of the library is used.
12643 When the main subprogram is in Ada, it may mean that the initialization
12644 procedure has to be called during elaboration of another package.
12645
12646 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12647 (those that are listed in attribute @code{Library_Interface}) are copied to
12648 the Library Directory. As a consequence, only the Interface Units may be
12649 imported from Ada units outside of the library. If other units are imported,
12650 the binding phase will fail.
12651
12652 When a Stand-Alone Library is bound, the switches that are specified in
12653 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12654 used in the call to @command{gnatbind}.
12655
12656 The string list attribute @code{Library_Options} may be used to specified
12657 additional switches to the call to @command{gcc} to link the library.
12658
12659 The attribute @code{Library_Src_Dir}, may be specified for a
12660 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12661 single string value. Its value must be the path (absolute or relative to the
12662 project directory) of an existing directory. This directory cannot be the
12663 object directory or one of the source directories, but it can be the same as
12664 the library directory. The sources of the Interface
12665 Units of the library, necessary to an Ada client of the library, will be
12666 copied to the designated directory, called Interface Copy directory.
12667 These sources includes the specs of the Interface Units, but they may also
12668 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12669 are used, or when there is a generic units in the spec. Before the sources
12670 are copied to the Interface Copy directory, an attempt is made to delete all
12671 files in the Interface Copy directory.
12672
12673 @c *************************************
12674 @c * Switches Related to Project Files *
12675 @c *************************************
12676 @node Switches Related to Project Files
12677 @section Switches Related to Project Files
12678
12679 @noindent
12680 The following switches are used by GNAT tools that support project files:
12681
12682 @table @option
12683
12684 @item ^-P^/PROJECT_FILE=^@var{project}
12685 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12686 Indicates the name of a project file. This project file will be parsed with
12687 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12688 if any, and using the external references indicated
12689 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12690 @ifclear vms
12691 There may zero, one or more spaces between @option{-P} and @var{project}.
12692 @end ifclear
12693
12694 @noindent
12695 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12696
12697 @noindent
12698 Since the Project Manager parses the project file only after all the switches
12699 on the command line are checked, the order of the switches
12700 @option{^-P^/PROJECT_FILE^},
12701 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12702 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12703
12704 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12705 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12706 Indicates that external variable @var{name} has the value @var{value}.
12707 The Project Manager will use this value for occurrences of
12708 @code{external(name)} when parsing the project file.
12709
12710 @ifclear vms
12711 @noindent
12712 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12713 put between quotes.
12714 @smallexample
12715   -XOS=NT
12716   -X"user=John Doe"
12717 @end smallexample
12718 @end ifclear
12719
12720 @noindent
12721 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12722 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12723 @var{name}, only the last one is used.
12724
12725 @noindent
12726 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12727 takes precedence over the value of the same name in the environment.
12728
12729 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12730 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
12731 @c Previous line uses code vs option command, to stay less than 80 chars
12732 Indicates the verbosity of the parsing of GNAT project files.
12733
12734 @ifclear vms
12735 @option{-vP0} means Default;
12736 @option{-vP1} means Medium;
12737 @option{-vP2} means High.
12738 @end ifclear
12739
12740 @ifset vms
12741 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12742 HIGH.
12743 @end ifset
12744
12745 @noindent
12746 The default is ^Default^DEFAULT^: no output for syntactically correct
12747 project files.
12748 @noindent
12749 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12750 only the last one is used.
12751
12752 @end table
12753
12754 @c **********************************
12755 @c * Tools Supporting Project Files *
12756 @c **********************************
12757
12758 @node  Tools Supporting Project Files
12759 @section Tools Supporting Project Files
12760
12761 @menu
12762 * gnatmake and Project Files::
12763 * The GNAT Driver and Project Files::
12764 @ifclear vms
12765 * Glide and Project Files::
12766 @end ifclear
12767 @end menu
12768
12769 @node gnatmake and Project Files
12770 @subsection gnatmake and Project Files
12771
12772 @noindent
12773 This section covers several topics related to @command{gnatmake} and
12774 project files: defining ^switches^switches^ for @command{gnatmake}
12775 and for the tools that it invokes; specifying configuration pragmas;
12776 the use of the @code{Main} attribute; building and rebuilding library project
12777 files.
12778
12779 @menu
12780 * ^Switches^Switches^ and Project Files::
12781 * Specifying Configuration Pragmas::
12782 * Project Files and Main Subprograms::
12783 * Library Project Files::
12784 @end menu
12785
12786 @node ^Switches^Switches^ and Project Files
12787 @subsubsection ^Switches^Switches^ and Project Files
12788
12789 @ifset vms
12790 It is not currently possible to specify VMS style qualifiers in the project
12791 files; only Unix style ^switches^switches^ may be specified.
12792 @end ifset
12793
12794 @noindent
12795 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12796 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12797 attribute, a @code{^Switches^Switches^} attribute, or both;
12798 as their names imply, these ^switch^switch^-related
12799 attributes affect the ^switches^switches^ that are used for each of these GNAT
12800 components when
12801 @command{gnatmake} is invoked.  As will be explained below, these
12802 component-specific ^switches^switches^ precede
12803 the ^switches^switches^ provided on the @command{gnatmake} command line.
12804
12805 The @code{^Default_Switches^Default_Switches^} attribute is an associative
12806 array indexed by language name (case insensitive) whose value is a string list.
12807 For example:
12808
12809 @smallexample @c projectfile
12810 @group
12811 package Compiler is
12812   for ^Default_Switches^Default_Switches^ ("Ada")
12813       use ("^-gnaty^-gnaty^",
12814            "^-v^-v^");
12815 end Compiler;
12816 @end group
12817 @end smallexample
12818
12819 @noindent
12820 The @code{^Switches^Switches^} attribute is also an associative array,
12821 indexed by a file name (which may or may not be case sensitive, depending
12822 on the operating system) whose value is a string list.  For example:
12823
12824 @smallexample @c projectfile
12825 @group
12826 package Builder is
12827    for ^Switches^Switches^ ("main1.adb")
12828        use ("^-O2^-O2^");
12829    for ^Switches^Switches^ ("main2.adb")
12830        use ("^-g^-g^");
12831 end Builder;
12832 @end group
12833 @end smallexample
12834
12835 @noindent
12836 For the @code{Builder} package, the file names must designate source files
12837 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12838 file names must designate @file{ALI} or source files for main subprograms.
12839 In each case just the file name without an explicit extension is acceptable.
12840
12841 For each tool used in a program build (@command{gnatmake}, the compiler, the
12842 binder, and the linker), the corresponding package @dfn{contributes} a set of
12843 ^switches^switches^ for each file on which the tool is invoked, based on the
12844 ^switch^switch^-related attributes defined in the package.
12845 In particular, the ^switches^switches^
12846 that each of these packages contributes for a given file @var{f} comprise:
12847
12848 @itemize @bullet
12849 @item
12850 the value of attribute @code{^Switches^Switches^ (@var{f})},
12851 if it is specified in the package for the given file,
12852 @item
12853 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12854 if it is specified in the package.
12855 @end itemize
12856
12857 @noindent
12858 If neither of these attributes is defined in the package, then the package does
12859 not contribute any ^switches^switches^ for the given file.
12860
12861 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12862 two sets, in the following order: those contributed for the file
12863 by the @code{Builder} package;
12864 and the switches passed on the command line.
12865
12866 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12867 the ^switches^switches^ passed to the tool comprise three sets,
12868 in the following order:
12869
12870 @enumerate
12871 @item
12872 the applicable ^switches^switches^ contributed for the file
12873 by the @code{Builder} package in the project file supplied on the command line;
12874
12875 @item
12876 those contributed for the file by the package (in the relevant project file --
12877 see below) corresponding to the tool; and
12878
12879 @item
12880 the applicable switches passed on the command line.
12881 @end enumerate
12882
12883 @noindent
12884 The term @emph{applicable ^switches^switches^} reflects the fact that
12885 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12886 tools, depending on the individual ^switch^switch^.
12887
12888 @command{gnatmake} may invoke the compiler on source files from different
12889 projects. The Project Manager will use the appropriate project file to
12890 determine the @code{Compiler} package for each source file being compiled.
12891 Likewise for the @code{Binder} and @code{Linker} packages.
12892
12893 As an example, consider the following package in a project file:
12894
12895 @smallexample @c projectfile
12896 @group
12897 project Proj1 is
12898    package Compiler is
12899       for ^Default_Switches^Default_Switches^ ("Ada")
12900           use ("^-g^-g^");
12901       for ^Switches^Switches^ ("a.adb")
12902           use ("^-O1^-O1^");
12903       for ^Switches^Switches^ ("b.adb")
12904           use ("^-O2^-O2^",
12905                "^-gnaty^-gnaty^");
12906    end Compiler;
12907 end Proj1;
12908 @end group
12909 @end smallexample
12910
12911 @noindent
12912 If @command{gnatmake} is invoked with this project file, and it needs to
12913 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12914 @file{a.adb} will be compiled with the ^switch^switch^
12915 @option{^-O1^-O1^},
12916 @file{b.adb} with ^switches^switches^
12917 @option{^-O2^-O2^}
12918 and @option{^-gnaty^-gnaty^},
12919 and @file{c.adb} with @option{^-g^-g^}.
12920
12921 The following example illustrates the ordering of the ^switches^switches^
12922 contributed by different packages:
12923
12924 @smallexample @c projectfile
12925 @group
12926 project Proj2 is
12927    package Builder is
12928       for ^Switches^Switches^ ("main.adb")
12929           use ("^-g^-g^",
12930                "^-O1^-)1^",
12931                "^-f^-f^");
12932    end Builder;
12933 @end group
12934
12935 @group
12936    package Compiler is
12937       for ^Switches^Switches^ ("main.adb")
12938           use ("^-O2^-O2^");
12939    end Compiler;
12940 end Proj2;
12941 @end group
12942 @end smallexample
12943
12944 @noindent
12945 If you issue the command:
12946
12947 @smallexample
12948     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12949 @end smallexample
12950
12951 @noindent
12952 then the compiler will be invoked on @file{main.adb} with the following
12953 sequence of ^switches^switches^
12954
12955 @smallexample
12956    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12957 @end smallexample
12958
12959 with the last @option{^-O^-O^}
12960 ^switch^switch^ having precedence over the earlier ones;
12961 several other ^switches^switches^
12962 (such as @option{^-c^-c^}) are added implicitly.
12963
12964 The ^switches^switches^
12965 @option{^-g^-g^}
12966 and @option{^-O1^-O1^} are contributed by package
12967 @code{Builder},  @option{^-O2^-O2^} is contributed
12968 by the package @code{Compiler}
12969 and @option{^-O0^-O0^} comes from the command line.
12970
12971 The @option{^-g^-g^}
12972 ^switch^switch^ will also be passed in the invocation of
12973 @command{Gnatlink.}
12974
12975 A final example illustrates switch contributions from packages in different
12976 project files:
12977
12978 @smallexample @c projectfile
12979 @group
12980 project Proj3 is
12981    for Source_Files use ("pack.ads", "pack.adb");
12982    package Compiler is
12983       for ^Default_Switches^Default_Switches^ ("Ada")
12984           use ("^-gnata^-gnata^");
12985    end Compiler;
12986 end Proj3;
12987 @end group
12988
12989 @group
12990 with "Proj3";
12991 project Proj4 is
12992    for Source_Files use ("foo_main.adb", "bar_main.adb");
12993    package Builder is
12994       for ^Switches^Switches^ ("foo_main.adb")
12995           use ("^-s^-s^",
12996                "^-g^-g^");
12997    end Builder;
12998 end Proj4;
12999 @end group
13000
13001 @group
13002 -- Ada source file:
13003 with Pack;
13004 procedure Foo_Main is
13005    ...
13006 end Foo_Main;
13007 @end group
13008 @end smallexample
13009
13010 If the command is
13011 @smallexample
13012 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13013 @end smallexample
13014
13015 @noindent
13016 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13017 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13018 @option{^-gnato^-gnato^} (passed on the command line).
13019 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13020 are @option{^-g^-g^} from @code{Proj4.Builder},
13021 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13022 and @option{^-gnato^-gnato^} from the command line.
13023
13024 @noindent
13025 When using @command{gnatmake} with project files, some ^switches^switches^ or
13026 arguments may be expressed as relative paths. As the working directory where
13027 compilation occurs may change, these relative paths are converted to absolute
13028 paths. For the ^switches^switches^ found in a project file, the relative paths
13029 are relative to the project file directory, for the switches on the command
13030 line, they are relative to the directory where @command{gnatmake} is invoked.
13031 The ^switches^switches^ for which this occurs are:
13032 ^-I^-I^,
13033 ^-A^-A^,
13034 ^-L^-L^,
13035 ^-aO^-aO^,
13036 ^-aL^-aL^,
13037 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13038 ^switch^switch^
13039 ^-o^-o^, object files specified in package @code{Linker} or after
13040 -largs on the command line). The exception to this rule is the ^switch^switch^
13041 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13042
13043 @node Specifying Configuration Pragmas
13044 @subsubsection Specifying Configuration Pragmas
13045
13046 When using @command{gnatmake} with project files, if there exists a file
13047 @file{gnat.adc} that contains configuration pragmas, this file will be
13048 ignored.
13049
13050 Configuration pragmas can be defined by means of the following attributes in
13051 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13052 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13053
13054 Both these attributes are single string attributes. Their values is the path
13055 name of a file containing configuration pragmas. If a path name is relative,
13056 then it is relative to the project directory of the project file where the
13057 attribute is defined.
13058
13059 When compiling a source, the configuration pragmas used are, in order,
13060 those listed in the file designated by attribute
13061 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13062 project file, if it is specified, and those listed in the file designated by
13063 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13064 the project file of the source, if it exists.
13065
13066 @node Project Files and Main Subprograms
13067 @subsubsection Project Files and Main Subprograms
13068
13069 @noindent
13070 When using a project file, you can invoke @command{gnatmake}
13071 with one or several main subprograms, by specifying their source files on the
13072 command line.
13073
13074 @smallexample
13075     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13076 @end smallexample
13077
13078 @noindent
13079 Each of these needs to be a source file of the same project, except
13080 when the switch ^-u^/UNIQUE^ is used.
13081
13082 @noindent
13083 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13084 same project, one of the project in the tree rooted at the project specified
13085 on the command line. The package @code{Builder} of this common project, the
13086 "main project" is the one that is considered by @command{gnatmake}.
13087
13088 @noindent
13089 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13090 imported directly or indirectly by the project specified on the command line.
13091 Note that if such a source file is not part of the project specified on the
13092 command line, the ^switches^switches^ found in package @code{Builder} of the
13093 project specified on the command line, if any, that are transmitted
13094 to the compiler will still be used, not those found in the project file of
13095 the source file.
13096
13097 @noindent
13098 When using a project file, you can also invoke @command{gnatmake} without
13099 explicitly specifying any main, and the effect depends on whether you have
13100 defined the @code{Main} attribute.  This attribute has a string list value,
13101 where each element in the list is the name of a source file (the file
13102 extension is optional) that contains a unit that can be a main subprogram.
13103
13104 If the @code{Main} attribute is defined in a project file as a non-empty
13105 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13106 line, then invoking @command{gnatmake} with this project file but without any
13107 main on the command line is equivalent to invoking @command{gnatmake} with all
13108 the file names in the @code{Main} attribute on the command line.
13109
13110 Example:
13111 @smallexample @c projectfile
13112 @group
13113    project Prj is
13114       for Main use ("main1", "main2", "main3");
13115    end Prj;
13116 @end group
13117 @end smallexample
13118
13119 @noindent
13120 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13121 is equivalent to
13122 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13123
13124 When the project attribute @code{Main} is not specified, or is specified
13125 as an empty string list, or when the switch @option{-u} is used on the command
13126 line, then invoking @command{gnatmake} with no main on the command line will
13127 result in all immediate sources of the project file being checked, and
13128 potentially recompiled. Depending on the presence of the switch @option{-u},
13129 sources from other project files on which the immediate sources of the main
13130 project file depend are also checked and potentially recompiled. In other
13131 words, the @option{-u} switch is applied to all of the immediate sources of the
13132 main project file.
13133
13134 When no main is specified on the command line and attribute @code{Main} exists
13135 and includes several mains, or when several mains are specified on the
13136 command line, the default ^switches^switches^ in package @code{Builder} will
13137 be used for all mains, even if there are specific ^switches^switches^
13138 specified for one or several mains.
13139
13140 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13141 the specific ^switches^switches^ for each main, if they are specified.
13142
13143 @node Library Project Files
13144 @subsubsection Library Project Files
13145
13146 @noindent
13147 When @command{gnatmake} is invoked with a main project file that is a library
13148 project file, it is not allowed to specify one or more mains on the command
13149 line.
13150
13151 @noindent
13152 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13153 ^-l^/ACTION=LINK^ have special meanings.
13154
13155 @itemize @bullet
13156 @item ^-b^/ACTION=BIND^ is only allwed for stand-alone libraries. It indicates
13157 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13158 library.
13159
13160 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13161 to @command{gnatmake} that the binder generated file should be compiled
13162 (in the case of a stand-alone library) and that the library should be built.
13163
13164 @end itemize
13165
13166 @node The GNAT Driver and Project Files
13167 @subsection The GNAT Driver and Project Files
13168
13169 @noindent
13170 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13171 are project-aware:
13172 @command{^gnatbind^gnatbind^},
13173 @command{^gnatfind^gnatfind^},
13174 @command{^gnatlink^gnatlink^},
13175 @command{^gnatls^gnatls^},
13176 @command{^gnatelim^gnatelim^},
13177 @command{^gnatpp^gnatpp^},
13178 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13179 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13180 They must be invoked through the @command{gnat} driver.
13181
13182 The @command{gnat} driver is a front-end that accepts a number of commands and
13183 call the corresponding tool. It has been designed initially for VMS to convert
13184 VMS style qualifiers to Unix style switches, but it is now available to all
13185 the GNAT supported platforms.
13186
13187 On non VMS platforms, the @command{gnat} driver accepts the following commands
13188 (case insensitive):
13189
13190 @itemize @bullet
13191 @item
13192 BIND to invoke @command{^gnatbind^gnatbind^}
13193 @item
13194 CHOP to invoke @command{^gnatchop^gnatchop^}
13195 @item
13196 CLEAN to invoke @command{^gnatclean^gnatclean^}
13197 @item
13198 COMP or COMPILE to invoke the compiler
13199 @item
13200 ELIM to invoke @command{^gnatelim^gnatelim^}
13201 @item
13202 FIND to invoke @command{^gnatfind^gnatfind^}
13203 @item
13204 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13205 @item
13206 LINK to invoke @command{^gnatlink^gnatlink^}
13207 @item
13208 LS or LIST to invoke @command{^gnatls^gnatls^}
13209 @item
13210 MAKE to invoke @command{^gnatmake^gnatmake^}
13211 @item
13212 NAME to invoke @command{^gnatname^gnatname^}
13213 @item
13214 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13215 @item
13216 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13217 @item
13218 STUB to invoke @command{^gnatstub^gnatstub^}
13219 @item
13220 XREF to invoke @command{^gnatxref^gnatxref^}
13221 @end itemize
13222
13223 @noindent
13224 Note that the compiler is invoked using the command
13225 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}.
13226
13227 @noindent
13228 The command may be followed by switches and arguments for the invoked
13229 tool.
13230
13231 @smallexample
13232   gnat bind -C main.ali
13233   gnat ls -a main
13234   gnat chop foo.txt
13235 @end smallexample
13236
13237 @noindent
13238 Switches may also be put in text files, one switch per line, and the text
13239 files may be specified with their path name preceded by '@@'.
13240
13241 @smallexample
13242    gnat bind @@args.txt main.ali
13243 @end smallexample
13244
13245 @noindent
13246 In addition, for command BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13247 PP or PRETTY and XREF, the project file related switches
13248 (@option{^-P^/PROJECT_FILE^},
13249 @option{^-X^/EXTERNAL_REFERENCE^} and
13250 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13251 the switches of the invoking tool.
13252
13253 @noindent
13254 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13255 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13256 the immediate sources of the specified project file.
13257
13258 @noindent
13259 For each of these commands, there is optionally a corresponding  package
13260 in the main project.
13261
13262 @itemize @bullet
13263 @item
13264 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13265
13266 @item
13267 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13268
13269 @item
13270 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13271
13272 @item
13273 package @code{Eliminate} for command ELIM (invoking
13274 @code{^gnatelim^gnatelim^})
13275
13276 @item
13277 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13278
13279 @item
13280 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13281
13282 @item
13283 package @code{Pretty_Printer} for command PP or PRETTY
13284 (invoking @code{^gnatpp^gnatpp^})
13285
13286 @item
13287 package @code{Cross_Reference} for command XREF (invoking
13288 @code{^gnatxref^gnatxref^})
13289
13290 @end itemize
13291
13292 @noindent
13293 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13294 a simple variable with a string list value. It contains ^switches^switches^
13295 for the invocation of @code{^gnatls^gnatls^}.
13296
13297 @smallexample @c projectfile
13298 @group
13299 project Proj1 is
13300    package gnatls is
13301       for ^Switches^Switches^
13302           use ("^-a^-a^",
13303                "^-v^-v^");
13304    end gnatls;
13305 end Proj1;
13306 @end group
13307 @end smallexample
13308
13309 @noindent
13310 All other packages have two attribute @code{^Switches^Switches^} and
13311 @code{^Default_Switches^Default_Switches^}.
13312
13313 @noindent
13314 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13315 source file name, that has a string list value: the ^switches^switches^ to be
13316 used when the tool corresponding to the package is invoked for the specific
13317 source file.
13318
13319 @noindent
13320 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13321 indexed by  the programming language that has a string list value.
13322 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13323 ^switches^switches^ for the invocation of the tool corresponding
13324 to the package, except if a specific @code{^Switches^Switches^} attribute
13325 is specified for the source file.
13326
13327 @smallexample @c projectfile
13328 @group
13329 project Proj is
13330
13331    for Source_Dirs use ("./**");
13332
13333    package gnatls is
13334       for ^Switches^Switches^ use
13335           ("^-a^-a^",
13336            "^-v^-v^");
13337    end gnatls;
13338 @end group
13339 @group
13340
13341    package Compiler is
13342       for ^Default_Switches^Default_Switches^ ("Ada")
13343           use ("^-gnatv^-gnatv^",
13344                "^-gnatwa^-gnatwa^");
13345    end Binder;
13346 @end group
13347 @group
13348
13349    package Binder is
13350       for ^Default_Switches^Default_Switches^ ("Ada")
13351           use ("^-C^-C^",
13352                "^-e^-e^");
13353    end Binder;
13354 @end group
13355 @group
13356
13357    package Linker is
13358       for ^Default_Switches^Default_Switches^ ("Ada")
13359           use ("^-C^-C^");
13360       for ^Switches^Switches^ ("main.adb")
13361           use ("^-C^-C^",
13362                "^-v^-v^",
13363                "^-v^-v^");
13364    end Linker;
13365 @end group
13366 @group
13367
13368    package Finder is
13369       for ^Default_Switches^Default_Switches^ ("Ada")
13370            use ("^-a^-a^",
13371                 "^-f^-f^");
13372    end Finder;
13373 @end group
13374 @group
13375
13376    package Cross_Reference is
13377       for ^Default_Switches^Default_Switches^ ("Ada")
13378           use ("^-a^-a^",
13379                "^-f^-f^",
13380                "^-d^-d^",
13381                "^-u^-u^");
13382    end Cross_Reference;
13383 end Proj;
13384 @end group
13385 @end smallexample
13386
13387 @noindent
13388 With the above project file, commands such as
13389
13390 @smallexample
13391    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13392    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13393    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13394    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13395    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13396 @end smallexample
13397
13398 @noindent
13399 will set up the environment properly and invoke the tool with the switches
13400 found in the package corresponding to the tool:
13401 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13402 except @code{^Switches^Switches^ ("main.adb")}
13403 for @code{^gnatlink^gnatlink^}.
13404
13405 @ifclear vms
13406 @node Glide and Project Files
13407 @subsection Glide and Project Files
13408
13409 @noindent
13410 Glide will automatically recognize the @file{.gpr} extension for
13411 project files, and will
13412 convert them to its own internal format automatically. However, it
13413 doesn't provide a syntax-oriented editor for modifying these
13414 files.
13415 The project file will be loaded as text when you select the menu item
13416 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13417 You can edit this text and save the @file{gpr} file;
13418 when you next select this project file in Glide it
13419 will be automatically reloaded.
13420 @end ifclear
13421
13422 @c **********************
13423 @node An Extended Example
13424 @section An Extended Example
13425
13426 @noindent
13427 Suppose that we have two programs, @var{prog1} and @var{prog2},
13428 whose sources are in corresponding directories. We would like
13429 to build them with a single @command{gnatmake} command, and we want to place
13430 their object files into @file{build} subdirectories of the source directories.
13431 Furthermore, we want to have to have two separate subdirectories
13432 in @file{build}  -- @file{release} and @file{debug} -- which will contain
13433 the object files compiled with different set of compilation flags.
13434
13435 In other words, we have the following structure:
13436
13437 @smallexample
13438 @group
13439    main
13440      |- prog1
13441      |    |- build
13442      |         | debug
13443      |         | release
13444      |- prog2
13445           |- build
13446                | debug
13447                | release
13448 @end group
13449 @end smallexample
13450
13451 @noindent
13452 Here are the project files that we must place in a directory @file{main}
13453 to maintain this structure:
13454
13455 @enumerate
13456
13457 @item We create a @code{Common} project with a package @code{Compiler} that
13458 specifies the compilation ^switches^switches^:
13459
13460 @smallexample
13461 File "common.gpr":
13462 @group
13463 @b{project} Common @b{is}
13464
13465    @b{for} Source_Dirs @b{use} (); -- No source files
13466 @end group
13467
13468 @group
13469    @b{type} Build_Type @b{is} ("release", "debug");
13470    Build : Build_Type := External ("BUILD", "debug");
13471 @end group
13472 @group
13473    @b{package} Compiler @b{is}
13474       @b{case} Build @b{is}
13475          @b{when} "release" =>
13476            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13477                    @b{use} ("^-O2^-O2^");
13478          @b{when} "debug"   =>
13479            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13480                    @b{use} ("^-g^-g^");
13481       @b{end case};
13482    @b{end} Compiler;
13483
13484 @b{end} Common;
13485 @end group
13486 @end smallexample
13487
13488 @item We create separate projects for the two programs:
13489
13490 @smallexample
13491 @group
13492 File "prog1.gpr":
13493
13494 @b{with} "common";
13495 @b{project} Prog1 @b{is}
13496
13497     @b{for} Source_Dirs @b{use} ("prog1");
13498     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
13499
13500     @b{package} Compiler @b{renames} Common.Compiler;
13501
13502 @b{end} Prog1;
13503 @end group
13504 @end smallexample
13505
13506 @smallexample
13507 @group
13508 File "prog2.gpr":
13509
13510 @b{with} "common";
13511 @b{project} Prog2 @b{is}
13512
13513     @b{for} Source_Dirs @b{use} ("prog2");
13514     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
13515
13516     @b{package} Compiler @b{renames} Common.Compiler;
13517
13518 @end group
13519 @b{end} Prog2;
13520 @end smallexample
13521
13522 @item We create a wrapping project @code{Main}:
13523
13524 @smallexample
13525 @group
13526 File "main.gpr":
13527
13528 @b{with} "common";
13529 @b{with} "prog1";
13530 @b{with} "prog2";
13531 @b{project} Main @b{is}
13532
13533    @b{package} Compiler @b{renames} Common.Compiler;
13534
13535 @b{end} Main;
13536 @end group
13537 @end smallexample
13538
13539 @item Finally we need to create a dummy procedure that @code{with}s (either
13540 explicitly or implicitly) all the sources of our two programs.
13541
13542 @end enumerate
13543
13544 @noindent
13545 Now we can build the programs using the command
13546
13547 @smallexample
13548    gnatmake ^-P^/PROJECT_FILE=^main dummy
13549 @end smallexample
13550
13551 @noindent
13552 for the Debug mode, or
13553
13554 @ifclear vms
13555 @smallexample
13556    gnatmake -Pmain -XBUILD=release
13557 @end smallexample
13558 @end ifclear
13559
13560 @ifset vms
13561 @smallexample
13562    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13563 @end smallexample
13564 @end ifset
13565
13566 @noindent
13567 for the Release mode.
13568
13569 @c ********************************
13570 @c * Project File Complete Syntax *
13571 @c ********************************
13572
13573 @node Project File Complete Syntax
13574 @section Project File Complete Syntax
13575
13576 @smallexample
13577 project ::=
13578   context_clause project_declaration
13579
13580 context_clause ::=
13581   @{with_clause@}
13582
13583 with_clause ::=
13584   @b{with} path_name @{ , path_name @} ;
13585
13586 path_name ::=
13587    string_literal
13588
13589 project_declaration ::=
13590   simple_project_declaration | project_extension
13591
13592 simple_project_declaration ::=
13593   @b{project} <project_>simple_name @b{is}
13594     @{declarative_item@}
13595   @b{end} <project_>simple_name;
13596
13597 project_extension ::=
13598   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
13599     @{declarative_item@}
13600   @b{end} <project_>simple_name;
13601
13602 declarative_item ::=
13603   package_declaration |
13604   typed_string_declaration |
13605   other_declarative_item
13606
13607 package_declaration ::=
13608   package_specification | package_renaming
13609
13610 package_specification ::=
13611   @b{package} package_identifier @b{is}
13612     @{simple_declarative_item@}
13613   @b{end} package_identifier ;
13614
13615 package_identifier ::=
13616   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13617   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
13618   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
13619
13620 package_renaming ::==
13621   @b{package} package_identifier @b{renames}
13622        <project_>simple_name.package_identifier ;
13623
13624 typed_string_declaration ::=
13625   @b{type} <typed_string_>_simple_name @b{is}
13626    ( string_literal @{, string_literal@} );
13627
13628 other_declarative_item ::=
13629   attribute_declaration |
13630   typed_variable_declaration |
13631   variable_declaration |
13632   case_construction
13633
13634 attribute_declaration ::=
13635   full_associative_array_declaration |
13636   @b{for} attribute_designator @b{use} expression ;
13637
13638 full_associative_array_declaration ::=
13639   @b{for} <associative_array_attribute_>simple_name @b{use}
13640   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13641
13642 attribute_designator ::=
13643   <simple_attribute_>simple_name |
13644   <associative_array_attribute_>simple_name ( string_literal )
13645
13646 typed_variable_declaration ::=
13647   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
13648
13649 variable_declaration ::=
13650   <variable_>simple_name := expression;
13651
13652 expression ::=
13653   term @{& term@}
13654
13655 term ::=
13656   literal_string |
13657   string_list |
13658   <variable_>name |
13659   external_value |
13660   attribute_reference
13661
13662 string_literal ::=
13663   (same as Ada)
13664
13665 string_list ::=
13666   ( <string_>expression @{ , <string_>expression @} )
13667
13668 external_value ::=
13669   @b{external} ( string_literal [, string_literal] )
13670
13671 attribute_reference ::=
13672   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
13673
13674 attribute_prefix ::=
13675   @b{project} |
13676   <project_>simple_name | package_identifier |
13677   <project_>simple_name . package_identifier
13678
13679 case_construction ::=
13680   @b{case} <typed_variable_>name @b{is}
13681     @{case_item@}
13682   @b{end case} ;
13683
13684 case_item ::=
13685   @b{when} discrete_choice_list =>
13686       @{case_construction | attribute_declaration@}
13687
13688 discrete_choice_list ::=
13689   string_literal @{| string_literal@} |
13690   @b{others}
13691
13692 name ::=
13693   simple_name @{. simple_name@}
13694
13695 simple_name ::=
13696   identifier (same as Ada)
13697
13698 @end smallexample
13699
13700
13701 @node The Cross-Referencing Tools gnatxref and gnatfind
13702 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13703 @findex gnatxref
13704 @findex gnatfind
13705
13706 @noindent
13707 The compiler generates cross-referencing information (unless
13708 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13709 This information indicates where in the source each entity is declared and
13710 referenced. Note that entities in package Standard are not included, but
13711 entities in all other predefined units are included in the output.
13712
13713 Before using any of these two tools, you need to compile successfully your
13714 application, so that GNAT gets a chance to generate the cross-referencing
13715 information.
13716
13717 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13718 information to provide the user with the capability to easily locate the
13719 declaration and references to an entity. These tools are quite similar,
13720 the difference being that @code{gnatfind} is intended for locating
13721 definitions and/or references to a specified entity or entities, whereas
13722 @code{gnatxref} is oriented to generating a full report of all
13723 cross-references.
13724
13725 To use these tools, you must not compile your application using the
13726 @option{-gnatx} switch on the @file{gnatmake} command line
13727 (see @ref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13728 information will not be generated.
13729
13730 @menu
13731 * gnatxref Switches::
13732 * gnatfind Switches::
13733 * Project Files for gnatxref and gnatfind::
13734 * Regular Expressions in gnatfind and gnatxref::
13735 * Examples of gnatxref Usage::
13736 * Examples of gnatfind Usage::
13737 @end menu
13738
13739 @node gnatxref Switches
13740 @section @code{gnatxref} Switches
13741
13742 @noindent
13743 The command invocation for @code{gnatxref} is:
13744 @smallexample
13745 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13746 @end smallexample
13747
13748 @noindent
13749 where
13750
13751 @table @code
13752 @item sourcefile1, sourcefile2
13753 identifies the source files for which a report is to be generated. The
13754 ``with''ed units will be processed too. You must provide at least one file.
13755
13756 These file names are considered to be regular expressions, so for instance
13757 specifying @file{source*.adb} is the same as giving every file in the current
13758 directory whose name starts with @file{source} and whose extension is
13759 @file{adb}.
13760
13761 @end table
13762
13763 @noindent
13764 The switches can be :
13765 @table @option
13766 @c !sort!
13767 @item ^-a^/ALL_FILES^
13768 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13769 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13770 the read-only files found in the library search path. Otherwise, these files
13771 will be ignored. This option can be used to protect Gnat sources or your own
13772 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13773 much faster, and their output much smaller. Read-only here refers to access
13774 or permissions status in the file system for the current user.
13775
13776 @item -aIDIR
13777 @cindex @option{-aIDIR} (@command{gnatxref})
13778 When looking for source files also look in directory DIR. The order in which
13779 source file search is undertaken is the same as for @file{gnatmake}.
13780
13781 @item -aODIR
13782 @cindex @option{-aODIR} (@command{gnatxref})
13783 When searching for library and object files, look in directory
13784 DIR. The order in which library files are searched is the same as for
13785 @file{gnatmake}.
13786
13787 @item -nostdinc
13788 @cindex @option{-nostdinc} (@command{gnatxref})
13789 Do not look for sources in the system default directory.
13790
13791 @item -nostdlib
13792 @cindex @option{-nostdlib} (@command{gnatxref})
13793 Do not look for library files in the system default directory.
13794
13795 @item --RTS=@var{rts-path}
13796 @cindex @option{--RTS} (@command{gnatxref})
13797 Specifies the default location of the runtime library. Same meaning as the
13798 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13799
13800 @item ^-d^/DERIVED_TYPES^
13801 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13802 If this switch is set @code{gnatxref} will output the parent type
13803 reference for each matching derived types.
13804
13805 @item ^-f^/FULL_PATHNAME^
13806 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13807 If this switch is set, the output file names will be preceded by their
13808 directory (if the file was found in the search path). If this switch is
13809 not set, the directory will not be printed.
13810
13811 @item ^-g^/IGNORE_LOCALS^
13812 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13813 If this switch is set, information is output only for library-level
13814 entities, ignoring local entities. The use of this switch may accelerate
13815 @code{gnatfind} and @code{gnatxref}.
13816
13817 @item -IDIR
13818 @cindex @option{-IDIR} (@command{gnatxref})
13819 Equivalent to @samp{-aODIR -aIDIR}.
13820
13821 @item -pFILE
13822 @cindex @option{-pFILE} (@command{gnatxref})
13823 Specify a project file to use @xref{Project Files}. These project files are
13824 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
13825 project files, you should use gnatxref through the GNAT driver
13826 (@command{gnat xref -Pproject}).
13827
13828 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13829 project file in the current directory.
13830
13831 If a project file is either specified or found by the tools, then the content
13832 of the source directory and object directory lines are added as if they
13833 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13834 and @samp{^-aO^OBJECT_SEARCH^}.
13835 @item ^-u^/UNUSED^
13836 Output only unused symbols. This may be really useful if you give your
13837 main compilation unit on the command line, as @code{gnatxref} will then
13838 display every unused entity and 'with'ed package.
13839
13840 @ifclear vms
13841 @item -v
13842 Instead of producing the default output, @code{gnatxref} will generate a
13843 @file{tags} file that can be used by vi. For examples how to use this
13844 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
13845 to the standard output, thus you will have to redirect it to a file.
13846 @end ifclear
13847
13848 @end table
13849
13850 @noindent
13851 All these switches may be in any order on the command line, and may even
13852 appear after the file names. They need not be separated by spaces, thus
13853 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13854 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13855
13856 @node gnatfind Switches
13857 @section @code{gnatfind} Switches
13858
13859 @noindent
13860 The command line for @code{gnatfind} is:
13861
13862 @smallexample
13863 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
13864       [file1 file2 ...]
13865 @end smallexample
13866
13867 @noindent
13868 where
13869
13870 @table @code
13871 @item pattern
13872 An entity will be output only if it matches the regular expression found
13873 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
13874
13875 Omitting the pattern is equivalent to specifying @samp{*}, which
13876 will match any entity. Note that if you do not provide a pattern, you
13877 have to provide both a sourcefile and a line.
13878
13879 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13880 for matching purposes. At the current time there is no support for
13881 8-bit codes other than Latin-1, or for wide characters in identifiers.
13882
13883 @item sourcefile
13884 @code{gnatfind} will look for references, bodies or declarations
13885 of symbols referenced in @file{sourcefile}, at line @samp{line}
13886 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
13887 for syntax examples.
13888
13889 @item line
13890 is a decimal integer identifying the line number containing
13891 the reference to the entity (or entities) to be located.
13892
13893 @item column
13894 is a decimal integer identifying the exact location on the
13895 line of the first character of the identifier for the
13896 entity reference. Columns are numbered from 1.
13897
13898 @item file1 file2 ...
13899 The search will be restricted to these source files. If none are given, then
13900 the search will be done for every library file in the search path.
13901 These file must appear only after the pattern or sourcefile.
13902
13903 These file names are considered to be regular expressions, so for instance
13904 specifying 'source*.adb' is the same as giving every file in the current
13905 directory whose name starts with 'source' and whose extension is 'adb'.
13906
13907 The location of the spec of the entity will always be displayed, even if it
13908 isn't in one of file1, file2,... The occurrences of the entity in the
13909 separate units of the ones given on the command line will also be displayed.
13910
13911 Note that if you specify at least one file in this part, @code{gnatfind} may
13912 sometimes not be able to find the body of the subprograms...
13913
13914 @end table
13915
13916 @noindent
13917 At least one of 'sourcefile' or 'pattern' has to be present on
13918 the command line.
13919
13920 The following switches are available:
13921 @table @option
13922 @c !sort!
13923
13924 @item ^-a^/ALL_FILES^
13925 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13926 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13927 the read-only files found in the library search path. Otherwise, these files
13928 will be ignored. This option can be used to protect Gnat sources or your own
13929 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13930 much faster, and their output much smaller. Read-only here refers to access
13931 or permission status in the file system for the current user.
13932
13933 @item -aIDIR
13934 @cindex @option{-aIDIR} (@command{gnatfind})
13935 When looking for source files also look in directory DIR. The order in which
13936 source file search is undertaken is the same as for @file{gnatmake}.
13937
13938 @item -aODIR
13939 @cindex @option{-aODIR} (@command{gnatfind})
13940 When searching for library and object files, look in directory
13941 DIR. The order in which library files are searched is the same as for
13942 @file{gnatmake}.
13943
13944 @item -nostdinc
13945 @cindex @option{-nostdinc} (@command{gnatfind})
13946 Do not look for sources in the system default directory.
13947
13948 @item -nostdlib
13949 @cindex @option{-nostdlib} (@command{gnatfind})
13950 Do not look for library files in the system default directory.
13951
13952 @item --RTS=@var{rts-path}
13953 @cindex @option{--RTS} (@command{gnatfind})
13954 Specifies the default location of the runtime library. Same meaning as the
13955 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13956
13957 @item ^-d^/DERIVED_TYPE_INFORMATION^
13958 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13959 If this switch is set, then @code{gnatfind} will output the parent type
13960 reference for each matching derived types.
13961
13962 @item ^-e^/EXPRESSIONS^
13963 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13964 By default, @code{gnatfind} accept the simple regular expression set for
13965 @samp{pattern}. If this switch is set, then the pattern will be
13966 considered as full Unix-style regular expression.
13967
13968 @item ^-f^/FULL_PATHNAME^
13969 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13970 If this switch is set, the output file names will be preceded by their
13971 directory (if the file was found in the search path). If this switch is
13972 not set, the directory will not be printed.
13973
13974 @item ^-g^/IGNORE_LOCALS^
13975 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13976 If this switch is set, information is output only for library-level
13977 entities, ignoring local entities. The use of this switch may accelerate
13978 @code{gnatfind} and @code{gnatxref}.
13979
13980 @item -IDIR
13981 @cindex @option{-IDIR} (@command{gnatfind})
13982 Equivalent to @samp{-aODIR -aIDIR}.
13983
13984 @item -pFILE
13985 @cindex @option{-pFILE} (@command{gnatfind})
13986 Specify a project file (@pxref{Project Files}) to use.
13987 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13988 project file in the current directory.
13989
13990 If a project file is either specified or found by the tools, then the content
13991 of the source directory and object directory lines are added as if they
13992 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13993 @samp{^-aO^/OBJECT_SEARCH^}.
13994
13995 @item ^-r^/REFERENCES^
13996 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13997 By default, @code{gnatfind} will output only the information about the
13998 declaration, body or type completion of the entities. If this switch is
13999 set, the @code{gnatfind} will locate every reference to the entities in
14000 the files specified on the command line (or in every file in the search
14001 path if no file is given on the command line).
14002
14003 @item ^-s^/PRINT_LINES^
14004 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14005 If this switch is set, then @code{gnatfind} will output the content
14006 of the Ada source file lines were the entity was found.
14007
14008 @item ^-t^/TYPE_HIERARCHY^
14009 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14010 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14011 the specified type. It act like -d option but recursively from parent
14012 type to parent type. When this switch is set it is not possible to
14013 specify more than one file.
14014
14015 @end table
14016
14017 @noindent
14018 All these switches may be in any order on the command line, and may even
14019 appear after the file names. They need not be separated by spaces, thus
14020 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14021 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14022
14023 As stated previously, gnatfind will search in every directory in the
14024 search path. You can force it to look only in the current directory if
14025 you specify @code{*} at the end of the command line.
14026
14027 @node Project Files for gnatxref and gnatfind
14028 @section Project Files for @command{gnatxref} and @command{gnatfind}
14029
14030 @noindent
14031 Project files allow a programmer to specify how to compile its
14032 application, where to find sources, etc.  These files are used
14033 @ifclear vms
14034 primarily by the Glide Ada mode, but they can also be used
14035 @end ifclear
14036 by the two tools
14037 @code{gnatxref} and @code{gnatfind}.
14038
14039 A project file name must end with @file{.gpr}. If a single one is
14040 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14041 extract the information from it. If multiple project files are found, none of
14042 them is read, and you have to use the @samp{-p} switch to specify the one
14043 you want to use.
14044
14045 The following lines can be included, even though most of them have default
14046 values which can be used in most cases.
14047 The lines can be entered in any order in the file.
14048 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14049 each line. If you have multiple instances, only the last one is taken into
14050 account.
14051
14052 @table @code
14053 @item src_dir=DIR
14054 [default: @code{"^./^[]^"}]
14055 specifies a directory where to look for source files. Multiple @code{src_dir}
14056 lines can be specified and they will be searched in the order they
14057 are specified.
14058
14059 @item obj_dir=DIR
14060 [default: @code{"^./^[]^"}]
14061 specifies a directory where to look for object and library files. Multiple
14062 @code{obj_dir} lines can be specified, and they will be searched in the order
14063 they are specified
14064
14065 @item comp_opt=SWITCHES
14066 [default: @code{""}]
14067 creates a variable which can be referred to subsequently by using
14068 the @code{$@{comp_opt@}} notation. This is intended to store the default
14069 switches given to @command{gnatmake} and @command{gcc}.
14070
14071 @item bind_opt=SWITCHES
14072 [default: @code{""}]
14073 creates a variable which can be referred to subsequently by using
14074 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14075 switches given to @command{gnatbind}.
14076
14077 @item link_opt=SWITCHES
14078 [default: @code{""}]
14079 creates a variable which can be referred to subsequently by using
14080 the @samp{$@{link_opt@}} notation. This is intended to store the default
14081 switches given to @command{gnatlink}.
14082
14083 @item main=EXECUTABLE
14084 [default: @code{""}]
14085 specifies the name of the executable for the application. This variable can
14086 be referred to in the following lines by using the @samp{$@{main@}} notation.
14087
14088 @ifset vms
14089 @item comp_cmd=COMMAND
14090 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14091 @end ifset
14092 @ifclear vms
14093 @item comp_cmd=COMMAND
14094 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14095 @end ifclear
14096 specifies the command used to compile a single file in the application.
14097
14098 @ifset vms
14099 @item make_cmd=COMMAND
14100 [default: @code{"GNAT MAKE $@{main@}
14101 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14102 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14103 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14104 @end ifset
14105 @ifclear vms
14106 @item make_cmd=COMMAND
14107 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14108  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14109  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14110 @end ifclear
14111 specifies the command used to recompile the whole application.
14112
14113 @item run_cmd=COMMAND
14114 [default: @code{"$@{main@}"}]
14115 specifies the command used to run the application.
14116
14117 @item debug_cmd=COMMAND
14118 [default: @code{"gdb $@{main@}"}]
14119 specifies the command used to debug the application
14120
14121 @end table
14122
14123 @noindent
14124 @command{gnatxref} and @command{gnatfind} only take into account the
14125 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14126
14127 @node Regular Expressions in gnatfind and gnatxref
14128 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
14129
14130 @noindent
14131 As specified in the section about @command{gnatfind}, the pattern can be a
14132 regular expression. Actually, there are to set of regular expressions
14133 which are recognized by the program :
14134
14135 @table @code
14136 @item globbing patterns
14137 These are the most usual regular expression. They are the same that you
14138 generally used in a Unix shell command line, or in a DOS session.
14139
14140 Here is a more formal grammar :
14141 @smallexample
14142 @group
14143 @iftex
14144 @leftskip=.5cm
14145 @end iftex
14146 regexp ::= term
14147 term   ::= elmt            -- matches elmt
14148 term   ::= elmt elmt       -- concatenation (elmt then elmt)
14149 term   ::= *               -- any string of 0 or more characters
14150 term   ::= ?               -- matches any character
14151 term   ::= [char @{char@}] -- matches any character listed
14152 term   ::= [char - char]   -- matches any character in range
14153 @end group
14154 @end smallexample
14155
14156 @item full regular expression
14157 The second set of regular expressions is much more powerful. This is the
14158 type of regular expressions recognized by utilities such a @file{grep}.
14159
14160 The following is the form of a regular expression, expressed in Ada
14161 reference manual style BNF is as follows
14162
14163 @smallexample
14164 @iftex
14165 @leftskip=.5cm
14166 @end iftex
14167 @group
14168 regexp ::= term @{| term@} -- alternation (term or term ...)
14169
14170 term ::= item @{item@}     -- concatenation (item then item)
14171
14172 item ::= elmt              -- match elmt
14173 item ::= elmt *            -- zero or more elmt's
14174 item ::= elmt +            -- one or more elmt's
14175 item ::= elmt ?            -- matches elmt or nothing
14176 @end group
14177 @group
14178 elmt ::= nschar            -- matches given character
14179 elmt ::= [nschar @{nschar@}]   -- matches any character listed
14180 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14181 elmt ::= [char - char]     -- matches chars in given range
14182 elmt ::= \ char            -- matches given character
14183 elmt ::= .                 -- matches any single character
14184 elmt ::= ( regexp )        -- parens used for grouping
14185
14186 char ::= any character, including special characters
14187 nschar ::= any character except ()[].*+?^^^
14188 @end group
14189 @end smallexample
14190
14191 Following are a few examples :
14192
14193 @table @samp
14194 @item abcde|fghi
14195 will match any of the two strings 'abcde' and 'fghi'.
14196
14197 @item abc*d
14198 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14199
14200 @item [a-z]+
14201 will match any string which has only lowercase characters in it (and at
14202 least one character
14203
14204 @end table
14205 @end table
14206
14207 @node Examples of gnatxref Usage
14208 @section Examples of @code{gnatxref} Usage
14209
14210 @subsection General Usage
14211
14212 @noindent
14213 For the following examples, we will consider the following units :
14214
14215 @smallexample @c ada
14216 @group
14217 @cartouche
14218 main.ads:
14219 1: with Bar;
14220 2: package Main is
14221 3:     procedure Foo (B : in Integer);
14222 4:     C : Integer;
14223 5: private
14224 6:     D : Integer;
14225 7: end Main;
14226
14227 main.adb:
14228 1: package body Main is
14229 2:     procedure Foo (B : in Integer) is
14230 3:     begin
14231 4:        C := B;
14232 5:        D := B;
14233 6:        Bar.Print (B);
14234 7:        Bar.Print (C);
14235 8:     end Foo;
14236 9: end Main;
14237
14238 bar.ads:
14239 1: package Bar is
14240 2:     procedure Print (B : Integer);
14241 3: end bar;
14242 @end cartouche
14243 @end group
14244 @end smallexample
14245
14246 @table @code
14247
14248 @noindent
14249 The first thing to do is to recompile your application (for instance, in
14250 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14251 the cross-referencing information.
14252 You can then issue any of the following commands:
14253
14254 @item gnatxref main.adb
14255 @code{gnatxref} generates cross-reference information for main.adb
14256 and every unit 'with'ed by main.adb.
14257
14258 The output would be:
14259 @smallexample
14260 @iftex
14261 @leftskip=0cm
14262 @end iftex
14263 B                                                      Type: Integer
14264   Decl: bar.ads           2:22
14265 B                                                      Type: Integer
14266   Decl: main.ads          3:20
14267   Body: main.adb          2:20
14268   Ref:  main.adb          4:13     5:13     6:19
14269 Bar                                                    Type: Unit
14270   Decl: bar.ads           1:9
14271   Ref:  main.adb          6:8      7:8
14272        main.ads           1:6
14273 C                                                      Type: Integer
14274   Decl: main.ads          4:5
14275   Modi: main.adb          4:8
14276   Ref:  main.adb          7:19
14277 D                                                      Type: Integer
14278   Decl: main.ads          6:5
14279   Modi: main.adb          5:8
14280 Foo                                                    Type: Unit
14281   Decl: main.ads          3:15
14282   Body: main.adb          2:15
14283 Main                                                    Type: Unit
14284   Decl: main.ads          2:9
14285   Body: main.adb          1:14
14286 Print                                                   Type: Unit
14287   Decl: bar.ads           2:15
14288   Ref:  main.adb          6:12     7:12
14289 @end smallexample
14290
14291 @noindent
14292 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14293 its body is in main.adb, line 1, column 14 and is not referenced any where.
14294
14295 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14296 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14297
14298 @item gnatxref package1.adb package2.ads
14299 @code{gnatxref} will generates cross-reference information for
14300 package1.adb, package2.ads and any other package 'with'ed by any
14301 of these.
14302
14303 @end table
14304
14305 @ifclear vms
14306 @subsection Using gnatxref with vi
14307
14308 @code{gnatxref} can generate a tags file output, which can be used
14309 directly from @file{vi}. Note that the standard version of @file{vi}
14310 will not work properly with overloaded symbols. Consider using another
14311 free implementation of @file{vi}, such as @file{vim}.
14312
14313 @smallexample
14314 $ gnatxref -v gnatfind.adb > tags
14315 @end smallexample
14316
14317 @noindent
14318 will generate the tags file for @code{gnatfind} itself (if the sources
14319 are in the search path!).
14320
14321 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14322 (replacing @i{entity} by whatever you are looking for), and vi will
14323 display a new file with the corresponding declaration of entity.
14324 @end ifclear
14325
14326 @node Examples of gnatfind Usage
14327 @section Examples of @code{gnatfind} Usage
14328
14329 @table @code
14330
14331 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14332 Find declarations for all entities xyz referenced at least once in
14333 main.adb. The references are search in every library file in the search
14334 path.
14335
14336 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14337 switch is set)
14338
14339 The output will look like:
14340 @smallexample
14341 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14342 ^directory/^[directory]^main.adb:24:10: xyz <= body
14343 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14344 @end smallexample
14345
14346 @noindent
14347 that is to say, one of the entities xyz found in main.adb is declared at
14348 line 12 of main.ads (and its body is in main.adb), and another one is
14349 declared at line 45 of foo.ads
14350
14351 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14352 This is the same command as the previous one, instead @code{gnatfind} will
14353 display the content of the Ada source file lines.
14354
14355 The output will look like:
14356
14357 @smallexample
14358 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14359    procedure xyz;
14360 ^directory/^[directory]^main.adb:24:10: xyz <= body
14361    procedure xyz is
14362 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14363    xyz : Integer;
14364 @end smallexample
14365
14366 @noindent
14367 This can make it easier to find exactly the location your are looking
14368 for.
14369
14370 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14371 Find references to all entities containing an x that are
14372 referenced on line 123 of main.ads.
14373 The references will be searched only in main.ads and foo.adb.
14374
14375 @item gnatfind main.ads:123
14376 Find declarations and bodies for all entities that are referenced on
14377 line 123 of main.ads.
14378
14379 This is the same as @code{gnatfind "*":main.adb:123}.
14380
14381 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14382 Find the declaration for the entity referenced at column 45 in
14383 line 123 of file main.adb in directory mydir. Note that it
14384 is usual to omit the identifier name when the column is given,
14385 since the column position identifies a unique reference.
14386
14387 The column has to be the beginning of the identifier, and should not
14388 point to any character in the middle of the identifier.
14389
14390 @end table
14391
14392
14393 @c *********************************
14394 @node The GNAT Pretty-Printer gnatpp
14395 @chapter The GNAT Pretty-Printer @command{gnatpp}
14396 @findex gnatpp
14397 @cindex Pretty-Printer
14398
14399 @noindent
14400 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14401 for source reformatting / pretty-printing.
14402 It takes an Ada source file as input and generates a reformatted
14403 version as output.
14404 You can specify various style directives via switches; e.g.,
14405 identifier case conventions, rules of indentation, and comment layout.
14406
14407 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14408 tree for the input source and thus requires the input to be syntactically and
14409 semantically legal.
14410 If this condition is not met, @command{gnatpp} will terminate with an
14411 error message; no output file will be generated.
14412
14413 If the compilation unit
14414 contained in the input source depends semantically upon units located
14415 outside the current directory, you have to provide the source search path
14416 when invoking @command{gnatpp}; see the description of the @command{gnatpp}
14417 switches below.
14418
14419 The @command{gnatpp} command has the form
14420
14421 @smallexample
14422 $ gnatpp [@var{switches}] @var{filename}
14423 @end smallexample
14424
14425 @noindent
14426 where
14427 @itemize @bullet
14428 @item
14429 @var{switches} is an optional sequence of switches defining such properties as
14430 the formatting rules, the source search path, and the destination for the
14431 output source file
14432
14433 @item
14434 @var{filename} is the name (including the extension) of the source file to
14435 reformat; ``wildcards'' or several file names on the same gnatpp command are
14436 allowed.  The file name may contain path information; it does not have to
14437 follow the GNAT file naming rules
14438 @end itemize
14439
14440
14441 @menu
14442 * Switches for gnatpp::
14443 * Formatting Rules::
14444 @end menu
14445
14446 @node Switches for gnatpp
14447 @section Switches for @command{gnatpp}
14448
14449 @noindent
14450 The following subsections describe the various switches accepted by
14451 @command{gnatpp}, organized by category.
14452
14453 @ifclear vms
14454 You specify a switch by supplying a name and generally also a value.
14455 In many cases the values for a switch with a given name are incompatible with
14456 each other
14457 (for example the switch that controls the casing of a reserved word may have
14458 exactly one value: upper case, lower case, or
14459 mixed case) and thus exactly one such switch can be in effect for an
14460 invocation of @command{gnatpp}.
14461 If more than one is supplied, the last one is used.
14462 However, some values for the same switch are mutually compatible.
14463 You may supply several such switches to @command{gnatpp}, but then
14464 each must be specified in full, with both the name and the value.
14465 Abbreviated forms (the name appearing once, followed by each value) are
14466 not permitted.
14467 For example, to set
14468 the alignment of the assignment delimiter both in declarations and in
14469 assignment statements, you must write @option{-A2A3}
14470 (or @option{-A2 -A3}), but not @option{-A23}.
14471 @end ifclear
14472
14473 @ifset vms
14474 In many cases the set of options for a given qualifier are incompatible with
14475 each other (for example the qualifier that controls the casing of a reserved
14476 word may have exactly one option, which specifies either upper case, lower
14477 case, or mixed case), and thus exactly one such option can be in effect for
14478 an invocation of @command{gnatpp}.
14479 If more than one is supplied, the last one is used.
14480 However, some qualifiers have options that are mutually compatible,
14481 and then you may then supply several such options when invoking
14482 @command{gnatpp}.
14483 @end ifset
14484
14485 In most cases, it is obvious whether or not the
14486 ^values for a switch with a given name^options for a given qualifier^
14487 are compatible with each other.
14488 When the semantics might not be evident, the summaries below explicitly
14489 indicate the effect.
14490
14491 @menu
14492 * Alignment Control::
14493 * Casing Control::
14494 * Construct Layout Control::
14495 * General Text Layout Control::
14496 * Other Formatting Options::
14497 * Setting the Source Search Path::
14498 * Output File Control::
14499 * Other gnatpp Switches::
14500 @end menu
14501
14502
14503 @node Alignment Control
14504 @subsection Alignment Control
14505 @cindex Alignment control in @command{gnatpp}
14506
14507 @noindent
14508 Programs can be easier to read if certain constructs are vertically aligned.
14509 By default all alignments are set ON.
14510 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14511 OFF, and then use one or more of the other
14512 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14513 to activate alignment for specific constructs.
14514
14515 @table @option
14516 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14517
14518 @ifset vms
14519 @item /ALIGN=ON
14520 Set all alignments to ON
14521 @end ifset
14522
14523 @item ^-A0^/ALIGN=OFF^
14524 Set all alignments to OFF
14525
14526 @item ^-A1^/ALIGN=COLONS^
14527 Align @code{:} in declarations
14528
14529 @item ^-A2^/ALIGN=DECLARATIONS^
14530 Align @code{:=} in initializations in declarations
14531
14532 @item ^-A3^/ALIGN=STATEMENTS^
14533 Align @code{:=} in assignment statements
14534
14535 @item ^-A4^/ALIGN=ARROWS^
14536 Align @code{=>} in associations
14537 @end table
14538
14539 @noindent
14540 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14541 is allowed.
14542
14543
14544 @node Casing Control
14545 @subsection Casing Control
14546 @cindex Casing control in @command{gnatpp}
14547
14548 @noindent
14549 @command{gnatpp} allows you to specify the casing for reserved words,
14550 pragma names, attribute designators and identifiers.
14551 For identifiers you may define a
14552 general rule for name casing but also override this rule
14553 via a set of dictionary files.
14554
14555 Three types of casing are supported: lower case, upper case, and mixed case.
14556 Lower and upper case are self-explanatory (but since some letters in
14557 Latin1 and other GNAT-supported character sets
14558 exist only in lower-case form, an upper case conversion will have no
14559 effect on them.)
14560 ``Mixed case'' means that the first letter, and also each letter immediately
14561 following an underscore, are converted to their uppercase forms;
14562 all the other letters are converted to their lowercase forms.
14563
14564 @table @option
14565 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14566 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14567 Attribute designators are lower case
14568
14569 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14570 Attribute designators are upper case
14571
14572 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14573 Attribute designators are mixed case (this is the default)
14574
14575 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14576 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14577 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14578 lower case (this is the default)
14579
14580 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14581 Keywords are upper case
14582
14583 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14584 @item ^-nD^/NAME_CASING=AS_DECLARED^
14585 Name casing for defining occurrences are as they appear in the source file
14586 (this is the default)
14587
14588 @item ^-nU^/NAME_CASING=UPPER_CASE^
14589 Names are in upper case
14590
14591 @item ^-nL^/NAME_CASING=LOWER_CASE^
14592 Names are in lower case
14593
14594 @item ^-nM^/NAME_CASING=MIXED_CASE^
14595 Names are in mixed case
14596
14597 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14598 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14599 Pragma names are lower case
14600
14601 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14602 Pragma names are upper case
14603
14604 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14605 Pragma names are mixed case (this is the default)
14606
14607 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14608 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14609 Use @var{file} as a @emph{dictionary file} that defines
14610 the casing for a set of specified names,
14611 thereby overriding the effect on these names by
14612 any explicit or implicit
14613 ^-n^/NAME_CASING^ switch.
14614 To supply more than one dictionary file,
14615 use ^several @option{-D} switches^a list of files as options^.
14616
14617 @noindent
14618 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14619 to define the casing for the Ada predefined names and
14620 the names declared in the GNAT libraries.
14621
14622 @item ^-D-^/SPECIFIC_CASING^
14623 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14624 Do not use the default dictionary file;
14625 instead, use the casing
14626 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14627 dictionary file(s)
14628 @end table
14629
14630 @noindent
14631 The structure of a dictionary file, and details on the conventions
14632 used in the default dictionary file, are defined in @ref{Name Casing}.
14633
14634 The @option{^-D-^/SPECIFIC_CASING^} and
14635 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14636 compatible.
14637
14638
14639 @node Construct Layout Control
14640 @subsection Construct Layout Control
14641 @cindex Layout control in @command{gnatpp}
14642
14643 @noindent
14644 This group of @command{gnatpp} switches controls the layout of comments and
14645 complex syntactic constructs.  See @ref{Formatting Comments}, for details
14646 on their effect.
14647
14648 @table @option
14649 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14650 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14651 All the comments remain unchanged
14652
14653 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14654 GNAT-style comment line indentation (this is the default).
14655
14656 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14657 Reference-manual comment line indentation.
14658
14659 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14660 GNAT-style comment beginning
14661
14662 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14663 Reformat comment blocks
14664
14665 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14666 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14667 GNAT-style layout (this is the default)
14668
14669 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14670 Compact layout
14671
14672 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14673 Uncompact layout
14674
14675 @item ^-notab^/NOTABS^
14676 All the VT characters are removed from the comment text. All the HT characters
14677 are expanded with the sequences of space characters to get to the next tab
14678 stops.
14679
14680 @end table
14681
14682 @ifclear vms
14683 @noindent
14684 The @option{-c1} and @option{-c2} switches are incompatible.
14685 The @option{-c3} and @option{-c4} switches are compatible with each other and
14686 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14687 the other comment formatting switches.
14688
14689 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14690 @end ifclear
14691
14692 @ifset vms
14693 @noindent
14694 For the @option{/COMMENTS_LAYOUT} qualifier:
14695 @itemize @bullet
14696 @item
14697 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14698 @item
14699 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14700 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14701 @end itemize
14702
14703 @noindent
14704 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14705 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14706 @end ifset
14707
14708 @node General Text Layout Control
14709 @subsection General Text Layout Control
14710
14711 @noindent
14712 These switches allow control over line length and indentation.
14713
14714 @table @option
14715 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
14716 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14717 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
14718
14719 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
14720 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14721 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
14722
14723 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
14724 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14725 Indentation level for continuation lines (relative to the line being
14726 continued), @i{nnn} from 1 .. 9.
14727 The default
14728 value is one less then the (normal) indentation level, unless the
14729 indentation is set to 1 (in which case the default value for continuation
14730 line indentation is also 1)
14731 @end table
14732
14733
14734 @node Other Formatting Options
14735 @subsection Other Formatting Options
14736
14737 @noindent
14738 These switches control the inclusion of missing end/exit labels, and
14739 the indentation level in @b{case} statements.
14740
14741 @table @option
14742 @item ^-e^/NO_MISSED_LABELS^
14743 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14744 Do not insert missing end/exit labels. An end label is the name of
14745 a construct that may optionally be repeated at the end of the
14746 construct's declaration;
14747 e.g., the names of packages, subprograms, and tasks.
14748 An exit label is the name of a loop that may appear as target
14749 of an exit statement within the loop.
14750 By default, @command{gnatpp} inserts these end/exit labels when
14751 they are absent from the original source. This option suppresses such
14752 insertion, so that the formatted source reflects the original.
14753
14754 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14755 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14756 Insert a Form Feed character after a pragma Page.
14757
14758 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
14759 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14760 Do not use an additional indentation level for @b{case} alternatives
14761 and variants if there are @i{nnn} or more (the default
14762 value is 10).
14763 If @i{nnn} is 0, an additional indentation level is
14764 used for @b{case} alternatives and variants regardless of their number.
14765 @end table
14766
14767 @node Setting the Source Search Path
14768 @subsection Setting the Source Search Path
14769
14770 @noindent
14771 To define the search path for the input source file, @command{gnatpp}
14772 uses the same switches as the GNAT compiler, with the same effects.
14773
14774 @table @option
14775 @item ^-I^/SEARCH=^@var{dir}
14776 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14777 The same as the corresponding gcc switch
14778
14779 @item ^-I-^/NOCURRENT_DIRECTORY^
14780 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14781 The same as the corresponding gcc switch
14782
14783 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14784 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14785 The same as the corresponding gcc switch
14786
14787 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14788 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14789 The same as the corresponding gcc switch
14790
14791 @end table
14792
14793
14794 @node Output File Control
14795 @subsection Output File Control
14796
14797 @noindent
14798 By default the output is sent to the file whose name is obtained by appending
14799 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14800 (if the file with this name already exists, it is unconditionally overwritten).
14801 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14802 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14803 as output file.
14804 The output may be redirected by the following switches:
14805
14806 @table @option
14807 @item ^-pipe^/STANDARD_OUTPUT^
14808 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14809 Send the output to @code{Standard_Output}
14810
14811 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14812 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14813 Write the output into @var{output_file}.
14814 If @var{output_file} already exists, @command{gnatpp} terminates without
14815 reading or processing the input file.
14816
14817 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14818 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14819 Write the output into @var{output_file}, overwriting the existing file
14820 (if one is present).
14821
14822 @item ^-r^/REPLACE^
14823 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14824 Replace the input source file with the reformatted output, and copy the
14825 original input source into the file whose name is obtained by appending the
14826 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14827 If a file with this name already exists, @command{gnatpp} terminates without
14828 reading or processing the input file.
14829
14830 @item ^-rf^/OVERRIDING_REPLACE^
14831 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14832 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14833 already exists, it is overwritten.
14834
14835 @item ^-rnb^/NO_BACKUP^
14836 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
14837 Replace the input source file with the reformatted output without
14838 creating any backup copy of the input source.
14839 @end table
14840
14841 @noindent
14842 Options @option{^-pipe^/STANDARD_OUTPUT^},
14843 @option{^-o^/OUTPUT^} and
14844 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14845 contains only one file to reformat
14846
14847 @node Other gnatpp Switches
14848 @subsection Other @code{gnatpp} Switches
14849
14850 @noindent
14851 The additional @command{gnatpp} switches are defined in this subsection.
14852
14853 @table @option
14854 @item ^-v^/VERBOSE^
14855 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14856 Verbose mode;
14857 @command{gnatpp} generates version information and then
14858 a trace of the actions it takes to produce or obtain the ASIS tree.
14859
14860 @item ^-w^/WARNINGS^
14861 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14862 Warning mode;
14863 @command{gnatpp} generates a warning whenever it can not provide
14864 a required layout in the result source.
14865 @end table
14866
14867
14868 @node Formatting Rules
14869 @section Formatting Rules
14870
14871 @noindent
14872 The following subsections show how @command{gnatpp} treats ``white space'',
14873 comments, program layout, and name casing.
14874 They provide the detailed descriptions of the switches shown above.
14875
14876 @menu
14877 * White Space and Empty Lines::
14878 * Formatting Comments::
14879 * Construct Layout::
14880 * Name Casing::
14881 @end menu
14882
14883
14884 @node White Space and Empty Lines
14885 @subsection White Space and Empty Lines
14886
14887 @noindent
14888 @command{gnatpp} does not have an option to control space characters.
14889 It will add or remove spaces according to the style illustrated by the
14890 examples in the @cite{Ada Reference Manual}.
14891
14892 The only format effectors
14893 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
14894 that will appear in the output file are platform-specific line breaks,
14895 and also format effectors within (but not at the end of) comments.
14896 In particular, each horizontal tab character that is not inside
14897 a comment will be treated as a space and thus will appear in the
14898 output file as zero or more spaces depending on
14899 the reformatting of the line in which it appears.
14900 The only exception is a Form Feed character, which is inserted after a
14901 pragma @code{Page} when @option{-ff} is set.
14902
14903 The output file will contain no lines with trailing ``white space'' (spaces,
14904 format effectors).
14905
14906 Empty lines in the original source are preserved
14907 only if they separate declarations or statements.
14908 In such contexts, a
14909 sequence of two or more empty lines is replaced by exactly one empty line.
14910 Note that a blank line will be removed if it separates two ``comment blocks''
14911 (a comment block is a sequence of whole-line comments).
14912 In order to preserve a visual separation between comment blocks, use an
14913 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
14914 Likewise, if for some reason you wish to have a sequence of empty lines,
14915 use a sequence of empty comments instead.
14916
14917
14918 @node Formatting Comments
14919 @subsection Formatting Comments
14920
14921 @noindent
14922 Comments in Ada code are of two kinds:
14923 @itemize @bullet
14924 @item
14925 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14926 ``white space'') on a line
14927
14928 @item
14929 an @emph{end-of-line comment}, which follows some other Ada lexical element
14930 on the same line.
14931 @end itemize
14932
14933 @noindent
14934 The indentation of a whole-line comment is that of either
14935 the preceding or following line in
14936 the formatted source, depending on switch settings as will be described below.
14937
14938 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
14939 between the end of the preceding Ada lexical element and the beginning
14940 of the comment as appear in the original source,
14941 unless either the comment has to be split to
14942 satisfy the line length limitation, or else the next line contains a
14943 whole line comment that is considered a continuation of this end-of-line
14944 comment (because it starts at the same position).
14945 In the latter two
14946 cases, the start of the end-of-line comment is moved right to the nearest
14947 multiple of the indentation level.
14948 This may result in a ``line overflow'' (the right-shifted comment extending
14949 beyond the maximum line length), in which case the comment is split as
14950 described below.
14951
14952 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
14953 (GNAT-style comment line indentation)
14954 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
14955 (reference-manual comment line indentation).
14956 With reference-manual style, a whole-line comment is indented as if it
14957 were a declaration or statement at the same place
14958 (i.e., according to the indentation of the preceding line(s)).
14959 With GNAT style, a whole-line comment that is immediately followed by an
14960 @b{if} or @b{case} statement alternative, a record variant, or the reserved
14961 word @b{begin}, is indented based on the construct that follows it.
14962
14963 For example:
14964 @smallexample @c ada
14965 @cartouche
14966 if A then
14967     null;
14968        -- some comment
14969 else
14970    null;
14971 end if;
14972 @end cartouche
14973 @end smallexample
14974
14975 @noindent
14976 Reference-manual indentation produces:
14977
14978 @smallexample @c ada
14979 @cartouche
14980 if A then
14981    null;
14982    --  some comment
14983 else
14984    null;
14985 end if;
14986 @end cartouche
14987 @end smallexample
14988
14989 @noindent
14990 while GNAT-style indentation produces:
14991
14992 @smallexample @c ada
14993 @cartouche
14994 if A then
14995    null;
14996 --  some comment
14997 else
14998    null;
14999 end if;
15000 @end cartouche
15001 @end smallexample
15002
15003 @noindent
15004 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15005 (GNAT style comment beginning) has the following
15006 effect:
15007
15008 @itemize @bullet
15009 @item
15010 For each whole-line comment that does not end with two hyphens,
15011 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15012 to ensure that there are at least two spaces between these hyphens and the
15013 first non-blank character of the comment.
15014 @end itemize
15015
15016 @noindent
15017 For an end-of-line comment, if in the original source the next line is a
15018 whole-line comment that starts at the same position
15019 as the end-of-line comment,
15020 then the whole-line comment (and all whole-line comments
15021 that follow it and that start at the same position)
15022 will start at this position in the output file.
15023
15024 @noindent
15025 That is, if in the original source we have:
15026
15027 @smallexample @c ada
15028 @cartouche
15029 begin
15030 A := B + C;            --  B must be in the range Low1..High1
15031                        --  C must be in the range Low2..High2
15032              --B+C will be in the range Low1+Low2..High1+High2
15033 X := X + 1;
15034 @end cartouche
15035 @end smallexample
15036
15037 @noindent
15038 Then in the formatted source we get
15039
15040 @smallexample @c ada
15041 @cartouche
15042 begin
15043    A := B + C;            --  B must be in the range Low1..High1
15044                           --  C must be in the range Low2..High2
15045    --  B+C will be in the range Low1+Low2..High1+High2
15046    X := X + 1;
15047 @end cartouche
15048 @end smallexample
15049
15050 @noindent
15051 A comment that exceeds the line length limit will be split.
15052 Unless switch
15053 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15054 the line belongs to a reformattable block, splitting the line generates a
15055 @command{gnatpp} warning.
15056 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15057 comments may be reformatted in typical
15058 word processor style (that is, moving words between lines and putting as
15059 many words in a line as possible).
15060
15061
15062 @node Construct Layout
15063 @subsection Construct Layout
15064
15065 @noindent
15066 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15067 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15068 layout on the one hand, and uncompact layout
15069 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15070 can be illustrated by the following examples:
15071
15072 @iftex
15073 @cartouche
15074 @multitable @columnfractions .5 .5
15075 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15076
15077 @item
15078 @smallexample @c ada
15079 type q is record
15080    a : integer;
15081    b : integer;
15082 end record;
15083 @end smallexample
15084 @tab
15085 @smallexample @c ada
15086 type q is
15087    record
15088       a : integer;
15089       b : integer;
15090    end record;
15091 @end smallexample
15092
15093 @item
15094 @smallexample @c ada
15095 Block : declare
15096    A : Integer := 3;
15097 begin
15098    Proc (A, A);
15099 end Block;
15100 @end smallexample
15101 @tab
15102 @smallexample @c ada
15103 Block :
15104    declare
15105       A : Integer := 3;
15106    begin
15107       Proc (A, A);
15108    end Block;
15109 @end smallexample
15110
15111 @item
15112 @smallexample @c ada
15113 Clear : for J in 1 .. 10 loop
15114    A (J) := 0;
15115 end loop Clear;
15116 @end smallexample
15117 @tab
15118 @smallexample @c ada
15119 Clear :
15120    for J in 1 .. 10 loop
15121       A (J) := 0;
15122    end loop Clear;
15123 @end smallexample
15124 @end multitable
15125 @end cartouche
15126 @end iftex
15127
15128 @ifnottex
15129 @smallexample
15130 @cartouche
15131 GNAT style, compact layout              Uncompact layout
15132
15133 type q is record                        type q is
15134    a : integer;                            record
15135    b : integer;                               a : integer;
15136 end record;                                   b : integer;
15137                                            end record;
15138
15139
15140 Block : declare                         Block :
15141    A : Integer := 3;                       declare
15142 begin                                         A : Integer := 3;
15143    Proc (A, A);                            begin
15144 end Block;                                    Proc (A, A);
15145                                            end Block;
15146
15147 Clear : for J in 1 .. 10 loop           Clear :
15148    A (J) := 0;                             for J in 1 .. 10 loop
15149 end loop Clear;                               A (J) := 0;
15150                                            end loop Clear;
15151 @end cartouche
15152 @end smallexample
15153 @end ifnottex
15154
15155 @noindent
15156 A further difference between GNAT style layout and compact layout is that
15157 GNAT style layout inserts empty lines as separation for
15158 compound statements, return statements and bodies.
15159
15160
15161 @node Name Casing
15162 @subsection Name Casing
15163
15164 @noindent
15165 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15166 the same casing as the corresponding defining identifier.
15167
15168 You control the casing for defining occurrences via the
15169 @option{^-n^/NAME_CASING^} switch.
15170 @ifclear vms
15171 With @option{-nD} (``as declared'', which is the default),
15172 @end ifclear
15173 @ifset vms
15174 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15175 @end ifset
15176 defining occurrences appear exactly as in the source file
15177 where they are declared.
15178 The other ^values for this switch^options for this qualifier^ ---
15179 @option{^-nU^UPPER_CASE^},
15180 @option{^-nL^LOWER_CASE^},
15181 @option{^-nM^MIXED_CASE^} ---
15182 result in
15183 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15184 If @command{gnatpp} changes the casing of a defining
15185 occurrence, it analogously changes the casing of all the
15186 usage occurrences of this name.
15187
15188 If the defining occurrence of a name is not in the source compilation unit
15189 currently being processed by @command{gnatpp}, the casing of each reference to
15190 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15191 switch (subject to the dictionary file mechanism described below).
15192 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15193 had affected the
15194 casing for the defining occurrence of the name.
15195
15196 Some names may need to be spelled with casing conventions that are not
15197 covered by the upper-, lower-, and mixed-case transformations.
15198 You can arrange correct casing by placing such names in a
15199 @emph{dictionary file},
15200 and then supplying a @option{^-D^/DICTIONARY^} switch.
15201 The casing of names from dictionary files overrides
15202 any @option{^-n^/NAME_CASING^} switch.
15203
15204 To handle the casing of Ada predefined names and the names from GNAT libraries,
15205 @command{gnatpp} assumes a default dictionary file.
15206 The name of each predefined entity is spelled with the same casing as is used
15207 for the entity in the @cite{Ada Reference Manual}.
15208 The name of each entity in the GNAT libraries is spelled with the same casing
15209 as is used in the declaration of that entity.
15210
15211 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15212 default dictionary file.
15213 Instead, the casing for predefined and GNAT-defined names will be established
15214 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15215 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15216 will appear as just shown,
15217 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15218 To ensure that even such names are rendered in uppercase,
15219 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15220 (or else, less conveniently, place these names in upper case in a dictionary
15221 file).
15222
15223 A dictionary file is
15224 a plain text file; each line in this file can be either a blank line
15225 (containing only space characters and ASCII.HT characters), an Ada comment
15226 line, or the specification of exactly one @emph{casing schema}.
15227
15228 A casing schema is a string that has the following syntax:
15229
15230 @smallexample
15231 @cartouche
15232   @var{casing_schema} ::= @var{identifier} | [*]@var{simple_identifier}[*]
15233
15234   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15235 @end cartouche
15236 @end smallexample
15237
15238 @noindent
15239 (The @code{[]} metanotation stands for an optional part;
15240 see @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15241 @var{identifier} lexical element and the @var{letter_or_digit} category).
15242
15243 The casing schema string can be followed by white space and/or an Ada-style
15244 comment; any amount of white space is allowed before the string.
15245
15246 If a dictionary file is passed as
15247 @ifclear vms
15248 the value of a @option{-D@var{file}} switch
15249 @end ifclear
15250 @ifset vms
15251 an option to the @option{/DICTIONARY} qualifier
15252 @end ifset
15253 then for every
15254 simple name and every identifier, @command{gnatpp} checks if the dictionary
15255 defines the casing for the name or for some of its parts (the term ``subword''
15256 is used below to denote the part of a name which is delimited by ``_'' or by
15257 the beginning or end of the word and which does not contain any ``_'' inside):
15258
15259 @itemize @bullet
15260 @item
15261 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15262 the casing defined by the dictionary; no subwords are checked for this word
15263
15264 @item
15265 for the first subword (that is, for the subword preceding the leftmost
15266 ``_''), @command{gnatpp} checks if the dictionary contains the corresponding
15267 string of the form @code{@var{simple_identifier}*}, and if it does, the
15268 casing of this @var{simple_identifier} is used for this subword
15269
15270 @item
15271 for the last subword (following the rightmost ``_'') @command{gnatpp}
15272 checks if the dictionary contains the corresponding string of the form
15273 @code{*@var{simple_identifier}}, and if it does, the casing of this
15274 @var{simple_identifier} is used for this subword
15275
15276 @item
15277 for every intermediate subword (surrounded by two'_') @command{gnatpp} checks
15278 if the dictionary contains the corresponding string of the form
15279 @code{*@var{simple_identifier}*}, and if it does, the casing of this
15280 simple_identifier is used for this subword
15281
15282 @item
15283 if more than one dictionary file is passed as @command{gnatpp} switches, each
15284 dictionary adds new casing exceptions and overrides all the existing casing
15285 exceptions set by the previous dictionaries
15286
15287 @item
15288 when @command{gnatpp} checks if the word or subword is in the dictionary,
15289 this check is not case sensitive
15290 @end itemize
15291
15292 @noindent
15293 For example, suppose we have the following source to reformat:
15294
15295 @smallexample @c ada
15296 @cartouche
15297 procedure test is
15298    name1 : integer := 1;
15299    name4_name3_name2 : integer := 2;
15300    name2_name3_name4 : Boolean;
15301    name1_var : Float;
15302 begin
15303    name2_name3_name4 := name4_name3_name2 > name1;
15304 end;
15305 @end cartouche
15306 @end smallexample
15307
15308 @noindent
15309 And suppose we have two dictionaries:
15310
15311 @smallexample
15312 @cartouche
15313 @i{dict1:}
15314    NAME1
15315    *NaMe3*
15316    *NAME2
15317 @end cartouche
15318
15319 @cartouche
15320 @i{dict2:}
15321   *NAME3*
15322 @end cartouche
15323 @end smallexample
15324
15325 @noindent
15326 If @command{gnatpp} is called with the following switches:
15327
15328 @smallexample
15329 @ifclear vms
15330 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15331 @end ifclear
15332 @ifset vms
15333 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15334 @end ifset
15335 @end smallexample
15336
15337 @noindent
15338 then we will get the following name casing in the @command{gnatpp} output:
15339
15340 @smallexample @c ada
15341 @cartouche
15342 procedure Test is
15343    NAME1             : Integer := 1;
15344    Name4_NAME3_NAME2 : integer := 2;
15345    Name2_NAME3_Name4 : Boolean;
15346    Name1_Var         : Float;
15347 begin
15348    Name2_NAME3_Name4 := Name4_NAME3_NAME2 > NAME1;
15349 end Test;
15350 @end cartouche
15351 @end smallexample
15352
15353
15354
15355 @c ***********************************
15356 @node File Name Krunching Using gnatkr
15357 @chapter File Name Krunching Using @code{gnatkr}
15358 @findex gnatkr
15359
15360 @noindent
15361 This chapter discusses the method used by the compiler to shorten
15362 the default file names chosen for Ada units so that they do not
15363 exceed the maximum length permitted. It also describes the
15364 @code{gnatkr} utility that can be used to determine the result of
15365 applying this shortening.
15366 @menu
15367 * About gnatkr::
15368 * Using gnatkr::
15369 * Krunching Method::
15370 * Examples of gnatkr Usage::
15371 @end menu
15372
15373 @node About gnatkr
15374 @section About @code{gnatkr}
15375
15376 @noindent
15377 The default file naming rule in GNAT
15378 is that the file name must be derived from
15379 the unit name. The exact default rule is as follows:
15380 @itemize @bullet
15381 @item
15382 Take the unit name and replace all dots by hyphens.
15383 @item
15384 If such a replacement occurs in the
15385 second character position of a name, and the first character is
15386 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
15387 ^~ (tilde)^$ (dollar sign)^
15388 instead of a minus.
15389 @end itemize
15390 The reason for this exception is to avoid clashes
15391 with the standard names for children of System, Ada, Interfaces,
15392 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
15393 respectively.
15394
15395 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15396 switch of the compiler activates a ``krunching''
15397 circuit that limits file names to nn characters (where nn is a decimal
15398 integer). For example, using OpenVMS,
15399 where the maximum file name length is
15400 39, the value of nn is usually set to 39, but if you want to generate
15401 a set of files that would be usable if ported to a system with some
15402 different maximum file length, then a different value can be specified.
15403 The default value of 39 for OpenVMS need not be specified.
15404
15405 The @code{gnatkr} utility can be used to determine the krunched name for
15406 a given file, when krunched to a specified maximum length.
15407
15408 @node Using gnatkr
15409 @section Using @code{gnatkr}
15410
15411 @noindent
15412 The @code{gnatkr} command has the form
15413
15414 @ifclear vms
15415 @smallexample
15416 $ gnatkr @var{name} [@var{length}]
15417 @end smallexample
15418 @end ifclear
15419
15420 @ifset vms
15421 @smallexample
15422 $ gnatkr @var{name} /COUNT=nn
15423 @end smallexample
15424 @end ifset
15425
15426 @noindent
15427 @var{name} is the uncrunched file name, derived from the name of the unit
15428 in the standard manner described in the previous section (i.e. in particular
15429 all dots are replaced by hyphens). The file name may or may not have an
15430 extension (defined as a suffix of the form period followed by arbitrary
15431 characters other than period). If an extension is present then it will
15432 be preserved in the output. For example, when krunching @file{hellofile.ads}
15433 to eight characters, the result will be hellofil.ads.
15434
15435 Note: for compatibility with previous versions of @code{gnatkr} dots may
15436 appear in the name instead of hyphens, but the last dot will always be
15437 taken as the start of an extension. So if @code{gnatkr} is given an argument
15438 such as @file{Hello.World.adb} it will be treated exactly as if the first
15439 period had been a hyphen, and for example krunching to eight characters
15440 gives the result @file{hellworl.adb}.
15441
15442 Note that the result is always all lower case (except on OpenVMS where it is
15443 all upper case). Characters of the other case are folded as required.
15444
15445 @var{length} represents the length of the krunched name. The default
15446 when no argument is given is ^8^39^ characters. A length of zero stands for
15447 unlimited, in other words do not chop except for system files where the
15448 impled crunching length is always eight characters.
15449
15450 @noindent
15451 The output is the krunched name. The output has an extension only if the
15452 original argument was a file name with an extension.
15453
15454 @node Krunching Method
15455 @section Krunching Method
15456
15457 @noindent
15458 The initial file name is determined by the name of the unit that the file
15459 contains. The name is formed by taking the full expanded name of the
15460 unit and replacing the separating dots with hyphens and
15461 using ^lowercase^uppercase^
15462 for all letters, except that a hyphen in the second character position is
15463 replaced by a ^tilde^dollar sign^ if the first character is
15464 ^a, i, g, or s^A, I, G, or S^.
15465 The extension is @code{.ads} for a
15466 specification and @code{.adb} for a body.
15467 Krunching does not affect the extension, but the file name is shortened to
15468 the specified length by following these rules:
15469
15470 @itemize @bullet
15471 @item
15472 The name is divided into segments separated by hyphens, tildes or
15473 underscores and all hyphens, tildes, and underscores are
15474 eliminated. If this leaves the name short enough, we are done.
15475
15476 @item
15477 If the name is too long, the longest segment is located (left-most
15478 if there are two of equal length), and shortened by dropping
15479 its last character. This is repeated until the name is short enough.
15480
15481 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15482 to fit the name into 8 characters as required by some operating systems.
15483
15484 @smallexample
15485 our-strings-wide_fixed 22
15486 our strings wide fixed 19
15487 our string  wide fixed 18
15488 our strin   wide fixed 17
15489 our stri    wide fixed 16
15490 our stri    wide fixe  15
15491 our str     wide fixe  14
15492 our str     wid  fixe  13
15493 our str     wid  fix   12
15494 ou  str     wid  fix   11
15495 ou  st      wid  fix   10
15496 ou  st      wi   fix   9
15497 ou  st      wi   fi    8
15498 Final file name: oustwifi.adb
15499 @end smallexample
15500
15501 @item
15502 The file names for all predefined units are always krunched to eight
15503 characters. The krunching of these predefined units uses the following
15504 special prefix replacements:
15505
15506 @table @file
15507 @item ada-
15508 replaced by @file{^a^A^-}
15509
15510 @item gnat-
15511 replaced by @file{^g^G^-}
15512
15513 @item interfaces-
15514 replaced by @file{^i^I^-}
15515
15516 @item system-
15517 replaced by @file{^s^S^-}
15518 @end table
15519
15520 These system files have a hyphen in the second character position. That
15521 is why normal user files replace such a character with a
15522 ^tilde^dollar sign^, to
15523 avoid confusion with system file names.
15524
15525 As an example of this special rule, consider
15526 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15527
15528 @smallexample
15529 ada-strings-wide_fixed 22
15530 a-  strings wide fixed 18
15531 a-  string  wide fixed 17
15532 a-  strin   wide fixed 16
15533 a-  stri    wide fixed 15
15534 a-  stri    wide fixe  14
15535 a-  str     wide fixe  13
15536 a-  str     wid  fixe  12
15537 a-  str     wid  fix   11
15538 a-  st      wid  fix   10
15539 a-  st      wi   fix   9
15540 a-  st      wi   fi    8
15541 Final file name: a-stwifi.adb
15542 @end smallexample
15543 @end itemize
15544
15545 Of course no file shortening algorithm can guarantee uniqueness over all
15546 possible unit names, and if file name krunching is used then it is your
15547 responsibility to ensure that no name clashes occur. The utility
15548 program @code{gnatkr} is supplied for conveniently determining the
15549 krunched name of a file.
15550
15551 @node Examples of gnatkr Usage
15552 @section Examples of @code{gnatkr} Usage
15553
15554 @smallexample
15555 @iftex
15556 @leftskip=0cm
15557 @end iftex
15558 @ifclear vms
15559 $ gnatkr very_long_unit_name.ads      --> velounna.ads
15560 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15561 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15562 $ gnatkr grandparent-parent-child     --> grparchi
15563 @end ifclear
15564 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15565 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15566 @end smallexample
15567
15568 @node Preprocessing Using gnatprep
15569 @chapter Preprocessing Using @code{gnatprep}
15570 @findex gnatprep
15571
15572 @noindent
15573 The @code{gnatprep} utility provides
15574 a simple preprocessing capability for Ada programs.
15575 It is designed for use with GNAT, but is not dependent on any special
15576 features of GNAT.
15577
15578 @menu
15579 * Using gnatprep::
15580 * Switches for gnatprep::
15581 * Form of Definitions File::
15582 * Form of Input Text for gnatprep::
15583 @end menu
15584
15585 @node Using gnatprep
15586 @section Using @code{gnatprep}
15587
15588 @noindent
15589 To call @code{gnatprep} use
15590
15591 @smallexample
15592 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
15593 @end smallexample
15594
15595 @noindent
15596 where
15597 @table @code
15598 @item infile
15599 is the full name of the input file, which is an Ada source
15600 file containing preprocessor directives.
15601
15602 @item outfile
15603 is the full name of the output file, which is an Ada source
15604 in standard Ada form. When used with GNAT, this file name will
15605 normally have an ads or adb suffix.
15606
15607 @item deffile
15608 is the full name of a text file containing definitions of
15609 symbols to be referenced by the preprocessor. This argument is
15610 optional, and can be replaced by the use of the @option{-D} switch.
15611
15612 @item switches
15613 is an optional sequence of switches as described in the next section.
15614 @end table
15615
15616 @node Switches for gnatprep
15617 @section Switches for @code{gnatprep}
15618
15619 @table @option
15620 @c !sort!
15621
15622 @item ^-b^/BLANK_LINES^
15623 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15624 Causes both preprocessor lines and the lines deleted by
15625 preprocessing to be replaced by blank lines in the output source file,
15626 preserving line numbers in the output file.
15627
15628 @item ^-c^/COMMENTS^
15629 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15630 Causes both preprocessor lines and the lines deleted
15631 by preprocessing to be retained in the output source as comments marked
15632 with the special string @code{"--! "}. This option will result in line numbers
15633 being preserved in the output file.
15634
15635 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15636 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15637 Defines a new symbol, associated with value. If no value is given on the
15638 command line, then symbol is considered to be @code{True}. This switch
15639 can be used in place of a definition file.
15640
15641 @ifset vms
15642 @item /REMOVE
15643 @cindex @option{/REMOVE} (@command{gnatprep})
15644 This is the default setting which causes lines deleted by preprocessing
15645 to be entirely removed from the output file.
15646 @end ifset
15647
15648 @item ^-r^/REFERENCE^
15649 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15650 Causes a @code{Source_Reference} pragma to be generated that
15651 references the original input file, so that error messages will use
15652 the file name of this original file. The use of this switch implies
15653 that preprocessor lines are not to be removed from the file, so its
15654 use will force @option{^-b^/BLANK_LINES^} mode if
15655 @option{^-c^/COMMENTS^}
15656 has not been specified explicitly.
15657
15658 Note that if the file to be preprocessed contains multiple units, then
15659 it will be necessary to @code{gnatchop} the output file from
15660 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15661 in the preprocessed file, it will be respected by
15662 @code{gnatchop ^-r^/REFERENCE^}
15663 so that the final chopped files will correctly refer to the original
15664 input source file for @code{gnatprep}.
15665
15666 @item ^-s^/SYMBOLS^
15667 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15668 Causes a sorted list of symbol names and values to be
15669 listed on the standard output file.
15670
15671 @item ^-u^/UNDEFINED^
15672 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15673 Causes undefined symbols to be treated as having the value FALSE in the context
15674 of a preprocessor test. In the absence of this option, an undefined symbol in
15675 a @code{#if} or @code{#elsif} test will be treated as an error.
15676
15677 @end table
15678
15679 @ifclear vms
15680 @noindent
15681 Note: if neither @option{-b} nor @option{-c} is present,
15682 then preprocessor lines and
15683 deleted lines are completely removed from the output, unless -r is
15684 specified, in which case -b is assumed.
15685 @end ifclear
15686
15687 @node Form of Definitions File
15688 @section Form of Definitions File
15689
15690 @noindent
15691 The definitions file contains lines of the form
15692
15693 @smallexample
15694 symbol := value
15695 @end smallexample
15696
15697 @noindent
15698 where symbol is an identifier, following normal Ada (case-insensitive)
15699 rules for its syntax, and value is one of the following:
15700
15701 @itemize @bullet
15702 @item
15703 Empty, corresponding to a null substitution
15704 @item
15705 A string literal using normal Ada syntax
15706 @item
15707 Any sequence of characters from the set
15708 (letters, digits, period, underline).
15709 @end itemize
15710
15711 @noindent
15712 Comment lines may also appear in the definitions file, starting with
15713 the usual @code{--},
15714 and comments may be added to the definitions lines.
15715
15716 @node Form of Input Text for gnatprep
15717 @section Form of Input Text for @code{gnatprep}
15718
15719 @noindent
15720 The input text may contain preprocessor conditional inclusion lines,
15721 as well as general symbol substitution sequences.
15722
15723 The preprocessor conditional inclusion commands have the form
15724
15725 @smallexample
15726 @group
15727 @cartouche
15728 #if @i{expression} [then]
15729    lines
15730 #elsif @i{expression} [then]
15731    lines
15732 #elsif @i{expression} [then]
15733    lines
15734 ...
15735 #else
15736    lines
15737 #end if;
15738 @end cartouche
15739 @end group
15740 @end smallexample
15741
15742 @noindent
15743 In this example, @i{expression} is defined by the following grammar:
15744 @smallexample
15745 @i{expression} ::=  <symbol>
15746 @i{expression} ::=  <symbol> = "<value>"
15747 @i{expression} ::=  <symbol> = <symbol>
15748 @i{expression} ::=  <symbol> 'Defined
15749 @i{expression} ::=  not @i{expression}
15750 @i{expression} ::=  @i{expression} and @i{expression}
15751 @i{expression} ::=  @i{expression} or @i{expression}
15752 @i{expression} ::=  @i{expression} and then @i{expression}
15753 @i{expression} ::=  @i{expression} or else @i{expression}
15754 @i{expression} ::=  ( @i{expression} )
15755 @end smallexample
15756
15757 @noindent
15758 For the first test (@i{expression} ::= <symbol>) the symbol must have
15759 either the value true or false, that is to say the right-hand of the
15760 symbol definition must be one of the (case-insensitive) literals
15761 @code{True} or @code{False}. If the value is true, then the
15762 corresponding lines are included, and if the value is false, they are
15763 excluded.
15764
15765 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15766 the symbol has been defined in the definition file or by a @option{-D}
15767 switch on the command line. Otherwise, the test is false.
15768
15769 The equality tests are case insensitive, as are all the preprocessor lines.
15770
15771 If the symbol referenced is not defined in the symbol definitions file,
15772 then the effect depends on whether or not switch @option{-u}
15773 is specified. If so, then the symbol is treated as if it had the value
15774 false and the test fails. If this switch is not specified, then
15775 it is an error to reference an undefined symbol. It is also an error to
15776 reference a symbol that is defined with a value other than @code{True}
15777 or @code{False}.
15778
15779 The use of the @code{not} operator inverts the sense of this logical test, so
15780 that the lines are included only if the symbol is not defined.
15781 The @code{then} keyword is optional as shown
15782
15783 The @code{#} must be the first non-blank character on a line, but
15784 otherwise the format is free form. Spaces or tabs may appear between
15785 the @code{#} and the keyword. The keywords and the symbols are case
15786 insensitive as in normal Ada code. Comments may be used on a
15787 preprocessor line, but other than that, no other tokens may appear on a
15788 preprocessor line. Any number of @code{elsif} clauses can be present,
15789 including none at all. The @code{else} is optional, as in Ada.
15790
15791 The @code{#} marking the start of a preprocessor line must be the first
15792 non-blank character on the line, i.e. it must be preceded only by
15793 spaces or horizontal tabs.
15794
15795 Symbol substitution outside of preprocessor lines is obtained by using
15796 the sequence
15797
15798 @smallexample
15799 $symbol
15800 @end smallexample
15801
15802 @noindent
15803 anywhere within a source line, except in a comment or within a
15804 string literal. The identifier
15805 following the @code{$} must match one of the symbols defined in the symbol
15806 definition file, and the result is to substitute the value of the
15807 symbol in place of @code{$symbol} in the output file.
15808
15809 Note that although the substitution of strings within a string literal
15810 is not possible, it is possible to have a symbol whose defined value is
15811 a string literal. So instead of setting XYZ to @code{hello} and writing:
15812
15813 @smallexample
15814 Header : String := "$XYZ";
15815 @end smallexample
15816
15817 @noindent
15818 you should set XYZ to @code{"hello"} and write:
15819
15820 @smallexample
15821 Header : String := $XYZ;
15822 @end smallexample
15823
15824 @noindent
15825 and then the substitution will occur as desired.
15826
15827 @ifset vms
15828 @node The GNAT Run-Time Library Builder gnatlbr
15829 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
15830 @findex gnatlbr
15831 @cindex Library builder
15832
15833 @noindent
15834 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
15835 supplied configuration pragmas.
15836
15837 @menu
15838 * Running gnatlbr::
15839 * Switches for gnatlbr::
15840 * Examples of gnatlbr Usage::
15841 @end menu
15842
15843 @node Running gnatlbr
15844 @section Running @code{gnatlbr}
15845
15846 @noindent
15847 The @code{gnatlbr} command has the form
15848
15849 @smallexample
15850 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
15851 @end smallexample
15852
15853 @node Switches for gnatlbr
15854 @section Switches for @code{gnatlbr}
15855
15856 @noindent
15857 @code{gnatlbr} recognizes the following switches:
15858
15859 @table @option
15860 @c !sort!
15861 @item /CREATE=directory
15862 @cindex @code{/CREATE} (@code{gnatlbr})
15863      Create the new run-time library in the specified directory.
15864
15865 @item /SET=directory
15866 @cindex @code{/SET} (@code{gnatlbr})
15867      Make the library in the specified directory the current run-time
15868      library.
15869
15870 @item /DELETE=directory
15871 @cindex @code{/DELETE} (@code{gnatlbr})
15872      Delete the run-time library in the specified directory.
15873
15874 @item /CONFIG=file
15875 @cindex @code{/CONFIG} (@code{gnatlbr})
15876      With /CREATE:
15877      Use the configuration pragmas in the specified file when building
15878      the library.
15879
15880      With /SET:
15881      Use the configuration pragmas in the specified file when compiling.
15882
15883 @end table
15884
15885 @node Examples of gnatlbr Usage
15886 @section Example of @code{gnatlbr} Usage
15887
15888 @smallexample
15889 Contents of VAXFLOAT.ADC:
15890 pragma Float_Representation (VAX_Float);
15891
15892 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
15893
15894 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
15895
15896 @end smallexample
15897 @end ifset
15898
15899 @node The GNAT Library Browser gnatls
15900 @chapter The GNAT Library Browser @code{gnatls}
15901 @findex gnatls
15902 @cindex Library browser
15903
15904 @noindent
15905 @code{gnatls} is a tool that outputs information about compiled
15906 units. It gives the relationship between objects, unit names and source
15907 files. It can also be used to check the source dependencies of a unit
15908 as well as various characteristics.
15909
15910 @menu
15911 * Running gnatls::
15912 * Switches for gnatls::
15913 * Examples of gnatls Usage::
15914 @end menu
15915
15916 @node Running gnatls
15917 @section Running @code{gnatls}
15918
15919 @noindent
15920 The @code{gnatls} command has the form
15921
15922 @smallexample
15923 $ gnatls switches @var{object_or_ali_file}
15924 @end smallexample
15925
15926 @noindent
15927 The main argument is the list of object or @file{ali} files
15928 (@pxref{The Ada Library Information Files})
15929 for which information is requested.
15930
15931 In normal mode, without additional option, @code{gnatls} produces a
15932 four-column listing. Each line represents information for a specific
15933 object. The first column gives the full path of the object, the second
15934 column gives the name of the principal unit in this object, the third
15935 column gives the status of the source and the fourth column gives the
15936 full path of the source representing this unit.
15937 Here is a simple example of use:
15938
15939 @smallexample
15940 $ gnatls *.o
15941 ^./^[]^demo1.o            demo1            DIF demo1.adb
15942 ^./^[]^demo2.o            demo2             OK demo2.adb
15943 ^./^[]^hello.o            h1                OK hello.adb
15944 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15945 ^./^[]^instr.o            instr             OK instr.adb
15946 ^./^[]^tef.o              tef              DIF tef.adb
15947 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15948 ^./^[]^tgef.o             tgef             DIF tgef.adb
15949 @end smallexample
15950
15951 @noindent
15952 The first line can be interpreted as follows: the main unit which is
15953 contained in
15954 object file @file{demo1.o} is demo1, whose main source is in
15955 @file{demo1.adb}. Furthermore, the version of the source used for the
15956 compilation of demo1 has been modified (DIF). Each source file has a status
15957 qualifier which can be:
15958
15959 @table @code
15960 @item OK (unchanged)
15961 The version of the source file used for the compilation of the
15962 specified unit corresponds exactly to the actual source file.
15963
15964 @item MOK (slightly modified)
15965 The version of the source file used for the compilation of the
15966 specified unit differs from the actual source file but not enough to
15967 require recompilation. If you use gnatmake with the qualifier
15968 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15969 MOK will not be recompiled.
15970
15971 @item DIF (modified)
15972 No version of the source found on the path corresponds to the source
15973 used to build this object.
15974
15975 @item ??? (file not found)
15976 No source file was found for this unit.
15977
15978 @item HID (hidden,  unchanged version not first on PATH)
15979 The version of the source that corresponds exactly to the source used
15980 for compilation has been found on the path but it is hidden by another
15981 version of the same source that has been modified.
15982
15983 @end table
15984
15985 @node Switches for gnatls
15986 @section Switches for @code{gnatls}
15987
15988 @noindent
15989 @code{gnatls} recognizes the following switches:
15990
15991 @table @option
15992 @c !sort!
15993 @item ^-a^/ALL_UNITS^
15994 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15995 Consider all units, including those of the predefined Ada library.
15996 Especially useful with @option{^-d^/DEPENDENCIES^}.
15997
15998 @item ^-d^/DEPENDENCIES^
15999 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16000 List sources from which specified units depend on.
16001
16002 @item ^-h^/OUTPUT=OPTIONS^
16003 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16004 Output the list of options.
16005
16006 @item ^-o^/OUTPUT=OBJECTS^
16007 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16008 Only output information about object files.
16009
16010 @item ^-s^/OUTPUT=SOURCES^
16011 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16012 Only output information about source files.
16013
16014 @item ^-u^/OUTPUT=UNITS^
16015 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16016 Only output information about compilation units.
16017
16018 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16019 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16020 @itemx ^-I^/SEARCH=^@var{dir}
16021 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
16022 @itemx -nostdinc
16023 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16024 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16025 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16026 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16027 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
16028 (see @ref{Switches for gnatmake}).
16029
16030 @item --RTS=@var{rts-path}
16031 @cindex @option{--RTS} (@code{gnatls})
16032 Specifies the default location of the runtime library. Same meaning as the
16033 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
16034
16035 @item ^-v^/OUTPUT=VERBOSE^
16036 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16037 Verbose mode. Output the complete source and object paths. Do not use
16038 the default column layout but instead use long format giving as much as
16039 information possible on each requested units, including special
16040 characteristics such as:
16041
16042 @table @code
16043 @item  Preelaborable
16044 The unit is preelaborable in the Ada 95 sense.
16045
16046 @item No_Elab_Code
16047 No elaboration code has been produced by the compiler for this unit.
16048
16049 @item Pure
16050 The unit is pure in the Ada 95 sense.
16051
16052 @item Elaborate_Body
16053 The unit contains a pragma Elaborate_Body.
16054
16055 @item Remote_Types
16056 The unit contains a pragma Remote_Types.
16057
16058 @item Shared_Passive
16059 The unit contains a pragma Shared_Passive.
16060
16061 @item Predefined
16062 This unit is part of the predefined environment and cannot be modified
16063 by the user.
16064
16065 @item Remote_Call_Interface
16066 The unit contains a pragma Remote_Call_Interface.
16067
16068 @end table
16069
16070 @end table
16071
16072 @node Examples of gnatls Usage
16073 @section Example of @code{gnatls} Usage
16074 @ifclear vms
16075
16076 @noindent
16077 Example of using the verbose switch. Note how the source and
16078 object paths are affected by the -I switch.
16079
16080 @smallexample
16081 $ gnatls -v -I.. demo1.o
16082
16083 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
16084
16085 Source Search Path:
16086    <Current_Directory>
16087    ../
16088    /home/comar/local/adainclude/
16089
16090 Object Search Path:
16091    <Current_Directory>
16092    ../
16093    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
16094
16095 ./demo1.o
16096    Unit =>
16097      Name   => demo1
16098      Kind   => subprogram body
16099      Flags  => No_Elab_Code
16100      Source => demo1.adb    modified
16101 @end smallexample
16102
16103 @noindent
16104 The following is an example of use of the dependency list.
16105 Note the use of the -s switch
16106 which gives a straight list of source files. This can be useful for
16107 building specialized scripts.
16108
16109 @smallexample
16110 $ gnatls -d demo2.o
16111 ./demo2.o   demo2        OK demo2.adb
16112                          OK gen_list.ads
16113                          OK gen_list.adb
16114                          OK instr.ads
16115                          OK instr-child.ads
16116
16117 $ gnatls -d -s -a demo1.o
16118 demo1.adb
16119 /home/comar/local/adainclude/ada.ads
16120 /home/comar/local/adainclude/a-finali.ads
16121 /home/comar/local/adainclude/a-filico.ads
16122 /home/comar/local/adainclude/a-stream.ads
16123 /home/comar/local/adainclude/a-tags.ads
16124 gen_list.ads
16125 gen_list.adb
16126 /home/comar/local/adainclude/gnat.ads
16127 /home/comar/local/adainclude/g-io.ads
16128 instr.ads
16129 /home/comar/local/adainclude/system.ads
16130 /home/comar/local/adainclude/s-exctab.ads
16131 /home/comar/local/adainclude/s-finimp.ads
16132 /home/comar/local/adainclude/s-finroo.ads
16133 /home/comar/local/adainclude/s-secsta.ads
16134 /home/comar/local/adainclude/s-stalib.ads
16135 /home/comar/local/adainclude/s-stoele.ads
16136 /home/comar/local/adainclude/s-stratt.ads
16137 /home/comar/local/adainclude/s-tasoli.ads
16138 /home/comar/local/adainclude/s-unstyp.ads
16139 /home/comar/local/adainclude/unchconv.ads
16140 @end smallexample
16141 @end ifclear
16142
16143 @ifset vms
16144 @smallexample
16145 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16146
16147 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16148 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16149 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16150 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16151 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16152 demo1.adb
16153 gen_list.ads
16154 gen_list.adb
16155 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16156 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16157 instr.ads
16158 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16159 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16160 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16161 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16162 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16163 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16164 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16165 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16166 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16167 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16168 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16169 @end smallexample
16170 @end ifset
16171
16172 @node Cleaning Up Using gnatclean
16173 @chapter Cleaning Up Using @code{gnatclean}
16174 @findex gnatclean
16175 @cindex Cleaning tool
16176
16177 @noindent
16178 @code{gnatclean} is a tool that allows the deletion of files produced by the
16179 compiler, binder and linker, including ALI files, object files, tree files,
16180 expanded source files, library files, interface copy source files, binder
16181 generated files and executable files.
16182
16183 @menu
16184 * Running gnatclean::
16185 * Switches for gnatclean::
16186 * Examples of gnatclean Usage::
16187 @end menu
16188
16189 @node Running gnatclean
16190 @section Running @code{gnatclean}
16191
16192 @noindent
16193 The @code{gnatclean} command has the form:
16194
16195 @smallexample
16196 $ gnatclean switches @var{names}
16197 @end smallexample
16198
16199 @noindent
16200 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16201 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16202 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16203
16204 @noindent
16205 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16206 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16207 the linker. In informative-only mode, specified by switch
16208 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16209 normal mode is listed, but no file is actually deleted.
16210
16211 @node Switches for gnatclean
16212 @section Switches for @code{gnatclean}
16213
16214 @noindent
16215 @code{gnatclean} recognizes the following switches:
16216
16217 @table @option
16218 @c !sort!
16219 @item ^-c^/COMPILER_FILES_ONLY^
16220 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16221 Only attempt to delete the files produced by the compiler, not those produced
16222 by the binder or the linker. The files that are not to be deleted are library
16223 files, interface copy files, binder generated files and executable files.
16224
16225 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16226 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16227 Indicate that ALI and object files should normally be found in directory
16228 @var{dir}.
16229
16230 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16231 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16232 When using project files, if some errors or warnings are detected during
16233 parsing and verbose mode is not in effect (no use of switch
16234 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16235 file, rather than its simple file name.
16236
16237 @item ^-h^/HELP^
16238 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16239 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16240
16241 @item ^-n^/NODELETE^
16242 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16243 Informative-only mode. Do not delete any files. Output the list of the files
16244 that would have been deleted if this switch was not specified.
16245
16246 @item ^-P^/PROJECT_FILE=^@var{project}
16247 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16248 Use project file @var{project}. Only one such switch can be used.
16249 When cleaning a project file, the files produced by the compilation of the
16250 immediate sources or inherited sources of the project files are to be
16251 deleted. This is not depending on the presence or not of executable names
16252 on the command line.
16253
16254 @item ^-q^/QUIET^
16255 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16256 Quiet output. If there are no error, do not ouuput anything, except in
16257 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16258 (switch ^-n^/NODELETE^).
16259
16260 @item ^-r^/RECURSIVE^
16261 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16262 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16263 clean all imported and extended project files, recursively. If this switch
16264 is not specified, only the files related to the main project file are to be
16265 deleted. This switch has no effect if no project file is specified.
16266
16267 @item ^-v^/VERBOSE^
16268 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16269 Verbose mode.
16270
16271 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16272 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16273 Indicates the verbosity of the parsing of GNAT project files.
16274 See @ref{Switches Related to Project Files}.
16275
16276 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16277 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16278 Indicates that external variable @var{name} has the value @var{value}.
16279 The Project Manager will use this value for occurrences of
16280 @code{external(name)} when parsing the project file.
16281 See @ref{Switches Related to Project Files}.
16282
16283 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16284 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16285 When searching for ALI and object files, look in directory
16286 @var{dir}.
16287
16288 @item ^-I^/SEARCH=^@var{dir}
16289 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16290 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16291
16292 @item ^-I-^/NOCURRENT_DIRECTORY^
16293 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16294 @cindex Source files, suppressing search
16295 Do not look for ALI or object files in the directory
16296 where @code{gnatclean} was invoked.
16297
16298 @end table
16299
16300 @node Examples of gnatclean Usage
16301 @section Examples of @code{gnatclean} Usage
16302
16303 @ifclear vms
16304 @node GNAT and Libraries
16305 @chapter GNAT and Libraries
16306 @cindex Library, building, installing, using
16307
16308 @noindent
16309 This chapter addresses the issues related to building and using
16310 libraries with GNAT. It also shows how the GNAT run-time library can be
16311 recompiled. It is recommended that the user understands how to use the
16312 @ref{GNAT Project Manager} facility before reading this chapter.
16313
16314 @menu
16315 * Introduction to Libraries in GNAT::
16316 * General Ada Libraries::
16317 * Stand-alone Ada Libraries::
16318 * Rebuilding the GNAT Run-Time Library::
16319 @end menu
16320
16321 @node Introduction to Libraries in GNAT
16322 @section Introduction to Libraries in GNAT
16323
16324 @noindent
16325 A library is, conceptually, a collection of objects which does not have its
16326 own main thread of execution, but rather provides certain services to the
16327 applications that use it. A library can be either statically linked with the
16328 application, in which case its code is directly included in the application,
16329 or, on platforms that support it, be dynamically linked, in which case
16330 its code is shared by all applications making use of this library. GNAT
16331 supports both types of libraries. In the static case, the compiled code can
16332 be provided in different ways. The simplest way is to provide directly the
16333 set of objects produced by the compiler during the compilation of the library.
16334 It is also possible to group the objects into an archive using whatever
16335 commands are provided by the operating system. For the later case, the objects
16336 are grouped into a shared library.
16337
16338 In the GNAT environment, a library has two types of components:
16339 @itemize @bullet
16340 @item
16341 Source files.
16342 @item
16343 Compiled code and Ali files. See @ref{The Ada Library Information Files}.
16344 @end itemize
16345
16346 @noindent
16347 GNAT libraries can either completely expose their source files to the
16348 compilation context of the user's application, or alternatively only expose
16349 a limited set of source files, called interface units, in which case they are
16350 called @ref{Stand-alone Ada Libraries}. In addition, GNAT provides full support
16351 for foreign libraries which are only available in the object format.
16352
16353 Ada semantics requires that all compilation units comprising the application
16354 are elaborated in the timely fashion. Where possible, GNAT provides facilities
16355 to ensure that compilation units of a library are automatically elaborated;
16356 however, there are cases where this must be responsibility of a user. This will
16357 be addressed in greater detail further on.
16358
16359 @node General Ada Libraries
16360 @section General Ada Libraries
16361
16362 @menu
16363 * Building the library::
16364 * Installing the library::
16365 * Using the library::
16366 @end menu
16367
16368 @node Building the library
16369 @subsection Building the library
16370
16371 @noindent
16372 The easiest way to build a library is to use the @ref{GNAT Project Manager},
16373 which supports a special type of projects called @ref{Library Projects}.
16374
16375 A project is considered a library project, when two project-level attributes
16376 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
16377 control different aspects of library configuration, additional optional
16378 project-level attributes can be specified:
16379 @itemize
16380 @item @code{Library_Kind}
16381 This attribute controls whether the library is to be static or shared
16382 @item @code{Library_Version}
16383 This attribute specifies what is the library version; this value is used
16384 during dynamic linking of shared libraries to determine if the currently
16385 installed versions of the binaries are compatible.
16386 @item @code{Library_Options}, @code{Library_GCC}
16387 These attributes specify additional low-level options to be used during
16388 library generation, and redefine the actual application used to generate
16389 library.
16390 @end itemize
16391
16392 @noindent
16393 GNAT Project Manager takes full care of the library maintenance task,
16394 including recompilation of the source files for which objects do not exist
16395 or are not up to date, assembly of the library archive, and installation of
16396 the library, i.e. the copy of associated source, object and ALI files to the
16397 specific location.
16398
16399 It is not entirely trivial to correctly do all the steps required to
16400 produce a library. We recommend that you use @ref{GNAT Project Manager}
16401 for this task. In special cases where this is not desired, the necessary
16402 steps are discussed below.
16403
16404 There are various possibilities for compiling the units that make up the
16405 library: for example with a Makefile @ref{Using the GNU make Utility},
16406 or with a conventional script.
16407 For simple libraries, it is also possible to create a
16408 dummy main program which depends upon all the packages that comprise the
16409 interface of the library. This dummy main program can then be given to
16410 gnatmake, which will ensure that all necessary objects are built.
16411
16412 After this task is accomplished, the user should follow the standard procedure
16413 of the underlying operating system to produce the static or shared library.
16414
16415 Below is an example of such a dummy program and the generic commands used to
16416 build an archive or a shared library.
16417
16418 @smallexample @c ada
16419 @iftex
16420 @leftskip=.7cm
16421 @end iftex
16422 with My_Lib.Service1;
16423 with My_Lib.Service2;
16424 with My_Lib.Service3;
16425 procedure My_Lib_Dummy is
16426 begin
16427    null;
16428 end;
16429 @end smallexample
16430
16431 @smallexample
16432 # compiling the library
16433 $ gnatmake -c my_lib_dummy.adb
16434
16435 # we don't need the dummy object itself
16436 $ rm my_lib_dummy.o my_lib_dummy.ali
16437
16438 # create an archive with the remaining objects
16439 $ ar rc libmy_lib.a *.o
16440 # some systems may require "ranlib" to be run as well
16441
16442 # or create a shared library
16443 $ gcc -shared -o libmy_lib.so *.o
16444 # some systems may require the code to have been compiled with -fPIC
16445
16446 # remove the object files that are now in the library
16447 $ rm *.o
16448
16449 # Make the ALI files read-only so that gnatmake will not try to
16450 # regenerate the objects that are in the library
16451 $ chmod -w *.ali
16452
16453 @end smallexample
16454
16455 @noindent
16456 Please note that the library must have a name of the form libxxx.a or
16457 libxxx.so in order to be accessed by the directive -lxxx at link
16458 time.
16459
16460 @node Installing the library
16461 @subsection Installing the library
16462
16463 @noindent
16464 In the GNAT model, installing a library consists in copying into a specific
16465 location the files that make up this library. When the library is built using
16466 projects, it is automatically installed in the location specified in the
16467 project by means of the attribute @code{Library_Dir}, otherwise it is
16468 responsibility of the user. GNAT also supports installing the sources in a
16469 different directory from the other files (ALI, objects, archives) since the
16470 source path and the object path can be specified separately.
16471
16472 For general purpose libraries, it is possible for the system
16473 administrator to put those libraries in the default compiler paths. To
16474 achieve this, he must specify their location in the configuration files
16475 @file{ada_source_path} and @file{ada_object_path} that must be located in
16476 the GNAT
16477 installation tree at the same place as the gcc spec file. The location of
16478 the gcc spec file can be determined as follows:
16479 @smallexample
16480 $ gcc -v
16481 @end smallexample
16482
16483 @noindent
16484 The configuration files mentioned above have simple format: each line in them
16485 must contain one unique
16486 directory name. Those names are added to the corresponding path
16487 in their order of appearance in the file. The names can be either absolute
16488 or relative, in the latter case, they are relative to where theses files
16489 are located.
16490
16491 @file{ada_source_path} and @file{ada_object_path} might actually not be
16492 present in a
16493 GNAT installation, in which case, GNAT will look for its run-time library in
16494 he directories @file{adainclude} for the sources and @file{adalib} for the
16495 objects and @file{ALI} files. When the files exist, the compiler does not
16496 look in @file{adainclude} and @file{adalib} at all, and thus the
16497 @file{ada_source_path} file
16498 must contain the location for the GNAT run-time sources (which can simply
16499 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16500 contain the location for the GNAT run-time objects (which can simply
16501 be @file{adalib}).
16502
16503 You can also specify a new default path to the runtime library at compilation
16504 time with the switch @option{--RTS=rts-path}. You can easily choose and change
16505 the runtime you want your program to be compiled with. This switch is
16506 recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref.
16507
16508 It is possible to install a library before or after the standard GNAT
16509 library, by reordering the lines in the configuration files. In general, a
16510 library must be installed before the GNAT library if it redefines
16511 any part of it.
16512
16513
16514 @node Using the library
16515 @subsection Using the library
16516
16517 @noindent
16518 Once again, the project facility greatly simplifies the addition of libraries
16519 to the compilation. If the project file for an application lists a library
16520 project in its @code{with} clause, the project manager will ensure that the
16521 library files are consistent, and are considered during compilation and
16522 linking of the main application.
16523
16524 Even if you have a third-party, non-Ada library, you can still use GNAT
16525 Project facility to provide a wrapper for it. The following project for
16526 example, when "withed" in your main project, will link with the third-party
16527 library liba.a:
16528
16529 @smallexample @c projectfile
16530 @group
16531 project Liba is
16532    for Source_Dirs use ();
16533    for Library_Dir use "lib";
16534    for Library_Name use "a";
16535    for Library_Kind use "static";
16536 end Liba;
16537 @end group
16538 @end smallexample
16539
16540 @noindent
16541 In order to use an Ada library manually, you need to make sure that this
16542 library is on both your source and object path
16543 @ref{Search Paths and the Run-Time Library (RTL)}
16544 and @ref{Search Paths for gnatbind}. Furthermore, when the objects are grouped
16545 in an archive or a shared library, the user needs to specify the desired
16546 library at link time.
16547
16548 By means of example, you can use the library @file{mylib} installed in
16549 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16550
16551 @smallexample
16552 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16553   -largs -lmy_lib
16554 @end smallexample
16555
16556 @noindent
16557 This can be simplified down to the following:
16558 @smallexample
16559 $ gnatmake my_appl
16560 @end smallexample
16561 when the following conditions are met:
16562 @itemize @bullet
16563 @item
16564 @file{/dir/my_lib_src} has been added by the user to the environment
16565 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
16566 @file{ada_source_path}
16567 @item
16568 @file{/dir/my_lib_obj} has been added by the user to the environment
16569 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
16570 @file{ada_object_path}
16571 @item
16572 a pragma @code{Linker_Options}, has been added to one of the sources.
16573 For example:
16574
16575 @smallexample @c ada
16576 pragma Linker_Options ("-lmy_lib");
16577 @end smallexample
16578 @end itemize
16579
16580
16581 @node Stand-alone Ada Libraries
16582 @section Stand-alone Ada Libraries
16583 @cindex Stand-alone library, building, using
16584
16585 @menu
16586 * Introduction to Stand-Alone Libraries::
16587 * Building SAL::
16588 * Creating SAL to be used in a non-Ada context::
16589 * Restrictions in SALs::
16590 @end menu
16591
16592 @node Introduction to Stand-Alone Libraries
16593 @subsection Introduction to Stand-Alone Libraries
16594
16595 @noindent
16596 A Stand-alone Library (SAL) is a library that contains the necessary code to
16597 elaborate the Ada units that are included in the library. Different from
16598 ordinary libraries, which consist of all sources, objects and ALI files of the
16599 library, the SAL creator can specify a restricted subset of compilation units
16600 comprising SAL to serve as a library interface. In this case, the fully
16601 self-sufficient set of files of such library will normally consist of objects
16602 archive, sources of interface units specs, and ALI files of interface units.
16603 Note that if interface specs contain generics or inlined subprograms, body
16604 source must also be provided; if the units that must be provided in the source
16605 form depend on other units, the source and ALIs of those must also be provided.
16606
16607 The main purpose of SAL is to minimize the recompilation overhead of client
16608 applications when the new version of the library is installed. Specifically,
16609 if the interface sources have not changed, client applications do not need to
16610 be recompiled. If, furthermore, SAL is provided in the shared form and its
16611 version, controlled by @code{Library_Version} attribute, is not changed, the
16612 clients don't need to be relinked, either.
16613
16614 SALs also allow the library providers to minimize amount of library source
16615 text exposed to the clients, which might be necessary for different reasons.
16616
16617 Stand-alone libraries are also well suited to be used in an executable which
16618 main is not written in Ada.
16619
16620 @node Building SAL
16621 @subsection Building SAL
16622
16623 @noindent
16624 GNAT Project facility provides a simple way of building and installing
16625 stand-alone libraries, see @ref{Stand-alone Library Projects}.
16626 To be a Stand-alone Library Project, in addition to the two attributes
16627 that make a project a Library Project (@code{Library_Name} and
16628 @code{Library_Dir}, see @ref{Library Projects}), the attribute
16629 @code{Library_Interface} must be defined.
16630
16631 @smallexample @c projectfile
16632 @group
16633    for Library_Dir use "lib_dir";
16634    for Library_Name use "dummy";
16635    for Library_Interface use ("int1", "int1.child");
16636 @end group
16637 @end smallexample
16638
16639 Attribute @code{Library_Interface} has a non empty string list value,
16640 each string in the list designating a unit contained in an immediate source
16641 of the project file.
16642
16643 When a Stand-alone Library is built, first the binder is invoked to build
16644 a package whose name depends on the library name
16645 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
16646 This binder-generated package includes initialization and
16647 finalization procedures whose
16648 names depend on the library name (dummyinit and dummyfinal in the example
16649 above). The object corresponding to this package is included in the library.
16650
16651 The user must ensure timely (e.g. prior to any use of interfaces in the SAL)
16652 calling of these procedures if static SAL is built, or shared SAL is built
16653 with project-level attribute @code{Library_Auto_Init} set to "false".
16654
16655 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16656 (those that are listed in attribute @code{Library_Interface}) are copied to
16657 the Library Directory. As a consequence, only the Interface Units may be
16658 imported from Ada units outside of the library. If other units are imported,
16659 the binding phase will fail.
16660
16661 The attribute @code{Library_Src_Dir}, may be specified for a
16662 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16663 single string value. Its value must be the path (absolute or relative to the
16664 project directory) of an existing directory. This directory cannot be the
16665 object directory or one of the source directories, but it can be the same as
16666 the library directory. The sources of the Interface
16667 Units of the library, necessary to an Ada client of the library, will be
16668 copied to the designated directory, called Interface Copy directory.
16669 These sources includes the specs of the Interface Units, but they may also
16670 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16671 are used, or when there is a generic units in the spec. Before the sources
16672 are copied to the Interface Copy directory, an attempt is made to delete all
16673 files in the Interface Copy directory.
16674
16675 Building stand-alone libraries by hand is difficult. Below are listed the steps
16676 necessary to be done by the user:
16677 @itemize @bullet
16678 @item
16679 compile all library sources
16680 @item
16681 invoke the binder with the switch -n (No Ada main program),
16682 with all the ALI files of the interfaces, and
16683 with the switch -L to give specific names to the init and final
16684 procedure.
16685 @smallexample
16686   gnatbind -n int1.ali int2.ali -Lsal1
16687 @end smallexample
16688 @item
16689 compile the binder generated file
16690 @smallexample
16691   gcc -c b~int2.adb
16692 @end smallexample
16693 @item
16694 link the dynamic library with all the necessary object files,
16695 indicating to the linker the names of the init (and possibly
16696 final) procedures for automatic initialization (and finalization).
16697 The built library should be put in a directory different from
16698 the object directory.
16699 @item
16700 copy the ALI files of the interface to the library directory,
16701 add in the copy the indication that it is an interface to a SAL
16702 (i.e. add a word @option{SL} on the line in ALI file that starts
16703 with letter P) and make the modified copy of the ALI file read-only.
16704 @end itemize
16705
16706 @noindent
16707 Using SALs is not different from using other libraries
16708 (see @ref{Using the library}).
16709
16710 @node Creating SAL to be used in a non-Ada context
16711 @subsection Creating SAL to be used in a non-Ada context
16712
16713 @noindent
16714 It is easy to adapt SAL build procedure discussed above for use of SAL in
16715 a non-Ada context.
16716
16717 The only extra step required is to ensure that library interface subprograms
16718 are compatible with the main program, by means of @code{pragma Export}
16719 or @code{pragma Convention}.
16720
16721 Here is an example of simple library interface for use with C main program:
16722
16723 @smallexample @c ada
16724 package Interface is
16725
16726    procedure Do_Something;
16727    pragma Export (C, Do_Something, "do_something");
16728
16729    procedure Do_Something_Else;
16730    pragma Export (C, Do_Something_Else, "do_something_else");
16731
16732 end Interface;
16733 @end smallexample
16734
16735 @noindent
16736 On the foreign language side, you must provide a ``foreign'' view of the
16737 library interface; remeber that it should contain elaboration routines in
16738 addition to interface subrporams.
16739
16740 The example below shows the content of @code{mylib_interface.h} (note
16741 that there is no rule for the naming of this file, any name can be used)
16742 @smallexample
16743 /* the library elaboration procedure */
16744 extern void mylibinit (void);
16745
16746 /* the library finalization procedure */
16747 extern void mylibfinal (void);
16748
16749 /* the interface exported by the library */
16750 extern void do_something (void);
16751 extern void do_something_else (void);
16752 @end smallexample
16753
16754 @noindent
16755 Libraries built as explained above can be used from any program, provided
16756 that the elaboration procedures (named @code{mylibinit} in the previous
16757 example) are called before the library services are used. Any number of
16758 libraries can be used simultaneously, as long as the elaboration
16759 procedure of each library is called.
16760
16761 Below is an example of C program that uses our @code{mylib} library.
16762
16763 @smallexample
16764 #include "mylib_interface.h"
16765
16766 int
16767 main (void)
16768 @{
16769    /* First, elaborate the library before using it */
16770    mylibinit ();
16771
16772    /* Main program, using the library exported entities */
16773    do_something ();
16774    do_something_else ();
16775
16776    /* Library finalization at the end of the program */
16777    mylibfinal ();
16778    return 0;
16779 @}
16780 @end smallexample
16781
16782 @noindent
16783 Note that invoking any library finalization procedure generated by
16784 @code{gnatbind} shuts down the Ada run time permanently. Consequently, the
16785 finalization of all Ada libraries must be performed at the end of the program.
16786 No call to these libraries nor the Ada run time should be made past the
16787 finalization phase.
16788
16789 @node Restrictions in SALs
16790 @subsection Restrictions in SALs
16791
16792 @noindent
16793 The pragmas listed below should be used with caution inside libraries,
16794 as they can create incompatibilities with other Ada libraries:
16795 @itemize @bullet
16796 @item pragma @code{Locking_Policy}
16797 @item pragma @code{Queuing_Policy}
16798 @item pragma @code{Task_Dispatching_Policy}
16799 @item pragma @code{Unreserve_All_Interrupts}
16800 @end itemize
16801 When using a library that contains such pragmas, the user must make sure
16802 that all libraries use the same pragmas with the same values. Otherwise,
16803 a @code{Program_Error} will
16804 be raised during the elaboration of the conflicting
16805 libraries. The usage of these pragmas and its consequences for the user
16806 should therefore be well documented.
16807
16808 Similarly, the traceback in exception occurrences mechanism should be
16809 enabled or disabled in a consistent manner across all libraries.
16810 Otherwise, a Program_Error will be raised during the elaboration of the
16811 conflicting libraries.
16812
16813 If the @code{'Version} and @code{'Body_Version}
16814 attributes are used inside a library, then it is necessary to
16815 perform a @code{gnatbind} step that mentions all @file{ALI} files in all
16816 libraries, so that version identifiers can be properly computed.
16817 In practice these attributes are rarely used, so this is unlikely
16818 to be a consideration.
16819
16820 @node  Rebuilding the GNAT Run-Time Library
16821 @section Rebuilding the GNAT Run-Time Library
16822 @cindex GNAT Run-Time Library, rebuilding
16823
16824 @noindent
16825 It may be useful to recompile the GNAT library in various contexts, the
16826 most important one being the use of partition-wide configuration pragmas
16827 such as @code{Normalize_Scalars}. A special Makefile called
16828 @code{Makefile.adalib} is provided to that effect and can be found in
16829 the directory containing the GNAT library. The location of this
16830 directory depends on the way the GNAT environment has been installed and can
16831 be determined by means of the command:
16832
16833 @smallexample
16834 $ gnatls -v
16835 @end smallexample
16836
16837 @noindent
16838 The last entry in the object search path usually contains the
16839 gnat library. This Makefile contains its own documentation and in
16840 particular the set of instructions needed to rebuild a new library and
16841 to use it.
16842
16843
16844 @node Using the GNU make Utility
16845 @chapter Using the GNU @code{make} Utility
16846 @findex make
16847
16848 @noindent
16849 This chapter offers some examples of makefiles that solve specific
16850 problems. It does not explain how to write a makefile (see the GNU make
16851 documentation), nor does it try to replace the @code{gnatmake} utility
16852 (@pxref{The GNAT Make Program gnatmake}).
16853
16854 All the examples in this section are specific to the GNU version of
16855 make. Although @code{make} is a standard utility, and the basic language
16856 is the same, these examples use some advanced features found only in
16857 @code{GNU make}.
16858
16859 @menu
16860 * Using gnatmake in a Makefile::
16861 * Automatically Creating a List of Directories::
16862 * Generating the Command Line Switches::
16863 * Overcoming Command Line Length Limits::
16864 @end menu
16865
16866 @node Using gnatmake in a Makefile
16867 @section Using gnatmake in a Makefile
16868 @findex makefile
16869 @cindex GNU make
16870
16871 @noindent
16872 Complex project organizations can be handled in a very powerful way by
16873 using GNU make combined with gnatmake. For instance, here is a Makefile
16874 which allows you to build each subsystem of a big project into a separate
16875 shared library. Such a makefile allows you to significantly reduce the link
16876 time of very big applications while maintaining full coherence at
16877 each step of the build process.
16878
16879 The list of dependencies are handled automatically by
16880 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
16881 the appropriate directories.
16882
16883 Note that you should also read the example on how to automatically
16884 create the list of directories
16885 (@pxref{Automatically Creating a List of Directories})
16886 which might help you in case your project has a lot of subdirectories.
16887
16888 @smallexample
16889 @iftex
16890 @leftskip=0cm
16891 @font@heightrm=cmr8
16892 @heightrm
16893 @end iftex
16894 ## This Makefile is intended to be used with the following directory
16895 ## configuration:
16896 ##  - The sources are split into a series of csc (computer software components)
16897 ##    Each of these csc is put in its own directory.
16898 ##    Their name are referenced by the directory names.
16899 ##    They will be compiled into shared library (although this would also work
16900 ##    with static libraries
16901 ##  - The main program (and possibly other packages that do not belong to any
16902 ##    csc is put in the top level directory (where the Makefile is).
16903 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16904 ##                    \_ second_csc (sources) __ lib (will contain the library)
16905 ##                    \_ ...
16906 ## Although this Makefile is build for shared library, it is easy to modify
16907 ## to build partial link objects instead (modify the lines with -shared and
16908 ## gnatlink below)
16909 ##
16910 ## With this makefile, you can change any file in the system or add any new
16911 ## file, and everything will be recompiled correctly (only the relevant shared
16912 ## objects will be recompiled, and the main program will be re-linked).
16913
16914 # The list of computer software component for your project. This might be
16915 # generated automatically.
16916 CSC_LIST=aa bb cc
16917
16918 # Name of the main program (no extension)
16919 MAIN=main
16920
16921 # If we need to build objects with -fPIC, uncomment the following line
16922 #NEED_FPIC=-fPIC
16923
16924 # The following variable should give the directory containing libgnat.so
16925 # You can get this directory through 'gnatls -v'. This is usually the last
16926 # directory in the Object_Path.
16927 GLIB=...
16928
16929 # The directories for the libraries
16930 # (This macro expands the list of CSC to the list of shared libraries, you
16931 # could simply use the expanded form :
16932 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16933 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16934
16935 $@{MAIN@}: objects $@{LIB_DIR@}
16936     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16937     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16938
16939 objects::
16940     # recompile the sources
16941     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16942
16943 # Note: In a future version of GNAT, the following commands will be simplified
16944 # by a new tool, gnatmlib
16945 $@{LIB_DIR@}:
16946     mkdir -p $@{dir $@@ @}
16947     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16948     cd $@{dir $@@ @}; cp -f ../*.ali .
16949
16950 # The dependencies for the modules
16951 # Note that we have to force the expansion of *.o, since in some cases
16952 # make won't be able to do it itself.
16953 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16954 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16955 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16956
16957 # Make sure all of the shared libraries are in the path before starting the
16958 # program
16959 run::
16960     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16961
16962 clean::
16963     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16964     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16965     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16966     $@{RM@} *.o *.ali $@{MAIN@}
16967 @end smallexample
16968
16969 @node Automatically Creating a List of Directories
16970 @section Automatically Creating a List of Directories
16971
16972 @noindent
16973 In most makefiles, you will have to specify a list of directories, and
16974 store it in a variable. For small projects, it is often easier to
16975 specify each of them by hand, since you then have full control over what
16976 is the proper order for these directories, which ones should be
16977 included...
16978
16979 However, in larger projects, which might involve hundreds of
16980 subdirectories, it might be more convenient to generate this list
16981 automatically.
16982
16983 The example below presents two methods. The first one, although less
16984 general, gives you more control over the list. It involves wildcard
16985 characters, that are automatically expanded by @code{make}. Its
16986 shortcoming is that you need to explicitly specify some of the
16987 organization of your project, such as for instance the directory tree
16988 depth, whether some directories are found in a separate tree,...
16989
16990 The second method is the most general one. It requires an external
16991 program, called @code{find}, which is standard on all Unix systems. All
16992 the directories found under a given root directory will be added to the
16993 list.
16994
16995 @smallexample
16996 @iftex
16997 @leftskip=0cm
16998 @font@heightrm=cmr8
16999 @heightrm
17000 @end iftex
17001 # The examples below are based on the following directory hierarchy:
17002 # All the directories can contain any number of files
17003 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17004 #                       ->  ab
17005 #                       ->  ac
17006 #                ->  b  ->  ba  ->  baa
17007 #                       ->  bb
17008 #                       ->  bc
17009 # This Makefile creates a variable called DIRS, that can be reused any time
17010 # you need this list (see the other examples in this section)
17011
17012 # The root of your project's directory hierarchy
17013 ROOT_DIRECTORY=.
17014
17015 ####
17016 # First method: specify explicitly the list of directories
17017 # This allows you to specify any subset of all the directories you need.
17018 ####
17019
17020 DIRS := a/aa/ a/ab/ b/ba/
17021
17022 ####
17023 # Second method: use wildcards
17024 # Note that the argument(s) to wildcard below should end with a '/'.
17025 # Since wildcards also return file names, we have to filter them out
17026 # to avoid duplicate directory names.
17027 # We thus use make's @code{dir} and @code{sort} functions.
17028 # It sets DIRs to the following value (note that the directories aaa and baa
17029 # are not given, unless you change the arguments to wildcard).
17030 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17031 ####
17032
17033 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17034                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17035
17036 ####
17037 # Third method: use an external program
17038 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17039 # This is the most complete command: it sets DIRs to the following value:
17040 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17041 ####
17042
17043 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17044
17045 @end smallexample
17046
17047 @node Generating the Command Line Switches
17048 @section Generating the Command Line Switches
17049
17050 @noindent
17051 Once you have created the list of directories as explained in the
17052 previous section (@pxref{Automatically Creating a List of Directories}),
17053 you can easily generate the command line arguments to pass to gnatmake.
17054
17055 For the sake of completeness, this example assumes that the source path
17056 is not the same as the object path, and that you have two separate lists
17057 of directories.
17058
17059 @smallexample
17060 # see "Automatically creating a list of directories" to create
17061 # these variables
17062 SOURCE_DIRS=
17063 OBJECT_DIRS=
17064
17065 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17066 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17067
17068 all:
17069         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17070 @end smallexample
17071
17072 @node Overcoming Command Line Length Limits
17073 @section Overcoming Command Line Length Limits
17074
17075 @noindent
17076 One problem that might be encountered on big projects is that many
17077 operating systems limit the length of the command line. It is thus hard to give
17078 gnatmake the list of source and object directories.
17079
17080 This example shows how you can set up environment variables, which will
17081 make @code{gnatmake} behave exactly as if the directories had been
17082 specified on the command line, but have a much higher length limit (or
17083 even none on most systems).
17084
17085 It assumes that you have created a list of directories in your Makefile,
17086 using one of the methods presented in
17087 @ref{Automatically Creating a List of Directories}.
17088 For the sake of completeness, we assume that the object
17089 path (where the ALI files are found) is different from the sources patch.
17090
17091 Note a small trick in the Makefile below: for efficiency reasons, we
17092 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17093 expanded immediately by @code{make}. This way we overcome the standard
17094 make behavior which is to expand the variables only when they are
17095 actually used.
17096
17097 On Windows, if you are using the standard Windows command shell, you must
17098 replace colons with semicolons in the assignments to these variables.
17099
17100 @smallexample
17101 @iftex
17102 @leftskip=0cm
17103 @font@heightrm=cmr8
17104 @heightrm
17105 @end iftex
17106 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
17107 # This is the same thing as putting the -I arguments on the command line.
17108 # (the equivalent of using -aI on the command line would be to define
17109 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
17110 # You can of course have different values for these variables.
17111 #
17112 # Note also that we need to keep the previous values of these variables, since
17113 # they might have been set before running 'make' to specify where the GNAT
17114 # library is installed.
17115
17116 # see "Automatically creating a list of directories" to create these
17117 # variables
17118 SOURCE_DIRS=
17119 OBJECT_DIRS=
17120
17121 empty:=
17122 space:=$@{empty@} $@{empty@}
17123 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17124 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17125 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17126 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
17127 export ADA_INCLUDE_PATH
17128 export ADA_OBJECT_PATH
17129
17130 all:
17131         gnatmake main_unit
17132 @end smallexample
17133 @end ifclear
17134
17135
17136 @node Finding Memory Problems
17137 @chapter Finding Memory Problems
17138
17139 @noindent
17140 This chapter describes
17141 @ifclear vms
17142 the @command{gnatmem} tool, which can be used to track down
17143 ``memory leaks'', and
17144 @end ifclear
17145 the GNAT Debug Pool facility, which can be used to detect incorrect uses of
17146 access values (including ``dangling references'').
17147
17148 @menu
17149 @ifclear vms
17150 * The gnatmem Tool::
17151 @end ifclear
17152 * The GNAT Debug Pool Facility::
17153 @end menu
17154
17155
17156 @ifclear vms
17157 @node The gnatmem Tool
17158 @section The @command{gnatmem} Tool
17159 @findex gnatmem
17160
17161 @noindent
17162 The @code{gnatmem} utility monitors dynamic allocation and
17163 deallocation activity in a program, and displays information about
17164 incorrect deallocations and possible sources of memory leaks.
17165 It provides three type of information:
17166 @itemize @bullet
17167 @item
17168 General information concerning memory management, such as the total
17169 number of allocations and deallocations, the amount of allocated
17170 memory and the high water mark, i.e. the largest amount of allocated
17171 memory in the course of program execution.
17172
17173 @item
17174 Backtraces for all incorrect deallocations, that is to say deallocations
17175 which do not correspond to a valid allocation.
17176
17177 @item
17178 Information on each allocation that is potentially the origin of a memory
17179 leak.
17180 @end itemize
17181
17182 @menu
17183 * Running gnatmem::
17184 * Switches for gnatmem::
17185 * Example of gnatmem Usage::
17186 @end menu
17187
17188 @node Running gnatmem
17189 @subsection Running @code{gnatmem}
17190
17191 @noindent
17192 @code{gnatmem} makes use of the output created by the special version of
17193 allocation and deallocation routines that record call information. This
17194 allows to obtain accurate dynamic memory usage history at a minimal cost to
17195 the execution speed. Note however, that @code{gnatmem} is not supported on
17196 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
17197 Solaris (sparc and x86) and Windows NT/2000/XP (x86).
17198
17199 @noindent
17200 The @code{gnatmem} command has the form
17201
17202 @smallexample
17203    $ gnatmem [switches] user_program
17204 @end smallexample
17205
17206 @noindent
17207 The program must have been linked with the instrumented version of the
17208 allocation and deallocation routines. This is done by linking with the
17209 @file{libgmem.a} library. For correct symbolic backtrace information,
17210 the user program should be compiled with debugging options
17211 @ref{Switches for gcc}. For example to build @file{my_program}:
17212
17213 @smallexample
17214 $ gnatmake -g my_program -largs -lgmem
17215 @end smallexample
17216
17217 @noindent
17218 When running @file{my_program} the file @file{gmem.out} is produced. This file
17219 contains information about all allocations and deallocations done by the
17220 program. It is produced by the instrumented allocations and
17221 deallocations routines and will be used by @code{gnatmem}.
17222
17223 @noindent
17224 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17225 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17226 @code{-i} switch, gnatmem will assume that this file can be found in the
17227 current directory. For example, after you have executed @file{my_program},
17228 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17229
17230 @smallexample
17231 $ gnatmem my_program
17232 @end smallexample
17233
17234 @noindent
17235 This will produce the output with the following format:
17236
17237 *************** debut cc
17238 @smallexample
17239 $ gnatmem my_program
17240
17241 Global information
17242 ------------------
17243    Total number of allocations        :  45
17244    Total number of deallocations      :   6
17245    Final Water Mark (non freed mem)   :  11.29 Kilobytes
17246    High Water Mark                    :  11.40 Kilobytes
17247
17248 .
17249 .
17250 .
17251 Allocation Root # 2
17252 -------------------
17253  Number of non freed allocations    :  11
17254  Final Water Mark (non freed mem)   :   1.16 Kilobytes
17255  High Water Mark                    :   1.27 Kilobytes
17256  Backtrace                          :
17257    my_program.adb:23 my_program.alloc
17258 .
17259 .
17260 .
17261 @end smallexample
17262
17263 The first block of output gives general information. In this case, the
17264 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17265 Unchecked_Deallocation routine occurred.
17266
17267 @noindent
17268 Subsequent paragraphs display  information on all allocation roots.
17269 An allocation root is a specific point in the execution of the program
17270 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17271 construct. This root is represented by an execution backtrace (or subprogram
17272 call stack). By default the backtrace depth for allocations roots is 1, so
17273 that a root corresponds exactly to a source location. The backtrace can
17274 be made deeper, to make the root more specific.
17275
17276 @node Switches for gnatmem
17277 @subsection Switches for @code{gnatmem}
17278
17279 @noindent
17280 @code{gnatmem} recognizes the following switches:
17281
17282 @table @option
17283
17284 @item -q
17285 @cindex @option{-q} (@code{gnatmem})
17286 Quiet. Gives the minimum output needed to identify the origin of the
17287 memory leaks. Omits statistical information.
17288
17289 @item @var{N}
17290 @cindex @var{N} (@code{gnatmem})
17291 N is an integer literal (usually between 1 and 10) which controls the
17292 depth of the backtraces defining allocation root. The default value for
17293 N is 1. The deeper the backtrace, the more precise the localization of
17294 the root. Note that the total number of roots can depend on this
17295 parameter. This parameter must be specified @emph{before} the name of the
17296 executable to be analyzed, to avoid ambiguity.
17297
17298 @item -b n
17299 @cindex @option{-b} (@code{gnatmem})
17300 This switch has the same effect as just depth parameter.
17301
17302 @item -i @var{file}
17303 @cindex @option{-i} (@code{gnatmem})
17304 Do the @code{gnatmem} processing starting from @file{file}, rather than
17305 @file{gmem.out} in the current directory.
17306
17307 @item -m n
17308 @cindex @option{-m} (@code{gnatmem})
17309 This switch causes @code{gnatmem} to mask the allocation roots that have less
17310 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17311 examine even the roots that didn't result in leaks.
17312
17313 @item -s order
17314 @cindex @option{-s} (@code{gnatmem})
17315 This switch causes @code{gnatmem} to sort the allocation roots according to the
17316 specified order of sort criteria, each identified by a single letter. The
17317 currently supported criteria are @code{n, h, w} standing respectively for
17318 number of unfreed allocations, high watermark, and final watermark
17319 corresponding to a specific root. The default order is @code{nwh}.
17320
17321 @end table
17322
17323 @node Example of gnatmem Usage
17324 @subsection Example of @code{gnatmem} Usage
17325
17326 @noindent
17327 The following example shows the use of @code{gnatmem}
17328 on a simple memory-leaking program.
17329 Suppose that we have the following Ada program:
17330
17331 @smallexample @c ada
17332 @group
17333 @cartouche
17334 with Unchecked_Deallocation;
17335 procedure Test_Gm is
17336
17337    type T is array (1..1000) of Integer;
17338    type Ptr is access T;
17339    procedure Free is new Unchecked_Deallocation (T, Ptr);
17340    A : Ptr;
17341
17342    procedure My_Alloc is
17343    begin
17344       A := new T;
17345    end My_Alloc;
17346
17347    procedure My_DeAlloc is
17348       B : Ptr := A;
17349    begin
17350       Free (B);
17351    end My_DeAlloc;
17352
17353 begin
17354    My_Alloc;
17355    for I in 1 .. 5 loop
17356       for J in I .. 5 loop
17357          My_Alloc;
17358       end loop;
17359       My_Dealloc;
17360    end loop;
17361 end;
17362 @end cartouche
17363 @end group
17364 @end smallexample
17365
17366 @noindent
17367 The program needs to be compiled with debugging option and linked with
17368 @code{gmem} library:
17369
17370 @smallexample
17371 $ gnatmake -g test_gm -largs -lgmem
17372 @end smallexample
17373
17374 @noindent
17375 Then we execute the program as usual:
17376
17377 @smallexample
17378 $ test_gm
17379 @end smallexample
17380
17381 @noindent
17382 Then @code{gnatmem} is invoked simply with
17383 @smallexample
17384 $ gnatmem test_gm
17385 @end smallexample
17386
17387 @noindent
17388 which produces the following output (result may vary on different platforms):
17389
17390 @smallexample
17391 Global information
17392 ------------------
17393    Total number of allocations        :  18
17394    Total number of deallocations      :   5
17395    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17396    High Water Mark                    :  56.90 Kilobytes
17397
17398 Allocation Root # 1
17399 -------------------
17400  Number of non freed allocations    :  11
17401  Final Water Mark (non freed mem)   :  42.97 Kilobytes
17402  High Water Mark                    :  46.88 Kilobytes
17403  Backtrace                          :
17404    test_gm.adb:11 test_gm.my_alloc
17405
17406 Allocation Root # 2
17407 -------------------
17408  Number of non freed allocations    :   1
17409  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17410  High Water Mark                    :  10.02 Kilobytes
17411  Backtrace                          :
17412    s-secsta.adb:81 system.secondary_stack.ss_init
17413
17414 Allocation Root # 3
17415 -------------------
17416  Number of non freed allocations    :   1
17417  Final Water Mark (non freed mem)   :  12 Bytes
17418  High Water Mark                    :  12 Bytes
17419  Backtrace                          :
17420    s-secsta.adb:181 system.secondary_stack.ss_init
17421 @end smallexample
17422
17423 @noindent
17424 Note that the GNAT run time contains itself a certain number of
17425 allocations that have no  corresponding deallocation,
17426 as shown here for root #2 and root
17427 #3. This is a normal behavior when the number of non freed allocations
17428 is one, it allocates dynamic data structures that the run time needs for
17429 the complete lifetime of the program. Note also that there is only one
17430 allocation root in the user program with a single line back trace:
17431 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17432 program shows that 'My_Alloc' is called at 2 different points in the
17433 source (line 21 and line 24). If those two allocation roots need to be
17434 distinguished, the backtrace depth parameter can be used:
17435
17436 @smallexample
17437 $ gnatmem 3 test_gm
17438 @end smallexample
17439
17440 @noindent
17441 which will give the following output:
17442
17443 @smallexample
17444 Global information
17445 ------------------
17446    Total number of allocations        :  18
17447    Total number of deallocations      :   5
17448    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17449    High Water Mark                    :  56.90 Kilobytes
17450
17451 Allocation Root # 1
17452 -------------------
17453  Number of non freed allocations    :  10
17454  Final Water Mark (non freed mem)   :  39.06 Kilobytes
17455  High Water Mark                    :  42.97 Kilobytes
17456  Backtrace                          :
17457    test_gm.adb:11 test_gm.my_alloc
17458    test_gm.adb:24 test_gm
17459    b_test_gm.c:52 main
17460
17461 Allocation Root # 2
17462 -------------------
17463  Number of non freed allocations    :   1
17464  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17465  High Water Mark                    :  10.02 Kilobytes
17466  Backtrace                          :
17467    s-secsta.adb:81  system.secondary_stack.ss_init
17468    s-secsta.adb:283 <system__secondary_stack___elabb>
17469    b_test_gm.c:33   adainit
17470
17471 Allocation Root # 3
17472 -------------------
17473  Number of non freed allocations    :   1
17474  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17475  High Water Mark                    :   3.91 Kilobytes
17476  Backtrace                          :
17477    test_gm.adb:11 test_gm.my_alloc
17478    test_gm.adb:21 test_gm
17479    b_test_gm.c:52 main
17480
17481 Allocation Root # 4
17482 -------------------
17483  Number of non freed allocations    :   1
17484  Final Water Mark (non freed mem)   :  12 Bytes
17485  High Water Mark                    :  12 Bytes
17486  Backtrace                          :
17487    s-secsta.adb:181 system.secondary_stack.ss_init
17488    s-secsta.adb:283 <system__secondary_stack___elabb>
17489    b_test_gm.c:33   adainit
17490 @end smallexample
17491
17492 @noindent
17493 The allocation root #1 of the first example has been split in 2 roots #1
17494 and #3 thanks to the more precise associated backtrace.
17495
17496 @end ifclear
17497
17498
17499 @node The GNAT Debug Pool Facility
17500 @section The GNAT Debug Pool Facility
17501 @findex Debug Pool
17502 @cindex storage, pool, memory corruption
17503
17504 @noindent
17505 The use of unchecked deallocation and unchecked conversion can easily
17506 lead to incorrect memory references. The problems generated by such
17507 references are usually difficult to tackle because the symptoms can be
17508 very remote from the origin of the problem. In such cases, it is
17509 very helpful to detect the problem as early as possible. This is the
17510 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17511
17512 In order to use the GNAT specific debugging pool, the user must
17513 associate a debug pool object with each of the access types that may be
17514 related to suspected memory problems. See Ada Reference Manual 13.11.
17515 @smallexample @c ada
17516 type Ptr is access Some_Type;
17517 Pool : GNAT.Debug_Pools.Debug_Pool;
17518 for Ptr'Storage_Pool use Pool;
17519 @end smallexample
17520
17521 @noindent
17522 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17523 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17524 allow the user to redefine allocation and deallocation strategies. They
17525 also provide a checkpoint for each dereference, through the use of
17526 the primitive operation @code{Dereference} which is implicitly called at
17527 each dereference of an access value.
17528
17529 Once an access type has been associated with a debug pool, operations on
17530 values of the type may raise four distinct exceptions,
17531 which correspond to four potential kinds of memory corruption:
17532 @itemize @bullet
17533 @item
17534 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17535 @item
17536 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17537 @item
17538 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17539 @item
17540 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17541 @end itemize
17542
17543 @noindent
17544 For types associated with a Debug_Pool, dynamic allocation is performed using
17545 the standard
17546 GNAT allocation routine. References to all allocated chunks of memory
17547 are kept in an internal dictionary.
17548 Several deallocation strategies are provided, whereupon the user can choose
17549 to release the memory to the system, keep it allocated for further invalid
17550 access checks, or fill it with an easily recognizable pattern for debug
17551 sessions.
17552 The memory pattern is the old IBM hexadecimal convention: @code{16#DEADBEEF#}.
17553
17554 See the documentation in the file g-debpoo.ads for more information on the
17555 various strategies.
17556
17557 Upon each dereference, a check is made that the access value denotes a
17558 properly allocated memory location. Here is a complete example of use of
17559 @code{Debug_Pools}, that includes typical instances of  memory corruption:
17560 @smallexample @c ada
17561 @iftex
17562 @leftskip=0cm
17563 @end iftex
17564 with Gnat.Io; use Gnat.Io;
17565 with Unchecked_Deallocation;
17566 with Unchecked_Conversion;
17567 with GNAT.Debug_Pools;
17568 with System.Storage_Elements;
17569 with Ada.Exceptions; use Ada.Exceptions;
17570 procedure Debug_Pool_Test is
17571
17572    type T is access Integer;
17573    type U is access all T;
17574
17575    P : GNAT.Debug_Pools.Debug_Pool;
17576    for T'Storage_Pool use P;
17577
17578    procedure Free is new Unchecked_Deallocation (Integer, T);
17579    function UC is new Unchecked_Conversion (U, T);
17580    A, B : aliased T;
17581
17582    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17583
17584 begin
17585    Info (P);
17586    A := new Integer;
17587    B := new Integer;
17588    B := A;
17589    Info (P);
17590    Free (A);
17591    begin
17592       Put_Line (Integer'Image(B.all));
17593    exception
17594       when E : others => Put_Line ("raised: " & Exception_Name (E));
17595    end;
17596    begin
17597       Free (B);
17598    exception
17599       when E : others => Put_Line ("raised: " & Exception_Name (E));
17600    end;
17601    B := UC(A'Access);
17602    begin
17603       Put_Line (Integer'Image(B.all));
17604    exception
17605       when E : others => Put_Line ("raised: " & Exception_Name (E));
17606    end;
17607    begin
17608       Free (B);
17609    exception
17610       when E : others => Put_Line ("raised: " & Exception_Name (E));
17611    end;
17612    Info (P);
17613 end Debug_Pool_Test;
17614 @end smallexample
17615
17616 @noindent
17617 The debug pool mechanism provides the following precise diagnostics on the
17618 execution of this erroneous program:
17619 @smallexample
17620 Debug Pool info:
17621   Total allocated bytes :  0
17622   Total deallocated bytes :  0
17623   Current Water Mark:  0
17624   High Water Mark:  0
17625
17626 Debug Pool info:
17627   Total allocated bytes :  8
17628   Total deallocated bytes :  0
17629   Current Water Mark:  8
17630   High Water Mark:  8
17631
17632 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17633 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17634 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17635 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17636 Debug Pool info:
17637   Total allocated bytes :  8
17638   Total deallocated bytes :  4
17639   Current Water Mark:  4
17640   High Water Mark:  8
17641 @end smallexample
17642
17643
17644 @node Creating Sample Bodies Using gnatstub
17645 @chapter Creating Sample Bodies Using @command{gnatstub}
17646 @findex gnatstub
17647
17648 @noindent
17649 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17650 for library unit declarations.
17651
17652 To create a body stub, @command{gnatstub} has to compile the library
17653 unit declaration. Therefore, bodies can be created only for legal
17654 library units. Moreover, if a library unit depends semantically upon
17655 units located outside the current directory, you have to provide
17656 the source search path when calling @command{gnatstub}, see the description
17657 of @command{gnatstub} switches below.
17658
17659 @menu
17660 * Running gnatstub::
17661 * Switches for gnatstub::
17662 @end menu
17663
17664 @node Running gnatstub
17665 @section Running @command{gnatstub}
17666
17667 @noindent
17668 @command{gnatstub} has the command-line interface of the form
17669
17670 @smallexample
17671 $ gnatstub [switches] filename [directory]
17672 @end smallexample
17673
17674 @noindent
17675 where
17676 @table @emph
17677 @item filename
17678 is the name of the source file that contains a library unit declaration
17679 for which a body must be created. The file name may contain the path
17680 information.
17681 The file name does not have to follow the GNAT file name conventions. If the
17682 name
17683 does not follow GNAT file naming conventions, the name of the body file must
17684 be provided
17685 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17686 If the file name follows the GNAT file naming
17687 conventions and the name of the body file is not provided,
17688 @command{gnatstub}
17689 creates the name
17690 of the body file from the argument file name by replacing the @file{.ads}
17691 suffix
17692 with the @file{.adb} suffix.
17693
17694 @item directory
17695 indicates the directory in which the body stub is to be placed (the default
17696 is the
17697 current directory)
17698
17699 @item switches
17700 is an optional sequence of switches as described in the next section
17701 @end table
17702
17703 @node Switches for gnatstub
17704 @section Switches for @command{gnatstub}
17705
17706 @table @option
17707 @c !sort!
17708
17709 @item ^-f^/FULL^
17710 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17711 If the destination directory already contains a file with the name of the
17712 body file
17713 for the argument spec file, replace it with the generated body stub.
17714
17715 @item ^-hs^/HEADER=SPEC^
17716 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17717 Put the comment header (i.e., all the comments preceding the
17718 compilation unit) from the source of the library unit declaration
17719 into the body stub.
17720
17721 @item ^-hg^/HEADER=GENERAL^
17722 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17723 Put a sample comment header into the body stub.
17724
17725 @ifclear vms
17726 @item -IDIR
17727 @cindex @option{-IDIR} (@command{gnatstub})
17728 @itemx -I-
17729 @cindex @option{-I-} (@command{gnatstub})
17730 @end ifclear
17731 @ifset vms
17732 @item /NOCURRENT_DIRECTORY
17733 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17734 @end ifset
17735 ^These switches have ^This switch has^ the same meaning as in calls to
17736 @command{gcc}.
17737 ^They define ^It defines ^ the source search path in the call to
17738 @command{gcc} issued
17739 by @command{gnatstub} to compile an argument source file.
17740
17741 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17742 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17743 This switch has the same meaning as in calls to @command{gcc}.
17744 It defines the additional configuration file to be passed to the call to
17745 @command{gcc} issued
17746 by @command{gnatstub} to compile an argument source file.
17747
17748 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17749 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17750 (@var{n} is a non-negative integer). Set the maximum line length in the
17751 body stub to @var{n}; the default is 79. The maximum value that can be
17752 specified is 32767. Note that in the special case of configuration
17753 pragma files, the maximum is always 32767 regardless of whether or
17754 not this switch appears.
17755
17756 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17757 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17758 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17759 the generated body sample to @var{n}.
17760 The default indentation is 3.
17761
17762 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17763 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17764 Order local bodies alphabetically. (By default local bodies are ordered
17765 in the same way as the corresponding local specs in the argument spec file.)
17766
17767 @item ^-i^/INDENTATION=^@var{n}
17768 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17769 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17770
17771 @item ^-k^/TREE_FILE=SAVE^
17772 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17773 Do not remove the tree file (i.e., the snapshot of the compiler internal
17774 structures used by @command{gnatstub}) after creating the body stub.
17775
17776 @item ^-l^/LINE_LENGTH=^@var{n}
17777 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17778 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17779
17780 @item ^-o^/BODY=^@var{body-name}
17781 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17782 Body file name.  This should be set if the argument file name does not
17783 follow
17784 the GNAT file naming
17785 conventions. If this switch is omitted the default name for the body will be
17786 obtained
17787 from the argument file name according to the GNAT file naming conventions.
17788
17789 @item ^-q^/QUIET^
17790 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17791 Quiet mode: do not generate a confirmation when a body is
17792 successfully created, and do not generate a message when a body is not
17793 required for an
17794 argument unit.
17795
17796 @item ^-r^/TREE_FILE=REUSE^
17797 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17798 Reuse the tree file (if it exists) instead of creating it.  Instead of
17799 creating the tree file for the library unit declaration, @command{gnatstub}
17800 tries to find it in the current directory and use it for creating
17801 a body. If the tree file is not found, no body is created. This option
17802 also implies @option{^-k^/SAVE^}, whether or not
17803 the latter is set explicitly.
17804
17805 @item ^-t^/TREE_FILE=OVERWRITE^
17806 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17807 Overwrite the existing tree file.  If the current directory already
17808 contains the file which, according to the GNAT file naming rules should
17809 be considered as a tree file for the argument source file,
17810 @command{gnatstub}
17811 will refuse to create the tree file needed to create a sample body
17812 unless this option is set.
17813
17814 @item ^-v^/VERBOSE^
17815 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17816 Verbose mode: generate version information.
17817
17818 @end table
17819
17820
17821 @node Other Utility Programs
17822 @chapter Other Utility Programs
17823
17824 @noindent
17825 This chapter discusses some other utility programs available in the Ada
17826 environment.
17827
17828 @menu
17829 * Using Other Utility Programs with GNAT::
17830 * The External Symbol Naming Scheme of GNAT::
17831 @ifclear vms
17832 * Ada Mode for Glide::
17833 @end ifclear
17834 * Converting Ada Files to html with gnathtml::
17835 * Installing gnathtml::
17836 @ifset vms
17837 * LSE::
17838 * Profiling::
17839 @end ifset
17840 @end menu
17841
17842 @node Using Other Utility Programs with GNAT
17843 @section Using Other Utility Programs with GNAT
17844
17845 @noindent
17846 The object files generated by GNAT are in standard system format and in
17847 particular the debugging information uses this format. This means
17848 programs generated by GNAT can be used with existing utilities that
17849 depend on these formats.
17850
17851 @ifclear vms
17852 In general, any utility program that works with C will also often work with
17853 Ada programs generated by GNAT. This includes software utilities such as
17854 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
17855 as Purify.
17856 @end ifclear
17857
17858 @node The External Symbol Naming Scheme of GNAT
17859 @section The External Symbol Naming Scheme of GNAT
17860
17861 @noindent
17862 In order to interpret the output from GNAT, when using tools that are
17863 originally intended for use with other languages, it is useful to
17864 understand the conventions used to generate link names from the Ada
17865 entity names.
17866
17867 All link names are in all lowercase letters. With the exception of library
17868 procedure names, the mechanism used is simply to use the full expanded
17869 Ada name with dots replaced by double underscores. For example, suppose
17870 we have the following package spec:
17871
17872 @smallexample @c ada
17873 @group
17874 @cartouche
17875 package QRS is
17876    MN : Integer;
17877 end QRS;
17878 @end cartouche
17879 @end group
17880 @end smallexample
17881
17882 @noindent
17883 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
17884 the corresponding link name is @code{qrs__mn}.
17885 @findex Export
17886 Of course if a @code{pragma Export} is used this may be overridden:
17887
17888 @smallexample @c ada
17889 @group
17890 @cartouche
17891 package Exports is
17892    Var1 : Integer;
17893    pragma Export (Var1, C, External_Name => "var1_name");
17894    Var2 : Integer;
17895    pragma Export (Var2, C, Link_Name => "var2_link_name");
17896 end Exports;
17897 @end cartouche
17898 @end group
17899 @end smallexample
17900
17901 @noindent
17902 In this case, the link name for @var{Var1} is whatever link name the
17903 C compiler would assign for the C function @var{var1_name}. This typically
17904 would be either @var{var1_name} or @var{_var1_name}, depending on operating
17905 system conventions, but other possibilities exist. The link name for
17906 @var{Var2} is @var{var2_link_name}, and this is not operating system
17907 dependent.
17908
17909 @findex _main
17910 One exception occurs for library level procedures. A potential ambiguity
17911 arises between the required name @code{_main} for the C main program,
17912 and the name we would otherwise assign to an Ada library level procedure
17913 called @code{Main} (which might well not be the main program).
17914
17915 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
17916 names. So if we have a library level procedure such as
17917
17918 @smallexample @c ada
17919 @group
17920 @cartouche
17921 procedure Hello (S : String);
17922 @end cartouche
17923 @end group
17924 @end smallexample
17925
17926 @noindent
17927 the external name of this procedure will be @var{_ada_hello}.
17928
17929 @ifclear vms
17930 @node Ada Mode for Glide
17931 @section Ada Mode for @code{Glide}
17932 @cindex Ada mode (for Glide)
17933
17934 @noindent
17935 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
17936 user to understand and navigate existing code, and facilitates writing
17937 new code. It furthermore provides some utility functions for easier
17938 integration of standard Emacs features when programming in Ada.
17939
17940 Its general features include:
17941
17942 @itemize @bullet
17943 @item
17944 An Integrated Development Environment with functionality such as the
17945 following
17946
17947 @itemize @bullet
17948 @item
17949 ``Project files'' for configuration-specific aspects
17950 (e.g. directories and compilation options)
17951
17952 @item
17953 Compiling and stepping through error messages.
17954
17955 @item
17956 Running and debugging an applications within Glide.
17957 @end itemize
17958
17959 @item
17960 Pull-down menus
17961
17962 @item
17963 User configurability
17964 @end itemize
17965
17966 Some of the specific Ada mode features are:
17967
17968 @itemize @bullet
17969 @item
17970 Functions for easy and quick stepping through Ada code
17971
17972 @item
17973 Getting cross reference information for identifiers (e.g., finding a
17974 defining occurrence)
17975
17976 @item
17977 Displaying an index menu of types and subprograms, allowing
17978 direct selection for browsing
17979
17980 @item
17981 Automatic color highlighting of the various Ada entities
17982 @end itemize
17983
17984 Glide directly supports writing Ada code, via several facilities:
17985
17986 @itemize @bullet
17987 @item
17988 Switching between spec and body files with possible
17989 autogeneration of body files
17990
17991 @item
17992 Automatic formating of subprogram parameter lists
17993
17994 @item
17995 Automatic indentation according to Ada syntax
17996
17997 @item
17998 Automatic completion of identifiers
17999
18000 @item
18001 Automatic (and configurable) casing of identifiers, keywords, and attributes
18002
18003 @item
18004 Insertion of syntactic templates
18005
18006 @item
18007 Block commenting / uncommenting
18008 @end itemize
18009
18010 @noindent
18011 For more information, please refer to the online documentation
18012 available in the @code{Glide} @result{} @code{Help} menu.
18013 @end ifclear
18014
18015
18016 @node Converting Ada Files to html with gnathtml
18017 @section Converting Ada Files to HTML with @code{gnathtml}
18018
18019 @noindent
18020 This @code{Perl} script allows Ada source files to be browsed using
18021 standard Web browsers. For installation procedure, see the section
18022 @xref{Installing gnathtml}.
18023
18024 Ada reserved keywords are highlighted in a bold font and Ada comments in
18025 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18026 switch to suppress the generation of cross-referencing information, user
18027 defined variables and types will appear in a different color; you will
18028 be able to click on any identifier and go to its declaration.
18029
18030 The command line is as follow:
18031 @smallexample
18032 $ perl gnathtml.pl [switches] ada-files
18033 @end smallexample
18034
18035 @noindent
18036 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18037 an html file for every ada file, and a global file called @file{index.htm}.
18038 This file is an index of every identifier defined in the files.
18039
18040 The available switches are the following ones :
18041
18042 @table @option
18043 @item -83
18044 @cindex @option{-83} (@code{gnathtml})
18045 Only the subset on the Ada 83 keywords will be highlighted, not the full
18046 Ada 95 keywords set.
18047
18048 @item -cc @var{color}
18049 @cindex @option{-cc} (@code{gnathtml})
18050 This option allows you to change the color used for comments. The default
18051 value is green. The color argument can be any name accepted by html.
18052
18053 @item -d
18054 @cindex @option{-d} (@code{gnathtml})
18055 If the ada files depend on some other files (using for instance the
18056 @code{with} command, the latter will also be converted to html.
18057 Only the files in the user project will be converted to html, not the files
18058 in the run-time library itself.
18059
18060 @item -D
18061 @cindex @option{-D} (@code{gnathtml})
18062 This command is the same as @option{-d} above, but @command{gnathtml} will
18063 also look for files in the run-time library, and generate html files for them.
18064
18065 @item -ext @var{extension}
18066 @cindex @option{-ext} (@code{gnathtml})
18067 This option allows you to change the extension of the generated HTML files.
18068 If you do not specify an extension, it will default to @file{htm}.
18069
18070 @item -f
18071 @cindex @option{-f} (@code{gnathtml})
18072 By default, gnathtml will generate html links only for global entities
18073 ('with'ed units, global variables and types,...). If you specify the
18074 @option{-f} on the command line, then links will be generated for local
18075 entities too.
18076
18077 @item -l @var{number}
18078 @cindex @option{-l} (@code{gnathtml})
18079 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
18080 will number the html files every @var{number} line.
18081
18082 @item -I @var{dir}
18083 @cindex @option{-I} (@code{gnathtml})
18084 Specify a directory to search for library files (@file{.ALI} files) and
18085 source files. You can provide several -I switches on the command line,
18086 and the directories will be parsed in the order of the command line.
18087
18088 @item -o @var{dir}
18089 @cindex @option{-o} (@code{gnathtml})
18090 Specify the output directory for html files. By default, gnathtml will
18091 saved the generated html files in a subdirectory named @file{html/}.
18092
18093 @item -p @var{file}
18094 @cindex @option{-p} (@code{gnathtml})
18095 If you are using Emacs and the most recent Emacs Ada mode, which provides
18096 a full Integrated Development Environment for compiling, checking,
18097 running and debugging applications, you may use @file{.gpr} files
18098 to give the directories where Emacs can find sources and object files.
18099
18100 Using this switch, you can tell gnathtml to use these files. This allows
18101 you to get an html version of your application, even if it is spread
18102 over multiple directories.
18103
18104 @item -sc @var{color}
18105 @cindex @option{-sc} (@code{gnathtml})
18106 This option allows you to change the color used for symbol definitions.
18107 The default value is red. The color argument can be any name accepted by html.
18108
18109 @item -t @var{file}
18110 @cindex @option{-t} (@code{gnathtml})
18111 This switch provides the name of a file. This file contains a list of
18112 file names to be converted, and the effect is exactly as though they had
18113 appeared explicitly on the command line. This
18114 is the recommended way to work around the command line length limit on some
18115 systems.
18116
18117 @end table
18118
18119 @node Installing gnathtml
18120 @section Installing @code{gnathtml}
18121
18122 @noindent
18123 @code{Perl} needs to be installed on your machine to run this script.
18124 @code{Perl} is freely available for almost every architecture and
18125 Operating System via the Internet.
18126
18127 On Unix systems, you  may want to modify  the  first line of  the script
18128 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18129 is. The syntax of this line is :
18130 @smallexample
18131 #!full_path_name_to_perl
18132 @end smallexample
18133
18134 @noindent
18135 Alternatively, you may run the script using the following command line:
18136
18137 @smallexample
18138 $ perl gnathtml.pl [switches] files
18139 @end smallexample
18140
18141 @ifset vms
18142 @node LSE
18143 @section LSE
18144 @findex LSE
18145
18146 @noindent
18147 The GNAT distribution provides an Ada 95 template for the Digital Language
18148 Sensitive Editor (LSE), a component of DECset. In order to
18149 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18150
18151 @node Profiling
18152 @section Profiling
18153 @findex PCA
18154
18155 @noindent
18156 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
18157 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18158 the collection phase with the /DEBUG qualifier.
18159
18160 @smallexample
18161 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18162 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18163 $ RUN/DEBUG <PROGRAM_NAME>
18164 @end smallexample
18165 @noindent
18166 @end ifset
18167
18168 @node Running and Debugging Ada Programs
18169 @chapter Running and Debugging Ada Programs
18170 @cindex Debugging
18171
18172 @noindent
18173 This chapter discusses how to debug Ada programs. An incorrect Ada program
18174 may be handled in three ways by the GNAT compiler:
18175
18176 @enumerate
18177 @item
18178 The illegality may be a violation of the static semantics of Ada. In
18179 that case GNAT diagnoses the constructs in the program that are illegal.
18180 It is then a straightforward matter for the user to modify those parts of
18181 the program.
18182
18183 @item
18184 The illegality may be a violation of the dynamic semantics of Ada. In
18185 that case the program compiles and executes, but may generate incorrect
18186 results, or may terminate abnormally with some exception.
18187
18188 @item
18189 When presented with a program that contains convoluted errors, GNAT
18190 itself may terminate abnormally without providing full diagnostics on
18191 the incorrect user program.
18192 @end enumerate
18193
18194 @menu
18195 * The GNAT Debugger GDB::
18196 * Running GDB::
18197 * Introduction to GDB Commands::
18198 * Using Ada Expressions::
18199 * Calling User-Defined Subprograms::
18200 * Using the Next Command in a Function::
18201 * Ada Exceptions::
18202 * Ada Tasks::
18203 * Debugging Generic Units::
18204 * GNAT Abnormal Termination or Failure to Terminate::
18205 * Naming Conventions for GNAT Source Files::
18206 * Getting Internal Debugging Information::
18207 * Stack Traceback::
18208 @end menu
18209
18210 @cindex Debugger
18211 @findex gdb
18212
18213 @node The GNAT Debugger GDB
18214 @section The GNAT Debugger GDB
18215
18216 @noindent
18217 @code{GDB} is a general purpose, platform-independent debugger that
18218 can be used to debug mixed-language programs compiled with @code{GCC},
18219 and in particular is capable of debugging Ada programs compiled with
18220 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18221 complex Ada data structures.
18222
18223 The manual @cite{Debugging with GDB}
18224 @ifset vms
18225 , located in the GNU:[DOCS] directory,
18226 @end ifset
18227 contains full details on the usage of @code{GDB}, including a section on
18228 its usage on programs. This manual should be consulted for full
18229 details. The section that follows is a brief introduction to the
18230 philosophy and use of @code{GDB}.
18231
18232 When GNAT programs are compiled, the compiler optionally writes debugging
18233 information into the generated object file, including information on
18234 line numbers, and on declared types and variables. This information is
18235 separate from the generated code. It makes the object files considerably
18236 larger, but it does not add to the size of the actual executable that
18237 will be loaded into memory, and has no impact on run-time performance. The
18238 generation of debug information is triggered by the use of the
18239 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
18240 the compilations. It is important to emphasize that the use of these
18241 options does not change the generated code.
18242
18243 The debugging information is written in standard system formats that
18244 are used by many tools, including debuggers and profilers. The format
18245 of the information is typically designed to describe C types and
18246 semantics, but GNAT implements a translation scheme which allows full
18247 details about Ada types and variables to be encoded into these
18248 standard C formats. Details of this encoding scheme may be found in
18249 the file exp_dbug.ads in the GNAT source distribution. However, the
18250 details of this encoding are, in general, of no interest to a user,
18251 since @code{GDB} automatically performs the necessary decoding.
18252
18253 When a program is bound and linked, the debugging information is
18254 collected from the object files, and stored in the executable image of
18255 the program. Again, this process significantly increases the size of
18256 the generated executable file, but it does not increase the size of
18257 the executable program itself. Furthermore, if this program is run in
18258 the normal manner, it runs exactly as if the debug information were
18259 not present, and takes no more actual memory.
18260
18261 However, if the program is run under control of @code{GDB}, the
18262 debugger is activated.  The image of the program is loaded, at which
18263 point it is ready to run.  If a run command is given, then the program
18264 will run exactly as it would have if @code{GDB} were not present. This
18265 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18266 entirely non-intrusive until a breakpoint is encountered.  If no
18267 breakpoint is ever hit, the program will run exactly as it would if no
18268 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18269 the debugging information and can respond to user commands to inspect
18270 variables, and more generally to report on the state of execution.
18271
18272 @c **************
18273 @node Running GDB
18274 @section Running GDB
18275
18276 @noindent
18277 The debugger can be launched directly and simply from @code{glide} or
18278 through its graphical interface: @code{gvd}. It can also be used
18279 directly in text mode. Here is described the basic use of @code{GDB}
18280 in text mode. All the commands described below can be used in the
18281 @code{gvd} console window even though there is usually other more
18282 graphical ways to achieve the same goals.
18283
18284 @ifclear vms
18285 @noindent
18286 The command to run the graphical interface of the debugger is
18287 @smallexample
18288 $ gvd program
18289 @end smallexample
18290 @end ifclear
18291
18292 @noindent
18293 The command to run @code{GDB} in text mode is
18294
18295 @smallexample
18296 $ ^gdb program^$ GDB PROGRAM^
18297 @end smallexample
18298
18299 @noindent
18300 where @code{^program^PROGRAM^} is the name of the executable file. This
18301 activates the debugger and results in a prompt for debugger commands.
18302 The simplest command is simply @code{run}, which causes the program to run
18303 exactly as if the debugger were not present. The following section
18304 describes some of the additional commands that can be given to @code{GDB}.
18305
18306
18307 @c *******************************
18308 @node Introduction to GDB Commands
18309 @section Introduction to GDB Commands
18310
18311 @noindent
18312 @code{GDB} contains a large repertoire of commands. The manual
18313 @cite{Debugging with GDB}
18314 @ifset vms
18315 , located in the GNU:[DOCS] directory,
18316 @end ifset
18317 includes extensive documentation on the use
18318 of these commands, together with examples of their use. Furthermore,
18319 the command @var{help} invoked from within @code{GDB} activates a simple help
18320 facility which summarizes the available commands and their options.
18321 In this section we summarize a few of the most commonly
18322 used commands to give an idea of what @code{GDB} is about. You should create
18323 a simple program with debugging information and experiment with the use of
18324 these @code{GDB} commands on the program as you read through the
18325 following section.
18326
18327 @table @code
18328 @item set args @var{arguments}
18329 The @var{arguments} list above is a list of arguments to be passed to
18330 the program on a subsequent run command, just as though the arguments
18331 had been entered on a normal invocation of the program. The @code{set args}
18332 command is not needed if the program does not require arguments.
18333
18334 @item run
18335 The @code{run} command causes execution of the program to start from
18336 the beginning. If the program is already running, that is to say if
18337 you are currently positioned at a breakpoint, then a prompt will ask
18338 for confirmation that you want to abandon the current execution and
18339 restart.
18340
18341 @item breakpoint @var{location}
18342 The breakpoint command sets a breakpoint, that is to say a point at which
18343 execution will halt and @code{GDB} will await further
18344 commands. @var{location} is
18345 either a line number within a file, given in the format @code{file:linenumber},
18346 or it is the name of a subprogram. If you request that a breakpoint be set on
18347 a subprogram that is overloaded, a prompt will ask you to specify on which of
18348 those subprograms you want to breakpoint. You can also
18349 specify that all of them should be breakpointed. If the program is run
18350 and execution encounters the breakpoint, then the program
18351 stops and @code{GDB} signals that the breakpoint was encountered by
18352 printing the line of code before which the program is halted.
18353
18354 @item breakpoint exception @var{name}
18355 A special form of the breakpoint command which breakpoints whenever
18356 exception @var{name} is raised.
18357 If @var{name} is omitted,
18358 then a breakpoint will occur when any exception is raised.
18359
18360 @item print @var{expression}
18361 This will print the value of the given expression. Most simple
18362 Ada expression formats are properly handled by @code{GDB}, so the expression
18363 can contain function calls, variables, operators, and attribute references.
18364
18365 @item continue
18366 Continues execution following a breakpoint, until the next breakpoint or the
18367 termination of the program.
18368
18369 @item step
18370 Executes a single line after a breakpoint. If the next statement
18371 is a subprogram call, execution continues into (the first statement of)
18372 the called subprogram.
18373
18374 @item next
18375 Executes a single line. If this line is a subprogram call, executes and
18376 returns from the call.
18377
18378 @item list
18379 Lists a few lines around the current source location. In practice, it
18380 is usually more convenient to have a separate edit window open with the
18381 relevant source file displayed. Successive applications of this command
18382 print subsequent lines. The command can be given an argument which is a
18383 line number, in which case it displays a few lines around the specified one.
18384
18385 @item backtrace
18386 Displays a backtrace of the call chain. This command is typically
18387 used after a breakpoint has occurred, to examine the sequence of calls that
18388 leads to the current breakpoint. The display includes one line for each
18389 activation record (frame) corresponding to an active subprogram.
18390
18391 @item up
18392 At a breakpoint, @code{GDB} can display the values of variables local
18393 to the current frame. The command @code{up} can be used to
18394 examine the contents of other active frames, by moving the focus up
18395 the stack, that is to say from callee to caller, one frame at a time.
18396
18397 @item down
18398 Moves the focus of @code{GDB} down from the frame currently being
18399 examined to the frame of its callee (the reverse of the previous command),
18400
18401 @item frame @var{n}
18402 Inspect the frame with the given number. The value 0 denotes the frame
18403 of the current breakpoint, that is to say the top of the call stack.
18404
18405 @end table
18406
18407 The above list is a very short introduction to the commands that
18408 @code{GDB} provides. Important additional capabilities, including conditional
18409 breakpoints, the ability to execute command sequences on a breakpoint,
18410 the ability to debug at the machine instruction level and many other
18411 features are described in detail in @cite{Debugging with GDB}.
18412 Note that most commands can be abbreviated
18413 (for example, c for continue, bt for backtrace).
18414
18415 @node Using Ada Expressions
18416 @section Using Ada Expressions
18417 @cindex Ada expressions
18418
18419 @noindent
18420 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18421 extensions. The philosophy behind the design of this subset is
18422
18423 @itemize @bullet
18424 @item
18425 That @code{GDB} should provide basic literals and access to operations for
18426 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18427 leaving more sophisticated computations to subprograms written into the
18428 program (which therefore may be called from @code{GDB}).
18429
18430 @item
18431 That type safety and strict adherence to Ada language restrictions
18432 are not particularly important to the @code{GDB} user.
18433
18434 @item
18435 That brevity is important to the @code{GDB} user.
18436 @end itemize
18437
18438 Thus, for brevity, the debugger acts as if there were
18439 implicit @code{with} and @code{use} clauses in effect for all user-written
18440 packages, thus making it unnecessary to fully qualify most names with
18441 their packages, regardless of context. Where this causes ambiguity,
18442 @code{GDB} asks the user's intent.
18443
18444 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
18445
18446 @node Calling User-Defined Subprograms
18447 @section Calling User-Defined Subprograms
18448
18449 @noindent
18450 An important capability of @code{GDB} is the ability to call user-defined
18451 subprograms while debugging. This is achieved simply by entering
18452 a subprogram call statement in the form:
18453
18454 @smallexample
18455 call subprogram-name (parameters)
18456 @end smallexample
18457
18458 @noindent
18459 The keyword @code{call} can be omitted in the normal case where the
18460 @code{subprogram-name} does not coincide with any of the predefined
18461 @code{GDB} commands.
18462
18463 The effect is to invoke the given subprogram, passing it the
18464 list of parameters that is supplied. The parameters can be expressions and
18465 can include variables from the program being debugged. The
18466 subprogram must be defined
18467 at the library level within your program, and @code{GDB} will call the
18468 subprogram within the environment of your program execution (which
18469 means that the subprogram is free to access or even modify variables
18470 within your program).
18471
18472 The most important use of this facility is in allowing the inclusion of
18473 debugging routines that are tailored to particular data structures
18474 in your program. Such debugging routines can be written to provide a suitably
18475 high-level description of an abstract type, rather than a low-level dump
18476 of its physical layout. After all, the standard
18477 @code{GDB print} command only knows the physical layout of your
18478 types, not their abstract meaning. Debugging routines can provide information
18479 at the desired semantic level and are thus enormously useful.
18480
18481 For example, when debugging GNAT itself, it is crucial to have access to
18482 the contents of the tree nodes used to represent the program internally.
18483 But tree nodes are represented simply by an integer value (which in turn
18484 is an index into a table of nodes).
18485 Using the @code{print} command on a tree node would simply print this integer
18486 value, which is not very useful. But the PN routine (defined in file
18487 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18488 a useful high level representation of the tree node, which includes the
18489 syntactic category of the node, its position in the source, the integers
18490 that denote descendant nodes and parent node, as well as varied
18491 semantic information. To study this example in more detail, you might want to
18492 look at the body of the PN procedure in the stated file.
18493
18494 @node Using the Next Command in a Function
18495 @section Using the Next Command in a Function
18496
18497 @noindent
18498 When you use the @code{next} command in a function, the current source
18499 location will advance to the next statement as usual. A special case
18500 arises in the case of a @code{return} statement.
18501
18502 Part of the code for a return statement is the ``epilog'' of the function.
18503 This is the code that returns to the caller. There is only one copy of
18504 this epilog code, and it is typically associated with the last return
18505 statement in the function if there is more than one return. In some
18506 implementations, this epilog is associated with the first statement
18507 of the function.
18508
18509 The result is that if you use the @code{next} command from a return
18510 statement that is not the last return statement of the function you
18511 may see a strange apparent jump to the last return statement or to
18512 the start of the function. You should simply ignore this odd jump.
18513 The value returned is always that from the first return statement
18514 that was stepped through.
18515
18516 @node Ada Exceptions
18517 @section Breaking on Ada Exceptions
18518 @cindex Exceptions
18519
18520 @noindent
18521 You can set breakpoints that trip when your program raises
18522 selected exceptions.
18523
18524 @table @code
18525 @item break exception
18526 Set a breakpoint that trips whenever (any task in the) program raises
18527 any exception.
18528
18529 @item break exception @var{name}
18530 Set a breakpoint that trips whenever (any task in the) program raises
18531 the exception @var{name}.
18532
18533 @item break exception unhandled
18534 Set a breakpoint that trips whenever (any task in the) program raises an
18535 exception for which there is no handler.
18536
18537 @item info exceptions
18538 @itemx info exceptions @var{regexp}
18539 The @code{info exceptions} command permits the user to examine all defined
18540 exceptions within Ada programs. With a regular expression, @var{regexp}, as
18541 argument, prints out only those exceptions whose name matches @var{regexp}.
18542 @end table
18543
18544 @node Ada Tasks
18545 @section Ada Tasks
18546 @cindex Tasks
18547
18548 @noindent
18549 @code{GDB} allows the following task-related commands:
18550
18551 @table @code
18552 @item info tasks
18553 This command shows a list of current Ada tasks, as in the following example:
18554
18555 @smallexample
18556 @iftex
18557 @leftskip=0cm
18558 @end iftex
18559 (gdb) info tasks
18560   ID       TID P-ID   Thread Pri State                 Name
18561    1   8088000   0   807e000  15 Child Activation Wait main_task
18562    2   80a4000   1   80ae000  15 Accept/Select Wait    b
18563    3   809a800   1   80a4800  15 Child Activation Wait a
18564 *  4   80ae800   3   80b8000  15 Running               c
18565 @end smallexample
18566
18567 @noindent
18568 In this listing, the asterisk before the first task indicates it to be the
18569 currently running task. The first column lists the task ID that is used
18570 to refer to tasks in the following commands.
18571
18572 @item break @var{linespec} task @var{taskid}
18573 @itemx break @var{linespec} task @var{taskid} if @dots{}
18574 @cindex Breakpoints and tasks
18575 These commands are like the @code{break @dots{} thread @dots{}}.
18576 @var{linespec} specifies source lines.
18577
18578 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
18579 to specify that you only want @code{GDB} to stop the program when a
18580 particular Ada task reaches this breakpoint. @var{taskid} is one of the
18581 numeric task identifiers assigned by @code{GDB}, shown in the first
18582 column of the @samp{info tasks} display.
18583
18584 If you do not specify @samp{task @var{taskid}} when you set a
18585 breakpoint, the breakpoint applies to @emph{all} tasks of your
18586 program.
18587
18588 You can use the @code{task} qualifier on conditional breakpoints as
18589 well; in this case, place @samp{task @var{taskid}} before the
18590 breakpoint condition (before the @code{if}).
18591
18592 @item task @var{taskno}
18593 @cindex Task switching
18594
18595 This command allows to switch to the task referred by @var{taskno}. In
18596 particular, This allows to browse the backtrace of the specified
18597 task. It is advised to switch back to the original task before
18598 continuing execution otherwise the scheduling of the program may be
18599 perturbated.
18600 @end table
18601
18602 @noindent
18603 For more detailed information on the tasking support,
18604 see @cite{Debugging with GDB}.
18605
18606 @node Debugging Generic Units
18607 @section Debugging Generic Units
18608 @cindex Debugging Generic Units
18609 @cindex Generics
18610
18611 @noindent
18612 GNAT always uses code expansion for generic instantiation. This means that
18613 each time an instantiation occurs, a complete copy of the original code is
18614 made, with appropriate substitutions of formals by actuals.
18615
18616 It is not possible to refer to the original generic entities in
18617 @code{GDB}, but it is always possible to debug a particular instance of
18618 a generic, by using the appropriate expanded names. For example, if we have
18619
18620 @smallexample @c ada
18621 @group
18622 @cartouche
18623 procedure g is
18624
18625    generic package k is
18626       procedure kp (v1 : in out integer);
18627    end k;
18628
18629    package body k is
18630       procedure kp (v1 : in out integer) is
18631       begin
18632          v1 := v1 + 1;
18633       end kp;
18634    end k;
18635
18636    package k1 is new k;
18637    package k2 is new k;
18638
18639    var : integer := 1;
18640
18641 begin
18642    k1.kp (var);
18643    k2.kp (var);
18644    k1.kp (var);
18645    k2.kp (var);
18646 end;
18647 @end cartouche
18648 @end group
18649 @end smallexample
18650
18651 @noindent
18652 Then to break on a call to procedure kp in the k2 instance, simply
18653 use the command:
18654
18655 @smallexample
18656 (gdb) break g.k2.kp
18657 @end smallexample
18658
18659 @noindent
18660 When the breakpoint occurs, you can step through the code of the
18661 instance in the normal manner and examine the values of local variables, as for
18662 other units.
18663
18664 @node GNAT Abnormal Termination or Failure to Terminate
18665 @section GNAT Abnormal Termination or Failure to Terminate
18666 @cindex GNAT Abnormal Termination or Failure to Terminate
18667
18668 @noindent
18669 When presented with programs that contain serious errors in syntax
18670 or semantics,
18671 GNAT may on rare occasions  experience problems in operation, such
18672 as aborting with a
18673 segmentation fault or illegal memory access, raising an internal
18674 exception, terminating abnormally, or failing to terminate at all.
18675 In such cases, you can activate
18676 various features of GNAT that can help you pinpoint the construct in your
18677 program that is the likely source of the problem.
18678
18679 The following strategies are presented in increasing order of
18680 difficulty, corresponding to your experience in using GNAT and your
18681 familiarity with compiler internals.
18682
18683 @enumerate
18684 @item
18685 Run @code{gcc} with the @option{-gnatf}. This first
18686 switch causes all errors on a given line to be reported. In its absence,
18687 only the first error on a line is displayed.
18688
18689 The @option{-gnatdO} switch causes errors to be displayed as soon as they
18690 are encountered, rather than after compilation is terminated. If GNAT
18691 terminates prematurely or goes into an infinite loop, the last error
18692 message displayed may help to pinpoint the culprit.
18693
18694 @item
18695 Run @code{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this mode,
18696 @code{gcc} produces ongoing information about the progress of the
18697 compilation and provides the name of each procedure as code is
18698 generated. This switch allows you to find which Ada procedure was being
18699 compiled when it encountered a code generation problem.
18700
18701 @item
18702 @cindex @option{-gnatdc} switch
18703 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
18704 switch that does for the front-end what @option{^-v^VERBOSE^} does
18705 for the back end. The system prints the name of each unit,
18706 either a compilation unit or nested unit, as it is being analyzed.
18707 @item
18708 Finally, you can start
18709 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
18710 front-end of GNAT, and can be run independently (normally it is just
18711 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
18712 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
18713 @code{where} command is the first line of attack; the variable
18714 @code{lineno} (seen by @code{print lineno}), used by the second phase of
18715 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
18716 which the execution stopped, and @code{input_file name} indicates the name of
18717 the source file.
18718 @end enumerate
18719
18720 @node Naming Conventions for GNAT Source Files
18721 @section Naming Conventions for GNAT Source Files
18722
18723 @noindent
18724 In order to examine the workings of the GNAT system, the following
18725 brief description of its organization may be helpful:
18726
18727 @itemize @bullet
18728 @item
18729 Files with prefix @file{^sc^SC^} contain the lexical scanner.
18730
18731 @item
18732 All files prefixed with @file{^par^PAR^} are components of the parser. The
18733 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
18734 parsing of select statements can be found in @file{par-ch9.adb}.
18735
18736 @item
18737 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
18738 numbers correspond to chapters of the Ada standard. For example, all
18739 issues involving context clauses can be found in @file{sem_ch10.adb}. In
18740 addition, some features of the language require sufficient special processing
18741 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
18742 dynamic dispatching, etc.
18743
18744 @item
18745 All files prefixed with @file{^exp^EXP^} perform normalization and
18746 expansion of the intermediate representation (abstract syntax tree, or AST).
18747 these files use the same numbering scheme as the parser and semantics files.
18748 For example, the construction of record initialization procedures is done in
18749 @file{exp_ch3.adb}.
18750
18751 @item
18752 The files prefixed with @file{^bind^BIND^} implement the binder, which
18753 verifies the consistency of the compilation, determines an order of
18754 elaboration, and generates the bind file.
18755
18756 @item
18757 The files @file{atree.ads} and @file{atree.adb} detail the low-level
18758 data structures used by the front-end.
18759
18760 @item
18761 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
18762 the abstract syntax tree as produced by the parser.
18763
18764 @item
18765 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
18766 all entities, computed during semantic analysis.
18767
18768 @item
18769 Library management issues are dealt with in files with prefix
18770 @file{^lib^LIB^}.
18771
18772 @item
18773 @findex Ada
18774 @cindex Annex A
18775 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
18776 defined in Annex A.
18777
18778 @item
18779 @findex Interfaces
18780 @cindex Annex B
18781 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
18782 defined in Annex B.
18783
18784 @item
18785 @findex System
18786 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
18787 both language-defined children and GNAT run-time routines.
18788
18789 @item
18790 @findex GNAT
18791 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
18792 general-purpose packages, fully documented in their specifications. All
18793 the other @file{.c} files are modifications of common @code{gcc} files.
18794 @end itemize
18795
18796 @node Getting Internal Debugging Information
18797 @section Getting Internal Debugging Information
18798
18799 @noindent
18800 Most compilers have internal debugging switches and modes. GNAT
18801 does also, except GNAT internal debugging switches and modes are not
18802 secret. A summary and full description of all the compiler and binder
18803 debug flags are in the file @file{debug.adb}. You must obtain the
18804 sources of the compiler to see the full detailed effects of these flags.
18805
18806 The switches that print the source of the program (reconstructed from
18807 the internal tree) are of general interest for user programs, as are the
18808 options to print
18809 the full internal tree, and the entity table (the symbol table
18810 information). The reconstructed source provides a readable version of the
18811 program after the front-end has completed analysis and  expansion,
18812 and is useful when studying the performance of specific constructs.
18813 For example, constraint checks are indicated, complex aggregates
18814 are replaced with loops and assignments, and tasking primitives
18815 are replaced with run-time calls.
18816
18817 @node Stack Traceback
18818 @section Stack Traceback
18819 @cindex traceback
18820 @cindex stack traceback
18821 @cindex stack unwinding
18822
18823 @noindent
18824 Traceback is a mechanism to display the sequence of subprogram calls that
18825 leads to a specified execution point in a program. Often (but not always)
18826 the execution point is an instruction at which an exception has been raised.
18827 This mechanism is also known as @i{stack unwinding} because it obtains
18828 its information by scanning the run-time stack and recovering the activation
18829 records of all active subprograms. Stack unwinding is one of the most
18830 important tools for program debugging.
18831
18832 The first entry stored in traceback corresponds to the deepest calling level,
18833 that is to say the subprogram currently executing the instruction
18834 from which we want to obtain the traceback.
18835
18836 Note that there is no runtime performance penalty when stack traceback
18837 is enabled, and no exception is raised during program execution.
18838
18839 @menu
18840 * Non-Symbolic Traceback::
18841 * Symbolic Traceback::
18842 @end menu
18843
18844 @node Non-Symbolic Traceback
18845 @subsection Non-Symbolic Traceback
18846 @cindex traceback, non-symbolic
18847
18848 @noindent
18849 Note: this feature is not supported on all platforms. See
18850 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
18851 platforms.
18852
18853 @menu
18854 * Tracebacks From an Unhandled Exception::
18855 * Tracebacks From Exception Occurrences (non-symbolic)::
18856 * Tracebacks From Anywhere in a Program (non-symbolic)::
18857 @end menu
18858
18859 @node Tracebacks From an Unhandled Exception
18860 @subsubsection Tracebacks From an Unhandled Exception
18861
18862 @noindent
18863 A runtime non-symbolic traceback is a list of addresses of call instructions.
18864 To enable this feature you must use the @option{-E}
18865 @code{gnatbind}'s option. With this option a stack traceback is stored as part
18866 of exception information. You can retrieve this information using the
18867 @code{addr2line} tool.
18868
18869 Here is a simple example:
18870
18871 @smallexample @c ada
18872 @cartouche
18873 procedure STB is
18874
18875    procedure P1 is
18876    begin
18877       raise Constraint_Error;
18878    end P1;
18879
18880    procedure P2 is
18881    begin
18882       P1;
18883    end P2;
18884
18885 begin
18886    P2;
18887 end STB;
18888 @end cartouche
18889 @end smallexample
18890
18891 @smallexample
18892 $ gnatmake stb -bargs -E
18893 $ stb
18894
18895 Execution terminated by unhandled exception
18896 Exception name: CONSTRAINT_ERROR
18897 Message: stb.adb:5
18898 Call stack traceback locations:
18899 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
18900 @end smallexample
18901
18902 @noindent
18903 As we see the traceback lists a sequence of addresses for the unhandled
18904 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
18905 guess that this exception come from procedure P1. To translate these
18906 addresses into the source lines where the calls appear, the
18907 @code{addr2line} tool, described below, is invaluable. The use of this tool
18908 requires the program to be compiled with debug information.
18909
18910 @smallexample
18911 $ gnatmake -g stb -bargs -E
18912 $ stb
18913
18914 Execution terminated by unhandled exception
18915 Exception name: CONSTRAINT_ERROR
18916 Message: stb.adb:5
18917 Call stack traceback locations:
18918 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
18919
18920 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
18921    0x4011f1 0x77e892a4
18922
18923 00401373 at d:/stb/stb.adb:5
18924 0040138B at d:/stb/stb.adb:10
18925 0040139C at d:/stb/stb.adb:14
18926 00401335 at d:/stb/b~stb.adb:104
18927 004011C4 at /build/.../crt1.c:200
18928 004011F1 at /build/.../crt1.c:222
18929 77E892A4 in ?? at ??:0
18930 @end smallexample
18931
18932 @noindent
18933 The @code{addr2line} tool has several other useful options:
18934
18935 @table @code
18936 @item --functions
18937 to get the function name corresponding to any location
18938
18939 @item --demangle=gnat
18940 to use the gnat decoding mode for the function names. Note that
18941 for binutils version 2.9.x the option is simply @option{--demangle}.
18942 @end table
18943
18944 @smallexample
18945 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
18946    0x40139c 0x401335 0x4011c4 0x4011f1
18947
18948 00401373 in stb.p1 at d:/stb/stb.adb:5
18949 0040138B in stb.p2 at d:/stb/stb.adb:10
18950 0040139C in stb at d:/stb/stb.adb:14
18951 00401335 in main at d:/stb/b~stb.adb:104
18952 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
18953 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
18954 @end smallexample
18955
18956 @noindent
18957 From this traceback we can see that the exception was raised in
18958 @file{stb.adb} at line 5, which was reached from a procedure call in
18959 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
18960 which contains the call to the main program.
18961 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
18962 and the output will vary from platform to platform.
18963
18964 It is also possible to use @code{GDB} with these traceback addresses to debug
18965 the program. For example, we can break at a given code location, as reported
18966 in the stack traceback:
18967
18968 @smallexample
18969 $ gdb -nw stb
18970 @ifclear vms
18971 @noindent
18972 Furthermore, this feature is not implemented inside Windows DLL. Only
18973 the non-symbolic traceback is reported in this case.
18974 @end ifclear
18975
18976 (gdb) break *0x401373
18977 Breakpoint 1 at 0x401373: file stb.adb, line 5.
18978 @end smallexample
18979
18980 @noindent
18981 It is important to note that the stack traceback addresses
18982 do not change when debug information is included. This is particularly useful
18983 because it makes it possible to release software without debug information (to
18984 minimize object size), get a field report that includes a stack traceback
18985 whenever an internal bug occurs, and then be able to retrieve the sequence
18986 of calls with the same program compiled with debug information.
18987
18988 @node Tracebacks From Exception Occurrences (non-symbolic)
18989 @subsubsection Tracebacks From Exception Occurrences
18990
18991 @noindent
18992 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
18993 The stack traceback is attached to the exception information string, and can
18994 be retrieved in an exception handler within the Ada program, by means of the
18995 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
18996
18997 @smallexample @c ada
18998 with Ada.Text_IO;
18999 with Ada.Exceptions;
19000
19001 procedure STB is
19002
19003    use Ada;
19004    use Ada.Exceptions;
19005
19006    procedure P1 is
19007       K : Positive := 1;
19008    begin
19009       K := K - 1;
19010    exception
19011       when E : others =>
19012          Text_IO.Put_Line (Exception_Information (E));
19013    end P1;
19014
19015    procedure P2 is
19016    begin
19017       P1;
19018    end P2;
19019
19020 begin
19021    P2;
19022 end STB;
19023 @end smallexample
19024
19025 @noindent
19026 This program will output:
19027
19028 @smallexample
19029 $ stb
19030
19031 Exception name: CONSTRAINT_ERROR
19032 Message: stb.adb:12
19033 Call stack traceback locations:
19034 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19035 @end smallexample
19036
19037 @node Tracebacks From Anywhere in a Program (non-symbolic)
19038 @subsubsection Tracebacks From Anywhere in a Program
19039
19040 @noindent
19041 It is also possible to retrieve a stack traceback from anywhere in a
19042 program. For this you need to
19043 use the @code{GNAT.Traceback} API. This package includes a procedure called
19044 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19045 display procedures described below. It is not necessary to use the
19046 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19047 is invoked explicitly.
19048
19049 @noindent
19050 In the following example we compute a traceback at a specific location in
19051 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19052 convert addresses to strings:
19053
19054 @smallexample @c ada
19055 with Ada.Text_IO;
19056 with GNAT.Traceback;
19057 with GNAT.Debug_Utilities;
19058
19059 procedure STB is
19060
19061    use Ada;
19062    use GNAT;
19063    use GNAT.Traceback;
19064
19065    procedure P1 is
19066       TB  : Tracebacks_Array (1 .. 10);
19067       --  We are asking for a maximum of 10 stack frames.
19068       Len : Natural;
19069       --  Len will receive the actual number of stack frames returned.
19070    begin
19071       Call_Chain (TB, Len);
19072
19073       Text_IO.Put ("In STB.P1 : ");
19074
19075       for K in 1 .. Len loop
19076          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19077          Text_IO.Put (' ');
19078       end loop;
19079
19080       Text_IO.New_Line;
19081    end P1;
19082
19083    procedure P2 is
19084    begin
19085       P1;
19086    end P2;
19087
19088 begin
19089    P2;
19090 end STB;
19091 @end smallexample
19092
19093 @smallexample
19094 $ gnatmake -g stb
19095 $ stb
19096
19097 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19098 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19099 @end smallexample
19100
19101 @noindent
19102 You can then get further information by invoking the @code{addr2line}
19103 tool as described earlier (note that the hexadecimal addresses
19104 need to be specified in C format, with a leading ``0x'').
19105
19106
19107 @node Symbolic Traceback
19108 @subsection Symbolic Traceback
19109 @cindex traceback, symbolic
19110
19111 @noindent
19112 A symbolic traceback is a stack traceback in which procedure names are
19113 associated with each code location.
19114
19115 @noindent
19116 Note that this feature is not supported on all platforms. See
19117 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19118 list of currently supported platforms.
19119
19120 @noindent
19121 Note that the symbolic traceback requires that the program be compiled
19122 with debug information. If it is not compiled with debug information
19123 only the non-symbolic information will be valid.
19124
19125 @menu
19126 * Tracebacks From Exception Occurrences (symbolic)::
19127 * Tracebacks From Anywhere in a Program (symbolic)::
19128 @end menu
19129
19130 @node Tracebacks From Exception Occurrences (symbolic)
19131 @subsubsection Tracebacks From Exception Occurrences
19132
19133 @smallexample @c ada
19134 with Ada.Text_IO;
19135 with GNAT.Traceback.Symbolic;
19136
19137 procedure STB is
19138
19139    procedure P1 is
19140    begin
19141       raise Constraint_Error;
19142    end P1;
19143
19144    procedure P2 is
19145    begin
19146       P1;
19147    end P2;
19148
19149    procedure P3 is
19150    begin
19151       P2;
19152    end P3;
19153
19154 begin
19155    P3;
19156 exception
19157    when E : others =>
19158       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19159 end STB;
19160 @end smallexample
19161
19162 @smallexample
19163 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19164 $ stb
19165
19166 0040149F in stb.p1 at stb.adb:8
19167 004014B7 in stb.p2 at stb.adb:13
19168 004014CF in stb.p3 at stb.adb:18
19169 004015DD in ada.stb at stb.adb:22
19170 00401461 in main at b~stb.adb:168
19171 004011C4 in __mingw_CRTStartup at crt1.c:200
19172 004011F1 in mainCRTStartup at crt1.c:222
19173 77E892A4 in ?? at ??:0
19174 @end smallexample
19175
19176 @noindent
19177 In the above example the ``.\'' syntax in the @command{gnatmake} command
19178 is currently required by @command{addr2line} for files that are in
19179 the current working directory.
19180 Moreover, the exact sequence of linker options may vary from platform
19181 to platform.
19182 The above @option{-largs} section is for Windows platforms. By contrast,
19183 under Unix there is no need for the @option{-largs} section.
19184 Differences across platforms are due to details of linker implementation.
19185
19186 @node Tracebacks From Anywhere in a Program (symbolic)
19187 @subsubsection Tracebacks From Anywhere in a Program
19188
19189 @noindent
19190 It is possible to get a symbolic stack traceback
19191 from anywhere in a program, just as for non-symbolic tracebacks.
19192 The first step is to obtain a non-symbolic
19193 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19194 information. Here is an example:
19195
19196 @smallexample @c ada
19197 with Ada.Text_IO;
19198 with GNAT.Traceback;
19199 with GNAT.Traceback.Symbolic;
19200
19201 procedure STB is
19202
19203    use Ada;
19204    use GNAT.Traceback;
19205    use GNAT.Traceback.Symbolic;
19206
19207    procedure P1 is
19208       TB  : Tracebacks_Array (1 .. 10);
19209       --  We are asking for a maximum of 10 stack frames.
19210       Len : Natural;
19211       --  Len will receive the actual number of stack frames returned.
19212    begin
19213       Call_Chain (TB, Len);
19214       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19215    end P1;
19216
19217    procedure P2 is
19218    begin
19219       P1;
19220    end P2;
19221
19222 begin
19223    P2;
19224 end STB;
19225 @end smallexample
19226
19227 @ifset vms
19228 @node Compatibility with DEC Ada
19229 @chapter Compatibility with DEC Ada
19230 @cindex Compatibility
19231
19232 @noindent
19233 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
19234 OpenVMS Alpha. GNAT achieves a high level of compatibility
19235 with DEC Ada, and it should generally be straightforward to port code
19236 from the DEC Ada environment to GNAT. However, there are a few language
19237 and implementation differences of which the user must be aware. These
19238 differences are discussed in this section. In
19239 addition, the operating environment and command structure for the
19240 compiler are different, and these differences are also discussed.
19241
19242 Note that this discussion addresses specifically the implementation
19243 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
19244 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19245 GNAT always follows the Alpha implementation.
19246
19247 @menu
19248 * Ada 95 Compatibility::
19249 * Differences in the Definition of Package System::
19250 * Language-Related Features::
19251 * The Package STANDARD::
19252 * The Package SYSTEM::
19253 * Tasking and Task-Related Features::
19254 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
19255 * Pragmas and Pragma-Related Features::
19256 * Library of Predefined Units::
19257 * Bindings::
19258 * Main Program Definition::
19259 * Implementation-Defined Attributes::
19260 * Compiler and Run-Time Interfacing::
19261 * Program Compilation and Library Management::
19262 * Input-Output::
19263 * Implementation Limits::
19264 * Tools::
19265 @end menu
19266
19267 @node Ada 95 Compatibility
19268 @section Ada 95 Compatibility
19269
19270 @noindent
19271 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
19272 compiler. Ada 95 is almost completely upwards compatible
19273 with Ada 83, and therefore Ada 83 programs will compile
19274 and run under GNAT with
19275 no changes or only minor changes. The Ada 95 Reference
19276 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
19277 incompatibilities.
19278
19279 GNAT provides the switch /83 on the GNAT COMPILE command,
19280 as well as the pragma ADA_83, to force the compiler to
19281 operate in Ada 83 mode. This mode does not guarantee complete
19282 conformance to Ada 83, but in practice is sufficient to
19283 eliminate most sources of incompatibilities.
19284 In particular, it eliminates the recognition of the
19285 additional Ada 95 keywords, so that their use as identifiers
19286 in Ada83 program is legal, and handles the cases of packages
19287 with optional bodies, and generics that instantiate unconstrained
19288 types without the use of @code{(<>)}.
19289
19290 @node Differences in the Definition of Package System
19291 @section Differences in the Definition of Package System
19292
19293 @noindent
19294 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
19295 implementation-dependent declarations to package System. In normal mode,
19296 GNAT does not take advantage of this permission, and the version of System
19297 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
19298
19299 However, DEC Ada adds an extensive set of declarations to package System,
19300 as fully documented in the DEC Ada manuals. To minimize changes required
19301 for programs that make use of these extensions, GNAT provides the pragma
19302 Extend_System for extending the definition of package System. By using:
19303
19304 @smallexample @c ada
19305 @group
19306 @cartouche
19307 pragma Extend_System (Aux_DEC);
19308 @end cartouche
19309 @end group
19310 @end smallexample
19311
19312 @noindent
19313 The set of definitions in System is extended to include those in package
19314 @code{System.Aux_DEC}.
19315 These definitions are incorporated directly into package
19316 System, as though they had been declared there in the first place. For a
19317 list of the declarations added, see the specification of this package,
19318 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
19319 The pragma Extend_System is a configuration pragma, which means that
19320 it can be placed in the file @file{gnat.adc}, so that it will automatically
19321 apply to all subsequent compilations. See the section on Configuration
19322 Pragmas for further details.
19323
19324 An alternative approach that avoids the use of the non-standard
19325 Extend_System pragma is to add a context clause to the unit that
19326 references these facilities:
19327
19328 @smallexample @c ada
19329 @group
19330 @cartouche
19331 with System.Aux_DEC;
19332 use  System.Aux_DEC;
19333 @end cartouche
19334 @end group
19335 @end smallexample
19336
19337 @noindent
19338 The effect is not quite semantically identical to incorporating
19339 the declarations directly into package @code{System},
19340 but most programs will not notice a difference
19341 unless they use prefix notation (e.g. @code{System.Integer_8})
19342 to reference the
19343 entities directly in package @code{System}.
19344 For units containing such references,
19345 the prefixes must either be removed, or the pragma @code{Extend_System}
19346 must be used.
19347
19348 @node Language-Related Features
19349 @section Language-Related Features
19350
19351 @noindent
19352 The following sections highlight differences in types,
19353 representations of types, operations, alignment, and
19354 related topics.
19355
19356 @menu
19357 * Integer Types and Representations::
19358 * Floating-Point Types and Representations::
19359 * Pragmas Float_Representation and Long_Float::
19360 * Fixed-Point Types and Representations::
19361 * Record and Array Component Alignment::
19362 * Address Clauses::
19363 * Other Representation Clauses::
19364 @end menu
19365
19366 @node Integer Types and Representations
19367 @subsection Integer Types and Representations
19368
19369 @noindent
19370 The set of predefined integer types is identical in DEC Ada and GNAT.
19371 Furthermore the representation of these integer types is also identical,
19372 including the capability of size clauses forcing biased representation.
19373
19374 In addition,
19375 DEC Ada for OpenVMS Alpha systems has defined the
19376 following additional integer types in package System:
19377
19378 @itemize @bullet
19379
19380 @item
19381 INTEGER_8
19382
19383 @item
19384 INTEGER_16
19385
19386 @item
19387 INTEGER_32
19388
19389 @item
19390 INTEGER_64
19391
19392 @item
19393 LARGEST_INTEGER
19394 @end itemize
19395
19396 @noindent
19397 When using GNAT, the first four of these types may be obtained from the
19398 standard Ada 95 package @code{Interfaces}.
19399 Alternatively, by use of the pragma
19400 @code{Extend_System}, identical
19401 declarations can be referenced directly in package @code{System}.
19402 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
19403
19404 @node Floating-Point Types and Representations
19405 @subsection Floating-Point Types and Representations
19406 @cindex Floating-Point types
19407
19408 @noindent
19409 The set of predefined floating-point types is identical in DEC Ada and GNAT.
19410 Furthermore the representation of these floating-point
19411 types is also identical. One important difference is that the default
19412 representation for DEC Ada is VAX_Float, but the default representation
19413 for GNAT is IEEE.
19414
19415 Specific types may be declared to be VAX_Float or IEEE, using the pragma
19416 @code{Float_Representation} as described in the DEC Ada documentation.
19417 For example, the declarations:
19418
19419 @smallexample @c ada
19420 @group
19421 @cartouche
19422 type F_Float is digits 6;
19423 pragma Float_Representation (VAX_Float, F_Float);
19424 @end cartouche
19425 @end group
19426 @end smallexample
19427
19428 @noindent
19429 declare a type F_Float that will be represented in VAX_Float format.
19430 This set of declarations actually appears in System.Aux_DEC, which provides
19431 the full set of additional floating-point declarations provided in
19432 the DEC Ada version of package
19433 System. This and similar declarations may be accessed in a user program
19434 by using pragma @code{Extend_System}. The use of this
19435 pragma, and the related pragma @code{Long_Float} is described in further
19436 detail in the following section.
19437
19438 @node Pragmas Float_Representation and Long_Float
19439 @subsection Pragmas Float_Representation and Long_Float
19440
19441 @noindent
19442 DEC Ada provides the pragma @code{Float_Representation}, which
19443 acts as a program library switch to allow control over
19444 the internal representation chosen for the predefined
19445 floating-point types declared in the package @code{Standard}.
19446 The format of this pragma is as follows:
19447
19448 @smallexample
19449 @group
19450 @cartouche
19451 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
19452 @end cartouche
19453 @end group
19454 @end smallexample
19455
19456 @noindent
19457 This pragma controls the representation of floating-point
19458 types as follows:
19459
19460 @itemize @bullet
19461 @item
19462 @code{VAX_Float} specifies that floating-point
19463 types are represented by default with the VAX hardware types
19464 F-floating, D-floating, G-floating. Note that the H-floating
19465 type is available only on DIGITAL Vax systems, and is not available
19466 in either DEC Ada or GNAT for Alpha systems.
19467
19468 @item
19469 @code{IEEE_Float} specifies that floating-point
19470 types are represented by default with the IEEE single and
19471 double floating-point types.
19472 @end itemize
19473
19474 @noindent
19475 GNAT provides an identical implementation of the pragma
19476 @code{Float_Representation}, except that it functions as a
19477 configuration pragma, as defined by Ada 95. Note that the
19478 notion of configuration pragma corresponds closely to the
19479 DEC Ada notion of a program library switch.
19480
19481 When no pragma is used in GNAT, the default is IEEE_Float, which is different
19482 from DEC Ada 83, where the default is VAX_Float. In addition, the
19483 predefined libraries in GNAT are built using IEEE_Float, so it is not
19484 advisable to change the format of numbers passed to standard library
19485 routines, and if necessary explicit type conversions may be needed.
19486
19487 The use of IEEE_Float is recommended in GNAT since it is more efficient,
19488 and (given that it conforms to an international standard) potentially more
19489 portable. The situation in which VAX_Float may be useful is in interfacing
19490 to existing code and data that expects the use of VAX_Float. There are
19491 two possibilities here. If the requirement for the use of VAX_Float is
19492 localized, then the best approach is to use the predefined VAX_Float
19493 types in package @code{System}, as extended by
19494 @code{Extend_System}. For example, use @code{System.F_Float}
19495 to specify the 32-bit @code{F-Float} format.
19496
19497 Alternatively, if an entire program depends heavily on the use of
19498 the @code{VAX_Float} and in particular assumes that the types in
19499 package @code{Standard} are in @code{Vax_Float} format, then it
19500 may be desirable to reconfigure GNAT to assume Vax_Float by default.
19501 This is done by using the GNAT LIBRARY command to rebuild the library, and
19502 then using the general form of the @code{Float_Representation}
19503 pragma to ensure that this default format is used throughout.
19504 The form of the GNAT LIBRARY command is:
19505
19506 @smallexample
19507 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
19508 @end smallexample
19509
19510 @noindent
19511 where @i{file} contains the new configuration pragmas
19512 and @i{directory} is the directory to be created to contain
19513 the new library.
19514
19515 @noindent
19516 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
19517 to allow control over the internal representation chosen
19518 for the predefined type @code{Long_Float} and for floating-point
19519 type declarations with digits specified in the range 7 .. 15.
19520 The format of this pragma is as follows:
19521
19522 @smallexample @c ada
19523 @cartouche
19524 pragma Long_Float (D_FLOAT | G_FLOAT);
19525 @end cartouche
19526 @end smallexample
19527
19528 @node Fixed-Point Types and Representations
19529 @subsection Fixed-Point Types and Representations
19530
19531 @noindent
19532 On DEC Ada for OpenVMS Alpha systems, rounding is
19533 away from zero for both positive and negative numbers.
19534 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
19535
19536 On GNAT for OpenVMS Alpha, the results of operations
19537 on fixed-point types are in accordance with the Ada 95
19538 rules. In particular, results of operations on decimal
19539 fixed-point types are truncated.
19540
19541 @node Record and Array Component Alignment
19542 @subsection Record and Array Component Alignment
19543
19544 @noindent
19545 On DEC Ada for OpenVMS Alpha, all non composite components
19546 are aligned on natural boundaries. For example, 1-byte
19547 components are aligned on byte boundaries, 2-byte
19548 components on 2-byte boundaries, 4-byte components on 4-byte
19549 byte boundaries, and so on. The OpenVMS Alpha hardware
19550 runs more efficiently with naturally aligned data.
19551
19552 ON GNAT for OpenVMS Alpha, alignment rules are compatible
19553 with DEC Ada for OpenVMS Alpha.
19554
19555 @node Address Clauses
19556 @subsection Address Clauses
19557
19558 @noindent
19559 In DEC Ada and GNAT, address clauses are supported for
19560 objects and imported subprograms.
19561 The predefined type @code{System.Address} is a private type
19562 in both compilers, with the same representation (it is simply
19563 a machine pointer). Addition, subtraction, and comparison
19564 operations are available in the standard Ada 95 package
19565 @code{System.Storage_Elements}, or in package @code{System}
19566 if it is extended to include @code{System.Aux_DEC} using a
19567 pragma @code{Extend_System} as previously described.
19568
19569 Note that code that with's both this extended package @code{System}
19570 and the package @code{System.Storage_Elements} should not @code{use}
19571 both packages, or ambiguities will result. In general it is better
19572 not to mix these two sets of facilities. The Ada 95 package was
19573 designed specifically to provide the kind of features that DEC Ada
19574 adds directly to package @code{System}.
19575
19576 GNAT is compatible with DEC Ada in its handling of address
19577 clauses, except for some limitations in
19578 the form of address clauses for composite objects with
19579 initialization. Such address clauses are easily replaced
19580 by the use of an explicitly-defined constant as described
19581 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
19582 of declarations:
19583
19584 @smallexample @c ada
19585 @cartouche
19586 X, Y : Integer := Init_Func;
19587 Q : String (X .. Y) := "abc";
19588 ...
19589 for Q'Address use Compute_Address;
19590 @end cartouche
19591 @end smallexample
19592
19593 @noindent
19594 will be rejected by GNAT, since the address cannot be computed at the time
19595 that Q is declared. To achieve the intended effect, write instead:
19596
19597 @smallexample @c ada
19598 @group
19599 @cartouche
19600 X, Y : Integer := Init_Func;
19601 Q_Address : constant Address := Compute_Address;
19602 Q : String (X .. Y) := "abc";
19603 ...
19604 for Q'Address use Q_Address;
19605 @end cartouche
19606 @end group
19607 @end smallexample
19608
19609 @noindent
19610 which will be accepted by GNAT (and other Ada 95 compilers), and is also
19611 backwards compatible with Ada 83. A fuller description of the restrictions
19612 on address specifications is found in the GNAT Reference Manual.
19613
19614 @node Other Representation Clauses
19615 @subsection Other Representation Clauses
19616
19617 @noindent
19618 GNAT supports in a compatible manner all the representation
19619 clauses supported by DEC Ada. In addition, it
19620 supports representation clause forms that are new in Ada 95
19621 including COMPONENT_SIZE and SIZE clauses for objects.
19622
19623 @node The Package STANDARD
19624 @section The Package STANDARD
19625
19626 @noindent
19627 The package STANDARD, as implemented by DEC Ada, is fully
19628 described in the Reference Manual for the Ada Programming
19629 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
19630 Language Reference Manual. As implemented by GNAT, the
19631 package STANDARD is described in the Ada 95 Reference
19632 Manual.
19633
19634 In addition, DEC Ada supports the Latin-1 character set in
19635 the type CHARACTER. GNAT supports the Latin-1 character set
19636 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
19637 the type WIDE_CHARACTER.
19638
19639 The floating-point types supported by GNAT are those
19640 supported by DEC Ada, but defaults are different, and are controlled by
19641 pragmas. See @pxref{Floating-Point Types and Representations} for details.
19642
19643 @node The Package SYSTEM
19644 @section The Package SYSTEM
19645
19646 @noindent
19647 DEC Ada provides a system-specific version of the package
19648 SYSTEM for each platform on which the language ships.
19649 For the complete specification of the package SYSTEM, see
19650 Appendix F of the DEC Ada Language Reference Manual.
19651
19652 On DEC Ada, the package SYSTEM includes the following conversion functions:
19653 @itemize @bullet
19654 @item TO_ADDRESS(INTEGER)
19655
19656 @item  TO_ADDRESS(UNSIGNED_LONGWORD)
19657
19658 @item  TO_ADDRESS(universal_integer)
19659
19660 @item  TO_INTEGER(ADDRESS)
19661
19662 @item  TO_UNSIGNED_LONGWORD(ADDRESS)
19663
19664 @item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
19665                  functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
19666 @end itemize
19667
19668 @noindent
19669 By default, GNAT supplies a version of SYSTEM that matches
19670 the definition given in the Ada 95 Reference Manual.
19671 This
19672 is a subset of the DIGITAL system definitions, which is as
19673 close as possible to the original definitions. The only difference
19674 is that the definition of SYSTEM_NAME is different:
19675
19676 @smallexample @c ada
19677 @group
19678 @cartouche
19679 type Name is (SYSTEM_NAME_GNAT);
19680 System_Name : constant Name := SYSTEM_NAME_GNAT;
19681 @end cartouche
19682 @end group
19683 @end smallexample
19684
19685 @noindent
19686 Also, GNAT adds the new Ada 95 declarations for
19687 BIT_ORDER and DEFAULT_BIT_ORDER.
19688
19689 However, the use of the following pragma causes GNAT
19690 to extend the definition of package SYSTEM so that it
19691 encompasses the full set of DIGITAL-specific extensions,
19692 including the functions listed above:
19693
19694 @smallexample @c ada
19695 @cartouche
19696 pragma Extend_System (Aux_DEC);
19697 @end cartouche
19698 @end smallexample
19699
19700 @noindent
19701 The pragma Extend_System is a configuration pragma that
19702 is most conveniently placed in the @file{gnat.adc} file. See the
19703 GNAT Reference Manual for further details.
19704
19705 DEC Ada does not allow the recompilation of the package
19706 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
19707 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
19708 the package SYSTEM. On OpenVMS Alpha systems, the pragma
19709 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
19710 its single argument.
19711
19712 GNAT does permit the recompilation of package SYSTEM using
19713 a special switch (@option{-gnatg}) and this switch can be used if
19714 it is necessary to modify the definitions in SYSTEM. GNAT does
19715 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
19716 or MEMORY_SIZE by any other means.
19717
19718 On GNAT systems, the pragma SYSTEM_NAME takes the
19719 enumeration literal SYSTEM_NAME_GNAT.
19720
19721 The definitions provided by the use of
19722
19723 @smallexample @c ada
19724 pragma Extend_System (AUX_Dec);
19725 @end smallexample
19726
19727 @noindent
19728 are virtually identical to those provided by the DEC Ada 83 package
19729 System. One important difference is that the name of the TO_ADDRESS
19730 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
19731 See the GNAT Reference manual for a discussion of why this change was
19732 necessary.
19733
19734 @noindent
19735 The version of TO_ADDRESS taking a universal integer argument is in fact
19736 an extension to Ada 83 not strictly compatible with the reference manual.
19737 In GNAT, we are constrained to be exactly compatible with the standard,
19738 and this means we cannot provide this capability. In DEC Ada 83, the
19739 point of this definition is to deal with a call like:
19740
19741 @smallexample @c ada
19742 TO_ADDRESS (16#12777#);
19743 @end smallexample
19744
19745 @noindent
19746 Normally, according to the Ada 83 standard, one would expect this to be
19747 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
19748 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
19749 definition using universal_integer takes precedence.
19750
19751 In GNAT, since the version with universal_integer cannot be supplied, it is
19752 not possible to be 100% compatible. Since there are many programs using
19753 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
19754 to change the name of the function in the UNSIGNED_LONGWORD case, so the
19755 declarations provided in the GNAT version of AUX_Dec are:
19756
19757 @smallexample @c ada
19758 function To_Address (X : Integer) return Address;
19759 pragma Pure_Function (To_Address);
19760
19761 function To_Address_Long (X : Unsigned_Longword) return Address;
19762 pragma Pure_Function (To_Address_Long);
19763 @end smallexample
19764
19765 @noindent
19766 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
19767 change the name to TO_ADDRESS_LONG.
19768
19769 @node Tasking and Task-Related Features
19770 @section Tasking and Task-Related Features
19771
19772 @noindent
19773 The concepts relevant to a comparison of tasking on GNAT
19774 and on DEC Ada for OpenVMS Alpha systems are discussed in
19775 the following sections.
19776
19777 For detailed information on concepts related to tasking in
19778 DEC Ada, see the DEC Ada Language Reference Manual and the
19779 relevant run-time reference manual.
19780
19781 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
19782 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
19783
19784 @noindent
19785 On OpenVMS Alpha systems, each Ada task (except a passive
19786 task) is implemented as a single stream of execution
19787 that is created and managed by the kernel. On these
19788 systems, DEC Ada tasking support is based on DECthreads,
19789 an implementation of the POSIX standard for threads.
19790
19791 Although tasks are implemented as threads, all tasks in
19792 an Ada program are part of the same process. As a result,
19793 resources such as open files and virtual memory can be
19794 shared easily among tasks. Having all tasks in one process
19795 allows better integration with the programming environment
19796 (the shell and the debugger, for example).
19797
19798 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
19799 code that calls DECthreads routines can be used together.
19800 The interaction between Ada tasks and DECthreads routines
19801 can have some benefits. For example when on OpenVMS Alpha,
19802 DEC Ada can call C code that is already threaded.
19803 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
19804 and Ada tasks are mapped to threads.
19805
19806 @menu
19807 * Assigning Task IDs::
19808 * Task IDs and Delays::
19809 * Task-Related Pragmas::
19810 * Scheduling and Task Priority::
19811 * The Task Stack::
19812 * External Interrupts::
19813 @end menu
19814
19815 @node Assigning Task IDs
19816 @subsection Assigning Task IDs
19817
19818 @noindent
19819 The DEC Ada Run-Time Library always assigns %TASK 1 to
19820 the environment task that executes the main program. On
19821 OpenVMS Alpha systems, %TASK 0 is often used for tasks
19822 that have been created but are not yet activated.
19823
19824 On OpenVMS Alpha systems, task IDs are assigned at
19825 activation. On GNAT systems, task IDs are also assigned at
19826 task creation but do not have the same form or values as
19827 task ID values in DEC Ada. There is no null task, and the
19828 environment task does not have a specific task ID value.
19829
19830 @node Task IDs and Delays
19831 @subsection Task IDs and Delays
19832
19833 @noindent
19834 On OpenVMS Alpha systems, tasking delays are implemented
19835 using Timer System Services. The Task ID is used for the
19836 identification of the timer request (the REQIDT parameter).
19837 If Timers are used in the application take care not to use
19838 0 for the identification, because cancelling such a timer
19839 will cancel all timers and may lead to unpredictable results.
19840
19841 @node Task-Related Pragmas
19842 @subsection Task-Related Pragmas
19843
19844 @noindent
19845 Ada supplies the pragma TASK_STORAGE, which allows
19846 specification of the size of the guard area for a task
19847 stack. (The guard area forms an area of memory that has no
19848 read or write access and thus helps in the detection of
19849 stack overflow.) On OpenVMS Alpha systems, if the pragma
19850 TASK_STORAGE specifies a value of zero, a minimal guard
19851 area is created. In the absence of a pragma TASK_STORAGE, a default guard
19852 area is created.
19853
19854 GNAT supplies the following task-related pragmas:
19855
19856 @itemize @bullet
19857 @item  TASK_INFO
19858
19859               This pragma appears within a task definition and
19860               applies to the task in which it appears. The argument
19861               must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
19862
19863 @item  TASK_STORAGE
19864
19865               GNAT implements pragma TASK_STORAGE in the same way as
19866               DEC Ada.
19867               Both DEC Ada and GNAT supply the pragmas PASSIVE,
19868               SUPPRESS, and VOLATILE.
19869 @end itemize
19870 @node Scheduling and Task Priority
19871 @subsection Scheduling and Task Priority
19872
19873 @noindent
19874 DEC Ada implements the Ada language requirement that
19875 when two tasks are eligible for execution and they have
19876 different priorities, the lower priority task does not
19877 execute while the higher priority task is waiting. The DEC
19878 Ada Run-Time Library keeps a task running until either the
19879 task is suspended or a higher priority task becomes ready.
19880
19881 On OpenVMS Alpha systems, the default strategy is round-
19882 robin with preemption. Tasks of equal priority take turns
19883 at the processor. A task is run for a certain period of
19884 time and then placed at the rear of the ready queue for
19885 its priority level.
19886
19887 DEC Ada provides the implementation-defined pragma TIME_SLICE,
19888 which can be used to enable or disable round-robin
19889 scheduling of tasks with the same priority.
19890 See the relevant DEC Ada run-time reference manual for
19891 information on using the pragmas to control DEC Ada task
19892 scheduling.
19893
19894 GNAT follows the scheduling rules of Annex D (real-time
19895 Annex) of the Ada 95 Reference Manual. In general, this
19896 scheduling strategy is fully compatible with DEC Ada
19897 although it provides some additional constraints (as
19898 fully documented in Annex D).
19899 GNAT implements time slicing control in a manner compatible with
19900 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
19901 to the DEC Ada 83 pragma of the same name.
19902 Note that it is not possible to mix GNAT tasking and
19903 DEC Ada 83 tasking in the same program, since the two run times are
19904 not compatible.
19905
19906 @node The Task Stack
19907 @subsection The Task Stack
19908
19909 @noindent
19910 In DEC Ada, a task stack is allocated each time a
19911 non passive task is activated. As soon as the task is
19912 terminated, the storage for the task stack is deallocated.
19913 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
19914 a default stack size is used. Also, regardless of the size
19915 specified, some additional space is allocated for task
19916 management purposes. On OpenVMS Alpha systems, at least
19917 one page is allocated.
19918
19919 GNAT handles task stacks in a similar manner. According to
19920 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
19921 an alternative method for controlling the task stack size.
19922 The specification of the attribute T'STORAGE_SIZE is also
19923 supported in a manner compatible with DEC Ada.
19924
19925 @node External Interrupts
19926 @subsection External Interrupts
19927
19928 @noindent
19929 On DEC Ada, external interrupts can be associated with task entries.
19930 GNAT is compatible with DEC Ada in its handling of external interrupts.
19931
19932 @node Pragmas and Pragma-Related Features
19933 @section Pragmas and Pragma-Related Features
19934
19935 @noindent
19936 Both DEC Ada and GNAT supply all language-defined pragmas
19937 as specified by the Ada 83 standard. GNAT also supplies all
19938 language-defined pragmas specified in the Ada 95 Reference Manual.
19939 In addition, GNAT implements the implementation-defined pragmas
19940 from DEC Ada 83.
19941
19942 @itemize @bullet
19943 @item  AST_ENTRY
19944
19945 @item  COMMON_OBJECT
19946
19947 @item  COMPONENT_ALIGNMENT
19948
19949 @item  EXPORT_EXCEPTION
19950
19951 @item  EXPORT_FUNCTION
19952
19953 @item  EXPORT_OBJECT
19954
19955 @item  EXPORT_PROCEDURE
19956
19957 @item  EXPORT_VALUED_PROCEDURE
19958
19959 @item  FLOAT_REPRESENTATION
19960
19961 @item  IDENT
19962
19963 @item  IMPORT_EXCEPTION
19964
19965 @item  IMPORT_FUNCTION
19966
19967 @item  IMPORT_OBJECT
19968
19969 @item  IMPORT_PROCEDURE
19970
19971 @item  IMPORT_VALUED_PROCEDURE
19972
19973 @item  INLINE_GENERIC
19974
19975 @item  INTERFACE_NAME
19976
19977 @item  LONG_FLOAT
19978
19979 @item  MAIN_STORAGE
19980
19981 @item  PASSIVE
19982
19983 @item  PSET_OBJECT
19984
19985 @item  SHARE_GENERIC
19986
19987 @item  SUPPRESS_ALL
19988
19989 @item  TASK_STORAGE
19990
19991 @item  TIME_SLICE
19992
19993 @item  TITLE
19994 @end itemize
19995
19996 @noindent
19997 These pragmas are all fully implemented, with the exception of @code{Title},
19998 @code{Passive}, and @code{Share_Generic}, which are
19999 recognized, but which have no
20000 effect in GNAT. The effect of @code{Passive} may be obtained by the
20001 use of protected objects in Ada 95. In GNAT, all generics are inlined.
20002
20003 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
20004 a separate subprogram specification which must appear before the
20005 subprogram body.
20006
20007 GNAT also supplies a number of implementation-defined pragmas as follows:
20008 @itemize @bullet
20009 @item  C_PASS_BY_COPY
20010
20011 @item  EXTEND_SYSTEM
20012
20013 @item  SOURCE_FILE_NAME
20014
20015 @item  UNSUPPRESS
20016
20017 @item  WARNINGS
20018
20019 @item  ABORT_DEFER
20020
20021 @item  ADA_83
20022
20023 @item  ADA_95
20024
20025 @item  ANNOTATE
20026
20027 @item  ASSERT
20028
20029 @item  CPP_CLASS
20030
20031 @item  CPP_CONSTRUCTOR
20032
20033 @item  CPP_DESTRUCTOR
20034
20035 @item  CPP_VIRTUAL
20036
20037 @item  CP_VTABLE
20038
20039 @item  DEBUG
20040
20041 @item  LINKER_ALIAS
20042
20043 @item  LINKER_SECTION
20044
20045 @item  MACHINE_ATTRIBUTE
20046
20047 @item  NO_RETURN
20048
20049 @item  PURE_FUNCTION
20050
20051 @item  SOURCE_REFERENCE
20052
20053 @item  TASK_INFO
20054
20055 @item  UNCHECKED_UNION
20056
20057 @item  UNIMPLEMENTED_UNIT
20058
20059 @item  UNIVERSAL_DATA
20060
20061 @item  WEAK_EXTERNAL
20062 @end itemize
20063
20064 @noindent
20065 For full details on these GNAT implementation-defined pragmas, see
20066 the GNAT Reference Manual.
20067
20068 @menu
20069 * Restrictions on the Pragma INLINE::
20070 * Restrictions on the Pragma INTERFACE::
20071 * Restrictions on the Pragma SYSTEM_NAME::
20072 @end menu
20073
20074 @node Restrictions on the Pragma INLINE
20075 @subsection Restrictions on the Pragma INLINE
20076
20077 @noindent
20078 DEC Ada applies the following restrictions to the pragma INLINE:
20079 @itemize @bullet
20080 @item  Parameters cannot be a task type.
20081
20082 @item  Function results cannot be task types, unconstrained
20083 array types, or unconstrained types with discriminants.
20084
20085 @item  Bodies cannot declare the following:
20086 @itemize @bullet
20087 @item  Subprogram body or stub (imported subprogram is allowed)
20088
20089 @item  Tasks
20090
20091 @item  Generic declarations
20092
20093 @item  Instantiations
20094
20095 @item  Exceptions
20096
20097 @item  Access types (types derived from access types allowed)
20098
20099 @item  Array or record types
20100
20101 @item  Dependent tasks
20102
20103 @item  Direct recursive calls of subprogram or containing
20104 subprogram, directly or via a renaming
20105
20106 @end itemize
20107 @end itemize
20108
20109 @noindent
20110 In GNAT, the only restriction on pragma INLINE is that the
20111 body must occur before the call if both are in the same
20112 unit, and the size must be appropriately small. There are
20113 no other specific restrictions which cause subprograms to
20114 be incapable of being inlined.
20115
20116 @node  Restrictions on the Pragma INTERFACE
20117 @subsection  Restrictions on the Pragma INTERFACE
20118
20119 @noindent
20120 The following lists and describes the restrictions on the
20121 pragma INTERFACE on DEC Ada and GNAT:
20122 @itemize @bullet
20123 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
20124 Default is the default on OpenVMS Alpha systems.
20125
20126 @item  Parameter passing: Language specifies default
20127 mechanisms but can be overridden with an EXPORT pragma.
20128
20129 @itemize @bullet
20130 @item  Ada: Use internal Ada rules.
20131
20132 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
20133 record or task type. Result cannot be a string, an
20134 array, or a record.
20135
20136 @item  Fortran: Parameters cannot be a task. Result cannot
20137 be a string, an array, or a record.
20138 @end itemize
20139 @end itemize
20140
20141 @noindent
20142 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
20143 record parameters for all languages.
20144
20145 @node  Restrictions on the Pragma SYSTEM_NAME
20146 @subsection  Restrictions on the Pragma SYSTEM_NAME
20147
20148 @noindent
20149 For DEC Ada for OpenVMS Alpha, the enumeration literal
20150 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
20151 literal for the type NAME is SYSTEM_NAME_GNAT.
20152
20153 @node  Library of Predefined Units
20154 @section  Library of Predefined Units
20155
20156 @noindent
20157 A library of predefined units is provided as part of the
20158 DEC Ada and GNAT implementations. DEC Ada does not provide
20159 the package MACHINE_CODE but instead recommends importing
20160 assembler code.
20161
20162 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
20163 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20164 version. During GNAT installation, the DEC Ada Predefined
20165 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
20166 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
20167 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
20168 for details.
20169
20170 The GNAT RTL is contained in
20171 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
20172 the default search path is set up to find DECLIB units in preference
20173 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
20174 for example).
20175
20176 However, it is possible to change the default so that the
20177 reverse is true, or even to mix them using child package
20178 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
20179 is the package name, and the Ada units are available in the
20180 standard manner defined for Ada 95, that is to say as Ada.xxx. To
20181 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
20182 appropriately. For example, to change the default to use the Ada95
20183 versions do:
20184
20185 @smallexample
20186 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
20187                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20188 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
20189                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20190 @end smallexample
20191
20192 @menu
20193 * Changes to DECLIB::
20194 @end menu
20195
20196 @node Changes to DECLIB
20197 @subsection Changes to DECLIB
20198
20199 @noindent
20200 The changes made to the DEC Ada predefined library for GNAT and Ada 95
20201 compatibility are minor and include the following:
20202
20203 @itemize @bullet
20204 @item  Adjusting the location of pragmas and record representation
20205 clauses to obey Ada 95 rules
20206
20207 @item  Adding the proper notation to generic formal parameters
20208 that take unconstrained types in instantiation
20209
20210 @item  Adding pragma ELABORATE_BODY to package specifications
20211 that have package bodies not otherwise allowed
20212
20213 @item  Occurrences of the identifier @code{"PROTECTED"} are renamed to
20214 @code{"PROTECTD"}.
20215 Currently these are found only in the STARLET package spec.
20216 @end itemize
20217
20218 @noindent
20219 None of the above changes is visible to users.
20220
20221 @node Bindings
20222 @section Bindings
20223
20224 @noindent
20225 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
20226 @itemize @bullet
20227
20228 @item  Command Language Interpreter (CLI interface)
20229
20230 @item  DECtalk Run-Time Library (DTK interface)
20231
20232 @item  Librarian utility routines (LBR interface)
20233
20234 @item  General Purpose Run-Time Library (LIB interface)
20235
20236 @item  Math Run-Time Library (MTH interface)
20237
20238 @item  National Character Set Run-Time Library (NCS interface)
20239
20240 @item  Compiled Code Support Run-Time Library (OTS interface)
20241
20242 @item  Parallel Processing Run-Time Library (PPL interface)
20243
20244 @item  Screen Management Run-Time Library (SMG interface)
20245
20246 @item  Sort Run-Time Library (SOR interface)
20247
20248 @item  String Run-Time Library (STR interface)
20249
20250 @item STARLET System Library
20251 @findex Starlet
20252
20253 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
20254
20255 @item  X Windows Toolkit (XT interface)
20256
20257 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
20258 @end itemize
20259
20260 @noindent
20261 GNAT provides implementations of these DEC bindings in the DECLIB directory.
20262
20263 The X/Motif bindings used to build DECLIB are whatever versions are in the
20264 DEC Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20265 The build script will
20266 automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt},
20267 and @code{X_Lib}
20268 causing the default X/Motif sharable image libraries to be linked in. This
20269 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20270 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20271
20272 It may be necessary to edit these options files to update or correct the
20273 library names if, for example, the newer X/Motif bindings from
20274 @file{ADA$EXAMPLES}
20275 had been (previous to installing GNAT) copied and renamed to supersede the
20276 default @file{ADA$PREDEFINED} versions.
20277
20278 @menu
20279 * Shared Libraries and Options Files::
20280 * Interfaces to C::
20281 @end menu
20282
20283 @node Shared Libraries and Options Files
20284 @subsection Shared Libraries and Options Files
20285
20286 @noindent
20287 When using the DEC Ada
20288 predefined X and Motif bindings, the linking with their sharable images is
20289 done automatically by @command{GNAT LINK}.
20290 When using other X and Motif bindings, you need
20291 to add the corresponding sharable images to the command line for
20292 @code{GNAT LINK}. When linking with shared libraries, or with
20293 @file{.OPT} files, you must
20294 also add them to the command line for @command{GNAT LINK}.
20295
20296 A shared library to be used with GNAT is built in the same way as other
20297 libraries under VMS. The VMS Link command can be used in standard fashion.
20298
20299 @node Interfaces to C
20300 @subsection Interfaces to C
20301
20302 @noindent
20303 DEC Ada
20304 provides the following Ada types and operations:
20305
20306 @itemize @bullet
20307 @item C types package (C_TYPES)
20308
20309 @item C strings (C_TYPES.NULL_TERMINATED)
20310
20311 @item Other_types (SHORT_INT)
20312 @end itemize
20313
20314 @noindent
20315 Interfacing to C with GNAT, one can use the above approach
20316 described for DEC Ada or the facilities of Annex B of
20317 the Ada 95 Reference Manual (packages INTERFACES.C,
20318 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
20319 information, see the section ``Interfacing to C'' in the
20320 @cite{GNAT Reference Manual}.
20321
20322 The @option{-gnatF} qualifier forces default and explicit
20323 @code{External_Name} parameters in pragmas Import and Export
20324 to be uppercased for compatibility with the default behavior
20325 of Compaq C. The qualifier has no effect on @code{Link_Name} parameters.
20326
20327 @node Main Program Definition
20328 @section Main Program Definition
20329
20330 @noindent
20331 The following section discusses differences in the
20332 definition of main programs on DEC Ada and GNAT.
20333 On DEC Ada, main programs are defined to meet the
20334 following conditions:
20335 @itemize @bullet
20336 @item  Procedure with no formal parameters (returns 0 upon
20337        normal completion)
20338
20339 @item  Procedure with no formal parameters (returns 42 when
20340        unhandled exceptions are raised)
20341
20342 @item  Function with no formal parameters whose returned value
20343        is of a discrete type
20344
20345 @item  Procedure with one OUT formal of a discrete type for
20346        which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
20347
20348 @end itemize
20349
20350 @noindent
20351 When declared with the pragma EXPORT_VALUED_PROCEDURE,
20352 a main function or main procedure returns a discrete
20353 value whose size is less than 64 bits (32 on VAX systems),
20354 the value is zero- or sign-extended as appropriate.
20355 On GNAT, main programs are defined as follows:
20356 @itemize @bullet
20357 @item  Must be a non-generic, parameter-less subprogram that
20358 is either a procedure or function returning an Ada
20359 STANDARD.INTEGER (the predefined type)
20360
20361 @item  Cannot be a generic subprogram or an instantiation of a
20362 generic subprogram
20363 @end itemize
20364
20365 @node Implementation-Defined Attributes
20366 @section Implementation-Defined Attributes
20367
20368 @noindent
20369 GNAT provides all DEC Ada implementation-defined
20370 attributes.
20371
20372 @node Compiler and Run-Time Interfacing
20373 @section Compiler and Run-Time Interfacing
20374
20375 @noindent
20376 DEC Ada provides the following ways to pass options to the linker
20377 (ACS LINK):
20378 @itemize @bullet
20379 @item  /WAIT and /SUBMIT qualifiers
20380
20381 @item  /COMMAND qualifier
20382
20383 @item  /[NO]MAP qualifier
20384
20385 @item  /OUTPUT=file-spec
20386
20387 @item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
20388 @end itemize
20389
20390 @noindent
20391 To pass options to the linker, GNAT provides the following
20392 switches:
20393
20394 @itemize @bullet
20395 @item   @option{/EXECUTABLE=exec-name}
20396
20397 @item   @option{/VERBOSE qualifier}
20398
20399 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers
20400 @end itemize
20401
20402 @noindent
20403 For more information on these switches, see
20404 @ref{Switches for gnatlink}.
20405 In DEC Ada, the command-line switch @option{/OPTIMIZE} is available
20406 to control optimization. DEC Ada also supplies the
20407 following pragmas:
20408 @itemize @bullet
20409 @item  @code{OPTIMIZE}
20410
20411 @item  @code{INLINE}
20412
20413 @item  @code{INLINE_GENERIC}
20414
20415 @item  @code{SUPPRESS_ALL}
20416
20417 @item  @code{PASSIVE}
20418 @end itemize
20419
20420 @noindent
20421 In GNAT, optimization is controlled strictly by command
20422 line parameters, as described in the corresponding section of this guide.
20423 The DIGITAL pragmas for control of optimization are
20424 recognized but ignored.
20425
20426 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
20427 the default is that optimization is turned on.
20428
20429 @node Program Compilation and Library Management
20430 @section Program Compilation and Library Management
20431
20432 @noindent
20433 DEC Ada and GNAT provide a comparable set of commands to
20434 build programs. DEC Ada also provides a program library,
20435 which is a concept that does not exist on GNAT. Instead,
20436 GNAT provides directories of sources that are compiled as
20437 needed.
20438
20439 The following table summarizes
20440 the DEC Ada commands and provides
20441 equivalent GNAT commands. In this table, some GNAT
20442 equivalents reflect the fact that GNAT does not use the
20443 concept of a program library. Instead, it uses a model
20444 in which collections of source and object files are used
20445 in a manner consistent with other languages like C and
20446 Fortran. Therefore, standard system file commands are used
20447 to manipulate these elements. Those GNAT commands are marked with
20448 an asterisk.
20449 Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards.
20450
20451 @need 1500
20452 @multitable @columnfractions .35 .65
20453
20454 @item @emph{DEC Ada Command}
20455 @tab @emph{GNAT Equivalent / Description}
20456
20457 @item @command{ADA}
20458 @tab @command{GNAT COMPILE}@*
20459 Invokes the compiler to compile one or more Ada source files.
20460
20461 @item @command{ACS ATTACH}@*
20462 @tab [No equivalent]@*
20463 Switches control of terminal from current process running the program
20464 library manager.
20465
20466 @item @command{ACS CHECK}
20467 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
20468 Forms the execution closure of one
20469 or more compiled units and checks completeness and currency.
20470
20471 @item @command{ACS COMPILE}
20472 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20473 Forms the execution closure of one or
20474 more specified units, checks completeness and currency,
20475 identifies units that have revised source files, compiles same,
20476 and recompiles units that are or will become obsolete.
20477 Also completes incomplete generic instantiations.
20478
20479 @item @command{ACS COPY FOREIGN}
20480 @tab Copy (*)@*
20481 Copies a foreign object file into the program library as a
20482 library unit body.
20483
20484 @item @command{ACS COPY UNIT}
20485 @tab Copy (*)@*
20486 Copies a compiled unit from one program library to another.
20487
20488 @item @command{ACS CREATE LIBRARY}
20489 @tab Create /directory (*)@*
20490 Creates a program library.
20491
20492 @item @command{ACS CREATE SUBLIBRARY}
20493 @tab Create /directory (*)@*
20494 Creates a program sublibrary.
20495
20496 @item @command{ACS DELETE LIBRARY}
20497 @tab @*
20498 Deletes a program library and its contents.
20499
20500 @item @command{ACS DELETE SUBLIBRARY}
20501 @tab @*
20502 Deletes a program sublibrary and its contents.
20503
20504 @item @command{ACS DELETE UNIT}
20505 @tab Delete file (*)@*
20506 On OpenVMS systems, deletes one or more compiled units from
20507 the current program library.
20508
20509 @item @command{ACS DIRECTORY}
20510 @tab Directory (*)@*
20511 On OpenVMS systems, lists units contained in the current
20512 program library.
20513
20514 @item @command{ACS ENTER FOREIGN}
20515 @tab Copy (*)@*
20516 Allows the import of a foreign body as an Ada library
20517 specification and enters a reference to a pointer.
20518
20519 @item @command{ACS ENTER UNIT}
20520 @tab Copy (*)@*
20521 Enters a reference (pointer) from the current program library to
20522 a unit compiled into another program library.
20523
20524 @item @command{ACS EXIT}
20525 @tab [No equivalent]@*
20526 Exits from the program library manager.
20527
20528 @item @command{ACS EXPORT}
20529 @tab Copy (*)@*
20530 Creates an object file that contains system-specific object code
20531 for one or more units. With GNAT, object files can simply be copied
20532 into the desired directory.
20533
20534 @item @command{ACS EXTRACT SOURCE}
20535 @tab Copy (*)@*
20536 Allows access to the copied source file for each Ada compilation unit
20537
20538 @item @command{ACS HELP}
20539 @tab @command{HELP GNAT}@*
20540 Provides online help.
20541
20542 @item @command{ACS LINK}
20543 @tab @command{GNAT LINK}@*
20544 Links an object file containing Ada units into an executable file.
20545
20546 @item @command{ACS LOAD}
20547 @tab Copy (*)@*
20548 Loads (partially compiles) Ada units into the program library.
20549 Allows loading a program from a collection of files into a library
20550 without knowing the relationship among units.
20551
20552 @item @command{ACS MERGE}
20553 @tab Copy (*)@*
20554 Merges into the current program library, one or more units from
20555 another library where they were modified.
20556
20557 @item @command{ACS RECOMPILE}
20558 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20559 Recompiles from   external or copied source files any obsolete
20560 unit in the closure. Also, completes any incomplete generic
20561 instantiations.
20562
20563 @item @command{ACS REENTER}
20564 @tab @command{GNAT MAKE}@*
20565 Reenters current references to units compiled after last entered
20566 with the @command{ACS ENTER UNIT} command.
20567
20568 @item @command{ACS SET LIBRARY}
20569 @tab Set default (*)@*
20570 Defines a program library to be the compilation context as well
20571 as the target library for compiler output and commands in general.
20572
20573 @item @command{ACS SET PRAGMA}
20574 @tab Edit @file{gnat.adc} (*)@*
20575 Redefines specified  values of the library characteristics
20576 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
20577 and @code{Float_Representation}.
20578
20579 @item @command{ACS SET SOURCE}
20580 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
20581 Defines the source file search list for the @command{ACS COMPILE} command.
20582
20583 @item @command{ACS SHOW LIBRARY}
20584 @tab Directory (*)@*
20585 Lists information about one or more program libraries.
20586
20587 @item @command{ACS SHOW PROGRAM}
20588 @tab [No equivalent]@*
20589 Lists information about the execution closure of one or
20590 more units in the program library.
20591
20592 @item @command{ACS SHOW SOURCE}
20593 @tab Show logical @code{ADA_INCLUDE_PATH}@*
20594 Shows the source file search used when compiling units.
20595
20596 @item @command{ACS SHOW VERSION}
20597 @tab Compile with @option{VERBOSE} option
20598 Displays the version number of the compiler and program library
20599 manager used.
20600
20601 @item @command{ACS SPAWN}
20602 @tab [No equivalent]@*
20603 Creates a subprocess of the current process (same as @command{DCL SPAWN}
20604 command).
20605
20606 @item @command{ACS VERIFY}
20607 @tab [No equivalent]@*
20608 Performs a series of consistency checks on a program library to
20609 determine whether the library structure and library files are in
20610 valid form.
20611 @end multitable
20612
20613 @noindent
20614
20615 @node Input-Output
20616 @section Input-Output
20617
20618 @noindent
20619 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
20620 Management Services (RMS) to perform operations on
20621 external files.
20622
20623 @noindent
20624 DEC Ada and GNAT predefine an identical set of input-
20625 output packages. To make the use of the
20626 generic TEXT_IO operations more convenient, DEC Ada
20627 provides predefined library packages that instantiate the
20628 integer and floating-point operations for the predefined
20629 integer and floating-point types as shown in the following table.
20630
20631 @multitable @columnfractions .45 .55
20632 @item @emph{Package Name} @tab Instantiation
20633
20634 @item @code{INTEGER_TEXT_IO}
20635 @tab @code{INTEGER_IO(INTEGER)}
20636
20637 @item @code{SHORT_INTEGER_TEXT_IO}
20638 @tab @code{INTEGER_IO(SHORT_INTEGER)}
20639
20640 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
20641 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
20642
20643 @item @code{FLOAT_TEXT_IO}
20644 @tab @code{FLOAT_IO(FLOAT)}
20645
20646 @item @code{LONG_FLOAT_TEXT_IO}
20647 @tab @code{FLOAT_IO(LONG_FLOAT)}
20648 @end multitable
20649
20650 @noindent
20651 The DEC Ada predefined packages and their operations
20652 are implemented using OpenVMS Alpha files and input-
20653 output facilities. DEC Ada supports asynchronous input-
20654 output on OpenVMS Alpha. Familiarity with the following is
20655 recommended:
20656 @itemize @bullet
20657 @item  RMS file organizations and access methods
20658
20659 @item  OpenVMS file specifications and directories
20660
20661 @item  OpenVMS File Definition Language (FDL)
20662 @end itemize
20663
20664 @noindent
20665 GNAT provides I/O facilities that are completely
20666 compatible with DEC Ada. The distribution includes the
20667 standard DEC Ada versions of all I/O packages, operating
20668 in a manner compatible with DEC Ada. In particular, the
20669 following packages are by default the DEC Ada (Ada 83)
20670 versions of these packages rather than the renamings
20671 suggested in annex J of the Ada 95 Reference Manual:
20672 @itemize @bullet
20673 @item  @code{TEXT_IO}
20674
20675 @item  @code{SEQUENTIAL_IO}
20676
20677 @item  @code{DIRECT_IO}
20678 @end itemize
20679
20680 @noindent
20681 The use of the standard Ada 95 syntax for child packages (for
20682 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
20683 packages, as defined in the Ada 95 Reference Manual.
20684 GNAT provides DIGITAL-compatible predefined instantiations
20685 of the @code{TEXT_IO} packages, and also
20686 provides the standard predefined instantiations required
20687 by the Ada 95 Reference Manual.
20688
20689 For further information on how GNAT interfaces to the file
20690 system or how I/O is implemented in programs written in
20691 mixed languages, see the chapter ``Implementation of the
20692 Standard I/O'' in the @cite{GNAT Reference Manual}.
20693 This chapter covers the following:
20694 @itemize @bullet
20695 @item  Standard I/O packages
20696
20697 @item  @code{FORM} strings
20698
20699 @item  @code{ADA.DIRECT_IO}
20700
20701 @item  @code{ADA.SEQUENTIAL_IO}
20702
20703 @item  @code{ADA.TEXT_IO}
20704
20705 @item  Stream pointer positioning
20706
20707 @item  Reading and writing non-regular files
20708
20709 @item  @code{GET_IMMEDIATE}
20710
20711 @item  Treating @code{TEXT_IO} files as streams
20712
20713 @item  Shared files
20714
20715 @item  Open modes
20716 @end itemize
20717
20718 @node Implementation Limits
20719 @section Implementation Limits
20720
20721 @noindent
20722 The following table lists implementation limits for DEC Ada
20723 and GNAT systems.
20724 @multitable @columnfractions .60 .20 .20
20725 @sp 1
20726 @item  @emph{Compilation Parameter}
20727 @tab   @emph{DEC Ada}
20728 @tab   @emph{GNAT}
20729 @sp 1
20730
20731 @item  In a subprogram or entry  declaration, maximum number of
20732        formal parameters that are of an unconstrained record type
20733 @tab   32
20734 @tab   No set limit
20735 @sp 1
20736
20737 @item  Maximum identifier length (number of characters)
20738 @tab   255
20739 @tab   255
20740 @sp 1
20741
20742 @item  Maximum number of characters in a source line
20743 @tab   255
20744 @tab   255
20745 @sp 1
20746
20747 @item  Maximum collection size   (number of bytes)
20748 @tab   2**31-1
20749 @tab   2**31-1
20750 @sp 1
20751
20752 @item  Maximum number of discriminants for a record type
20753 @tab   245
20754 @tab   No set limit
20755 @sp 1
20756
20757 @item  Maximum number of formal parameters in an entry or
20758        subprogram declaration
20759 @tab   246
20760 @tab    No set limit
20761 @sp 1
20762
20763 @item  Maximum number of dimensions in an array type
20764 @tab   255
20765 @tab   No set limit
20766 @sp 1
20767
20768 @item  Maximum number of library  units and subunits in a compilation.
20769 @tab   4095
20770 @tab   No set limit
20771 @sp 1
20772
20773 @item  Maximum number of library units and subunits in an execution.
20774 @tab   16383
20775 @tab   No set limit
20776 @sp 1
20777
20778 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
20779        or @code{PSECT_OBJECT}
20780 @tab   32757
20781 @tab   No set limit
20782 @sp 1
20783
20784 @item  Maximum number of enumeration literals in an enumeration type
20785        definition
20786 @tab   65535
20787 @tab   No set limit
20788 @sp 1
20789
20790 @item  Maximum number of lines in a source file
20791 @tab   65534
20792 @tab   No set limit
20793 @sp 1
20794
20795 @item  Maximum number of bits in any object
20796 @tab   2**31-1
20797 @tab   2**31-1
20798 @sp 1
20799
20800 @item  Maximum size of the static portion of a stack frame (approximate)
20801 @tab   2**31-1
20802 @tab   2**31-1
20803 @end multitable
20804
20805 @node  Tools
20806 @section Tools
20807
20808 @end ifset
20809
20810
20811 @c **************************************
20812 @node Platform-Specific Information for the Run-Time Libraries
20813 @appendix Platform-Specific Information for the Run-Time Libraries
20814 @cindex Tasking and threads libraries
20815 @cindex Threads libraries and tasking
20816 @cindex Run-time libraries (platform-specific information)
20817
20818 @noindent
20819 The GNAT run-time implementation
20820 may vary with respect to both the underlying threads library and
20821 the exception handling scheme.
20822 For threads support, one or more of the following are supplied:
20823 @itemize @bullet
20824 @item @b{native threads library}, a binding to the thread package from
20825 the underlying operating system
20826
20827 @item @b{FSU threads library}, a binding to the Florida State University
20828 threads implementation, which complies fully with the requirements of Annex D
20829
20830 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
20831 POSIX thread package
20832 @end itemize
20833
20834 @noindent
20835 For exception handling, either or both of two models are supplied:
20836 @itemize @bullet
20837 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
20838 Most programs should experience a substantial speed improvement by
20839 being compiled with a ZCX run-time.
20840 This is especially true for
20841 tasking applications or applications with many exception handlers.}
20842 @cindex Zero-Cost Exceptions
20843 @cindex ZCX (Zero-Cost Exceptions)
20844 which uses binder-generated tables that
20845 are interrogated at run time to locate a handler
20846
20847 @item @b{setjmp / longjmp} (``SJLJ''),
20848 @cindex setjmp/longjmp Exception Model
20849 @cindex SJLJ (setjmp/longjmp Exception Model)
20850 which uses dynamically-set data to establish
20851 the set of handlers
20852 @end itemize
20853
20854 @noindent
20855 This appendix summarizes which combinations of threads and exception support
20856 are supplied on various GNAT platforms.
20857 It then shows how to select a particular library either
20858 permanently or temporarily,
20859 explains the properties of (and tradeoffs among) the various threads
20860 libraries, and provides some additional
20861 information about several specific platforms.
20862
20863 @menu
20864 * Summary of Run-Time Configurations::
20865 * Specifying a Run-Time Library::
20866 * Choosing between Native and FSU Threads Libraries::
20867 * Choosing the Scheduling Policy::
20868 * Solaris-Specific Considerations::
20869 * IRIX-Specific Considerations::
20870 * Linux-Specific Considerations::
20871 * AIX-Specific Considerations::
20872 @end menu
20873
20874
20875 @node Summary of Run-Time Configurations
20876 @section Summary of Run-Time Configurations
20877
20878
20879 @multitable @columnfractions .30 .70
20880 @item @b{alpha-openvms}
20881 @item @code{@ @ }@i{rts-native (default)}
20882 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
20883 @item @code{@ @ @ @ }Exceptions @tab ZCX
20884 @*
20885 @item @b{pa-hpux}
20886 @item @code{@ @ }@i{rts-native (default)}
20887 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
20888 @item @code{@ @ @ @ }Exceptions @tab ZCX
20889 @*
20890 @item @code{@ @ }@i{rts-sjlj}
20891 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
20892 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20893 @*
20894 @item @b{sparc-solaris}  @tab
20895 @item @code{@ @ }@i{rts-native (default)}
20896 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
20897 @item @code{@ @ @ @ }Exceptions @tab ZCX
20898 @*
20899 @item @code{@ @ }@i{rts-fsu}    @tab
20900 @item @code{@ @ @ @ }Tasking    @tab FSU threads library
20901 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20902 @*
20903 @item @code{@ @ }@i{rts-m64}
20904 @item @code{@ @ @ @ }Tasking     @tab native Solaris threads library
20905 @item @code{@ @ @ @ }Exceptions  @tab ZCX
20906 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
20907 @item    @tab Use only on Solaris 8 or later.
20908 @item    @tab @xref{Building and Debugging 64-bit Applications}, for details.
20909 @*
20910 @item @code{@ @ }@i{rts-pthread}
20911 @item @code{@ @ @ @ }Tasking    @tab pthreads library
20912 @item @code{@ @ @ @ }Exceptions @tab ZCX
20913 @*
20914 @item @code{@ @ }@i{rts-sjlj}
20915 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
20916 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20917 @*
20918 @item @b{x86-linux}
20919 @item @code{@ @ }@i{rts-native (default)}
20920 @item @code{@ @ @ @ }Tasking    @tab LinuxThread library
20921 @item @code{@ @ @ @ }Exceptions @tab ZCX
20922 @*
20923 @item @code{@ @ }@i{rts-fsu}
20924 @item @code{@ @ @ @ }Tasking    @tab FSU threads library
20925 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20926 @*
20927 @item @code{@ @ }@i{rts-sjlj}
20928 @item @code{@ @ @ @ }Tasking    @tab LinuxThread library
20929 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20930 @*
20931 @item @b{x86-windows}
20932 @item @code{@ @ }@i{rts-native (default)}
20933 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
20934 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20935 @*
20936 @end multitable
20937
20938
20939
20940 @node Specifying a Run-Time Library
20941 @section Specifying a Run-Time Library
20942
20943 @noindent
20944 The @file{adainclude} subdirectory containing the sources of the GNAT
20945 run-time library, and the @file{adalib} subdirectory containing the
20946 @file{ALI} files and the static and/or shared GNAT library, are located
20947 in the gcc target-dependent area:
20948
20949 @smallexample
20950 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
20951 @end smallexample
20952
20953 @noindent
20954 As indicated above, on some platforms several run-time libraries are supplied.
20955 These libraries are installed in the target dependent area and
20956 contain a complete source and binary subdirectory. The detailed description
20957 below explains the differences between the different libraries in terms of
20958 their thread support.
20959
20960 The default run-time library (when GNAT is installed) is @emph{rts-native}.
20961 This default run time is selected by the means of soft links.
20962 For example on x86-linux:
20963
20964 @smallexample
20965 @group
20966  $(target-dir)
20967      |
20968      +--- adainclude----------+
20969      |                        |
20970      +--- adalib-----------+  |
20971      |                     |  |
20972      +--- rts-native       |  |
20973      |    |                |  |
20974      |    +--- adainclude <---+
20975      |    |                |
20976      |    +--- adalib <----+
20977      |
20978      +--- rts-fsu
20979      |    |
20980      |    +--- adainclude
20981      |    |
20982      |    +--- adalib
20983      |
20984      +--- rts-sjlj
20985           |
20986           +--- adainclude
20987           |
20988           +--- adalib
20989 @end group
20990 @end smallexample
20991
20992 @noindent
20993 If the @i{rts-fsu} library is to be selected on a permanent basis,
20994 these soft links can be modified with the following commands:
20995
20996 @smallexample
20997 $ cd $target
20998 $ rm -f adainclude adalib
20999 $ ln -s rts-fsu/adainclude adainclude
21000 $ ln -s rts-fsu/adalib adalib
21001 @end smallexample
21002
21003 @noindent
21004 Alternatively, you can specify @file{rts-fsu/adainclude} in the file
21005 @file{$target/ada_source_path} and @file{rts-fsu/adalib} in
21006 @file{$target/ada_object_path}.
21007
21008 Selecting another run-time library temporarily can be
21009 achieved by the regular mechanism for GNAT object or source path selection:
21010
21011 @itemize @bullet
21012 @item
21013 Set the environment variables:
21014
21015 @smallexample
21016 $ ADA_INCLUDE_PATH=$target/rts-fsu/adainclude:$ADA_INCLUDE_PATH
21017 $ ADA_OBJECTS_PATH=$target/rts-fsu/adalib:$ADA_OBJECTS_PATH
21018 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
21019 @end smallexample
21020
21021 @item
21022 Use @option{-aI$target/rts-fsu/adainclude}
21023 and @option{-aO$target/rts-fsu/adalib}
21024 on the @command{gnatmake} command line
21025
21026 @item
21027 Use the switch @option{--RTS}; e.g., @option{--RTS=fsu}
21028 @cindex @option{--RTS} option
21029 @end itemize
21030
21031 @noindent
21032 You can similarly switch to @emph{rts-sjlj}.
21033
21034 @node Choosing between Native and FSU Threads Libraries
21035 @section Choosing between Native and FSU Threads Libraries
21036 @cindex Native threads library
21037 @cindex FSU threads library
21038
21039 @noindent
21040 Some GNAT implementations offer a choice between
21041 native threads and FSU threads.
21042
21043 @itemize @bullet
21044 @item
21045 The @emph{native threads} library correspond to the standard system threads
21046 implementation (e.g. LinuxThreads on GNU/Linux,
21047 @cindex LinuxThreads library
21048 POSIX threads on AIX, or
21049 Solaris threads on Solaris). When this option is chosen, GNAT provides
21050 a full and accurate implementation of the core language tasking model
21051 as described in Chapter 9 of the Ada Reference Manual,
21052 but might not (and probably does not) implement
21053 the exact semantics as specified in @w{Annex D} (the Real-Time Systems Annex).
21054 @cindex Annex D (Real-Time Systems Annex) compliance
21055 @cindex Real-Time Systems Annex compliance
21056 Indeed, the reason that a choice of libraries is offered
21057 on a given target is because some of the
21058 ACATS tests for @w{Annex D} fail using the native threads library.
21059 As far as possible, this library is implemented
21060 in accordance with Ada semantics (e.g., modifying priorities as required
21061 to simulate ceiling locking),
21062 but there are often slight inaccuracies, most often in the area of
21063 absolutely respecting the priority rules on a single
21064 processor.
21065 Moreover, it is not possible in general to define the exact behavior,
21066 because the native threads implementations
21067 are not well enough documented.
21068
21069 On systems where the @code{SCHED_FIFO} POSIX scheduling policy is supported,
21070 @cindex POSIX scheduling policies
21071 @cindex @code{SCHED_FIFO} scheduling policy
21072 native threads will provide a behavior very close to the @w{Annex D}
21073 requirements (i.e., a run-till-blocked scheduler with fixed priorities), but
21074 on some systems (in particular GNU/Linux and Solaris), you need to have root
21075 privileges to use the @code{SCHED_FIFO} policy.
21076
21077 @item
21078 The @emph{FSU threads} library provides a completely accurate implementation
21079 of @w{Annex D}.
21080 Thus, operating with this library, GNAT is 100% compliant with both the core
21081 and all @w{Annex D}
21082 requirements.
21083 The formal validations for implementations offering
21084 a choice of threads packages are always carried out using the FSU
21085 threads option.
21086 @end itemize
21087
21088 @noindent
21089 From these considerations, it might seem that FSU threads are the
21090 better choice,
21091 but that is by no means always the case. The FSU threads package
21092 operates with all Ada tasks appearing to the system to be a single
21093 thread. This is often considerably more efficient than operating
21094 with separate threads, since for example, switching between tasks
21095 can be accomplished without the (in some cases considerable)
21096 overhead of a context switch between two system threads. However,
21097 it means that you may well lose concurrency at the system
21098 level. Notably, some system operations (such as I/O) may block all
21099 tasks in a program and not just the calling task. More
21100 significantly, the FSU threads approach likely means you cannot
21101 take advantage of multiple processors, since for this you need
21102 separate threads (or even separate processes) to operate on
21103 different processors.
21104
21105 For most programs, the native threads library is
21106 usually the better choice. Use the FSU threads if absolute
21107 conformance to @w{Annex D} is important for your application, or if
21108 you find that the improved efficiency of FSU threads is significant to you.
21109
21110 Note also that to take full advantage of Florist and Glade, it is highly
21111 recommended that you use native threads.
21112
21113
21114 @node Choosing the Scheduling Policy
21115 @section Choosing the Scheduling Policy
21116
21117 @noindent
21118 When using a POSIX threads implementation, you have a choice of several
21119 scheduling policies: @code{SCHED_FIFO},
21120 @cindex @code{SCHED_FIFO} scheduling policy
21121 @code{SCHED_RR}
21122 @cindex @code{SCHED_RR} scheduling policy
21123 and @code{SCHED_OTHER}.
21124 @cindex @code{SCHED_OTHER} scheduling policy
21125 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21126 or @code{SCHED_RR} requires special (e.g., root) privileges.
21127
21128 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21129 @code{SCHED_FIFO},
21130 @cindex @code{SCHED_FIFO} scheduling policy
21131 you can use one of the following:
21132
21133 @itemize @bullet
21134 @item
21135 @code{pragma Time_Slice (0.0)}
21136 @cindex pragma Time_Slice
21137 @item
21138 the corresponding binder option @option{-T0}
21139 @cindex @option{-T0} option
21140 @item
21141 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21142 @cindex pragma Task_Dispatching_Policy
21143 @end itemize
21144
21145 @noindent
21146 To specify @code{SCHED_RR},
21147 @cindex @code{SCHED_RR} scheduling policy
21148 you should use @code{pragma Time_Slice} with a
21149 value greater than @code{0.0}, or else use the corresponding @option{-T}
21150 binder option.
21151
21152
21153
21154 @node Solaris-Specific Considerations
21155 @section Solaris-Specific Considerations
21156 @cindex Solaris Sparc threads libraries
21157
21158 @noindent
21159 This section addresses some topics related to the various threads libraries
21160 on Sparc Solaris and then provides some information on building and
21161 debugging 64-bit applications.
21162
21163 @menu
21164 * Solaris Threads Issues::
21165 * Building and Debugging 64-bit Applications::
21166 @end menu
21167
21168
21169 @node Solaris Threads Issues
21170 @subsection Solaris Threads Issues
21171
21172 @noindent
21173 Starting with version 3.14, GNAT under Solaris comes with a new tasking
21174 run-time library based on POSIX threads --- @emph{rts-pthread}.
21175 @cindex rts-pthread threads library
21176 This run-time library has the advantage of being mostly shared across all
21177 POSIX-compliant thread implementations, and it also provides under
21178 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21179 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21180 and @code{PTHREAD_PRIO_PROTECT}
21181 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21182 semantics that can be selected using the predefined pragma
21183 @code{Locking_Policy}
21184 @cindex pragma Locking_Policy (under rts-pthread)
21185 with respectively
21186 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21187 @cindex @code{Inheritance_Locking} (under rts-pthread)
21188 @cindex @code{Ceiling_Locking} (under rts-pthread)
21189
21190 As explained above, the native run-time library is based on the Solaris thread
21191 library (@code{libthread}) and is the default library.
21192 The FSU run-time library is based on the FSU threads.
21193 @cindex FSU threads library
21194
21195 Starting with Solaris 2.5.1, when the Solaris threads library is used
21196 (this is the default), programs
21197 compiled with GNAT can automatically take advantage of
21198 and can thus execute on multiple processors.
21199 The user can alternatively specify a processor on which the program should run
21200 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21201 is made by
21202 setting the environment variable @code{GNAT_PROCESSOR}
21203 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21204 to one of the following:
21205
21206 @table @code
21207 @item -2
21208 Use the default configuration (run the program on all
21209          available processors) - this is the same as having
21210          @code{GNAT_PROCESSOR} unset
21211
21212 @item -1
21213 Let the run-time implementation choose one processor and run the program on
21214          that processor
21215
21216 @item 0 .. Last_Proc
21217 Run the program on the specified processor.
21218   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21219 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21220 @end table
21221
21222
21223 @node Building and Debugging 64-bit Applications
21224 @subsection Building and Debugging 64-bit Applications
21225
21226 @noindent
21227 In a 64-bit application, all the sources involved must be compiled with the
21228 @option{-m64} command-line option, and a specific GNAT library (compiled with
21229 this option) is required.
21230 The easiest way to build a 64bit application is to add
21231 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
21232
21233 To debug these applications, dwarf-2 debug information is required, so you
21234 have to add @option{-gdwarf-2} to your gnatmake arguments.
21235 In addition, a special
21236 version of gdb, called @command{gdb64}, needs to be used.
21237
21238 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
21239 amounts to:
21240
21241 @smallexample
21242      $ gnatmake -m64 -gdwarf-2 --RTS=m64 hello.adb
21243      $ gdb64 hello
21244 @end smallexample
21245
21246
21247
21248 @node IRIX-Specific Considerations
21249 @section IRIX-Specific Considerations
21250 @cindex IRIX thread library
21251
21252 @noindent
21253 On SGI IRIX, the thread library depends on which compiler is used.
21254 The @emph{o32 ABI} compiler comes with a run-time library based on the
21255 user-level @code{athread}
21256 library. Thus kernel-level capabilities such as nonblocking system
21257 calls or time slicing can only be achieved reliably by specifying different
21258 @code{sprocs} via the pragma @code{Task_Info}
21259 @cindex pragma Task_Info (and IRIX threads)
21260 and the
21261 @code{System.Task_Info} package.
21262 @cindex @code{System.Task_Info} package (and IRIX threads)
21263 See the @cite{GNAT Reference Manual} for further information.
21264
21265 The @emph{n32 ABI} compiler comes with a run-time library based on the
21266 kernel POSIX threads and thus does not have the limitations mentioned above.
21267
21268
21269 @node Linux-Specific Considerations
21270 @section Linux-Specific Considerations
21271 @cindex Linux threads libraries
21272
21273 @noindent
21274 The default thread library under GNU/Linux has the following disadvantages
21275 compared to other native thread libraries:
21276
21277 @itemize @bullet
21278 @item The size of the task's stack is limited to 2 megabytes.
21279 @item  The signal model is not POSIX compliant, which means that to send a
21280   signal to the process, you need to send the signal to all threads,
21281   e.g. by using @code{killpg()}.
21282 @end itemize
21283
21284 @node AIX-Specific Considerations
21285 @section AIX-Specific Considerations
21286 @cindex AIX resolver library
21287
21288 @noindent
21289 On AIX, the resolver library initializes some internal structure on
21290 the first call to @code{get*by*} functions, which are used to implement
21291 @code{GNAT.Sockets.Get_Host_By_Name} and @code{GNAT.Sockets.Get_Host_By_Addrss}.
21292 If such initialization occurs within an Ada task, and the stack size for
21293 the task is the default size, a stack overflow may occur.
21294
21295 To avoid this overflow, the user should either ensure that the first call
21296 to @code{GNAT.Sockets.Get_Host_By_Name} or @code{GNAT.Sockets.Get_Host_By_Addrss}
21297 occurs in the environment task, or use @code{pragma Storage_Size} to
21298 specify a sufficiently large size for the stack of the task that contains
21299 this call.
21300
21301 @c *******************************
21302 @node Example of Binder Output File
21303 @appendix Example of Binder Output File
21304
21305 @noindent
21306 This Appendix displays the source code for @command{gnatbind}'s output
21307 file generated for a simple ``Hello World'' program.
21308 Comments have been added for clarification purposes.
21309
21310
21311 @smallexample @c adanocomment
21312 @iftex
21313 @leftskip=0cm
21314 @end iftex
21315 --  The package is called Ada_Main unless this name is actually used
21316 --  as a unit name in the partition, in which case some other unique
21317 --  name is used.
21318
21319 with System;
21320 package ada_main is
21321
21322    Elab_Final_Code : Integer;
21323    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
21324
21325    --  The main program saves the parameters (argument count,
21326    --  argument values, environment pointer) in global variables
21327    --  for later access by other units including
21328    --  Ada.Command_Line.
21329
21330    gnat_argc : Integer;
21331    gnat_argv : System.Address;
21332    gnat_envp : System.Address;
21333
21334    --  The actual variables are stored in a library routine. This
21335    --  is useful for some shared library situations, where there
21336    --  are problems if variables are not in the library.
21337
21338    pragma Import (C, gnat_argc);
21339    pragma Import (C, gnat_argv);
21340    pragma Import (C, gnat_envp);
21341
21342    --  The exit status is similarly an external location
21343
21344    gnat_exit_status : Integer;
21345    pragma Import (C, gnat_exit_status);
21346
21347    GNAT_Version : constant String :=
21348                     "GNAT Version: 3.15w (20010315)";
21349    pragma Export (C, GNAT_Version, "__gnat_version");
21350
21351    --  This is the generated adafinal routine that performs
21352    --  finalization at the end of execution. In the case where
21353    --  Ada is the main program, this main program makes a call
21354    --  to adafinal at program termination.
21355
21356    procedure adafinal;
21357    pragma Export (C, adafinal, "adafinal");
21358
21359    --  This is the generated adainit routine that performs
21360    --  initialization at the start of execution. In the case
21361    --  where Ada is the main program, this main program makes
21362    --  a call to adainit at program startup.
21363
21364    procedure adainit;
21365    pragma Export (C, adainit, "adainit");
21366
21367    --  This routine is called at the start of execution. It is
21368    --  a dummy routine that is used by the debugger to breakpoint
21369    --  at the start of execution.
21370
21371    procedure Break_Start;
21372    pragma Import (C, Break_Start, "__gnat_break_start");
21373
21374    --  This is the actual generated main program (it would be
21375    --  suppressed if the no main program switch were used). As
21376    --  required by standard system conventions, this program has
21377    --  the external name main.
21378
21379    function main
21380      (argc : Integer;
21381       argv : System.Address;
21382       envp : System.Address)
21383       return Integer;
21384    pragma Export (C, main, "main");
21385
21386    --  The following set of constants give the version
21387    --  identification values for every unit in the bound
21388    --  partition. This identification is computed from all
21389    --  dependent semantic units, and corresponds to the
21390    --  string that would be returned by use of the
21391    --  Body_Version or Version attributes.
21392
21393    type Version_32 is mod 2 ** 32;
21394    u00001 : constant Version_32 := 16#7880BEB3#;
21395    u00002 : constant Version_32 := 16#0D24CBD0#;
21396    u00003 : constant Version_32 := 16#3283DBEB#;
21397    u00004 : constant Version_32 := 16#2359F9ED#;
21398    u00005 : constant Version_32 := 16#664FB847#;
21399    u00006 : constant Version_32 := 16#68E803DF#;
21400    u00007 : constant Version_32 := 16#5572E604#;
21401    u00008 : constant Version_32 := 16#46B173D8#;
21402    u00009 : constant Version_32 := 16#156A40CF#;
21403    u00010 : constant Version_32 := 16#033DABE0#;
21404    u00011 : constant Version_32 := 16#6AB38FEA#;
21405    u00012 : constant Version_32 := 16#22B6217D#;
21406    u00013 : constant Version_32 := 16#68A22947#;
21407    u00014 : constant Version_32 := 16#18CC4A56#;
21408    u00015 : constant Version_32 := 16#08258E1B#;
21409    u00016 : constant Version_32 := 16#367D5222#;
21410    u00017 : constant Version_32 := 16#20C9ECA4#;
21411    u00018 : constant Version_32 := 16#50D32CB6#;
21412    u00019 : constant Version_32 := 16#39A8BB77#;
21413    u00020 : constant Version_32 := 16#5CF8FA2B#;
21414    u00021 : constant Version_32 := 16#2F1EB794#;
21415    u00022 : constant Version_32 := 16#31AB6444#;
21416    u00023 : constant Version_32 := 16#1574B6E9#;
21417    u00024 : constant Version_32 := 16#5109C189#;
21418    u00025 : constant Version_32 := 16#56D770CD#;
21419    u00026 : constant Version_32 := 16#02F9DE3D#;
21420    u00027 : constant Version_32 := 16#08AB6B2C#;
21421    u00028 : constant Version_32 := 16#3FA37670#;
21422    u00029 : constant Version_32 := 16#476457A0#;
21423    u00030 : constant Version_32 := 16#731E1B6E#;
21424    u00031 : constant Version_32 := 16#23C2E789#;
21425    u00032 : constant Version_32 := 16#0F1BD6A1#;
21426    u00033 : constant Version_32 := 16#7C25DE96#;
21427    u00034 : constant Version_32 := 16#39ADFFA2#;
21428    u00035 : constant Version_32 := 16#571DE3E7#;
21429    u00036 : constant Version_32 := 16#5EB646AB#;
21430    u00037 : constant Version_32 := 16#4249379B#;
21431    u00038 : constant Version_32 := 16#0357E00A#;
21432    u00039 : constant Version_32 := 16#3784FB72#;
21433    u00040 : constant Version_32 := 16#2E723019#;
21434    u00041 : constant Version_32 := 16#623358EA#;
21435    u00042 : constant Version_32 := 16#107F9465#;
21436    u00043 : constant Version_32 := 16#6843F68A#;
21437    u00044 : constant Version_32 := 16#63305874#;
21438    u00045 : constant Version_32 := 16#31E56CE1#;
21439    u00046 : constant Version_32 := 16#02917970#;
21440    u00047 : constant Version_32 := 16#6CCBA70E#;
21441    u00048 : constant Version_32 := 16#41CD4204#;
21442    u00049 : constant Version_32 := 16#572E3F58#;
21443    u00050 : constant Version_32 := 16#20729FF5#;
21444    u00051 : constant Version_32 := 16#1D4F93E8#;
21445    u00052 : constant Version_32 := 16#30B2EC3D#;
21446    u00053 : constant Version_32 := 16#34054F96#;
21447    u00054 : constant Version_32 := 16#5A199860#;
21448    u00055 : constant Version_32 := 16#0E7F912B#;
21449    u00056 : constant Version_32 := 16#5760634A#;
21450    u00057 : constant Version_32 := 16#5D851835#;
21451
21452    --  The following Export pragmas export the version numbers
21453    --  with symbolic names ending in B (for body) or S
21454    --  (for spec) so that they can be located in a link. The
21455    --  information provided here is sufficient to track down
21456    --  the exact versions of units used in a given build.
21457
21458    pragma Export (C, u00001, "helloB");
21459    pragma Export (C, u00002, "system__standard_libraryB");
21460    pragma Export (C, u00003, "system__standard_libraryS");
21461    pragma Export (C, u00004, "adaS");
21462    pragma Export (C, u00005, "ada__text_ioB");
21463    pragma Export (C, u00006, "ada__text_ioS");
21464    pragma Export (C, u00007, "ada__exceptionsB");
21465    pragma Export (C, u00008, "ada__exceptionsS");
21466    pragma Export (C, u00009, "gnatS");
21467    pragma Export (C, u00010, "gnat__heap_sort_aB");
21468    pragma Export (C, u00011, "gnat__heap_sort_aS");
21469    pragma Export (C, u00012, "systemS");
21470    pragma Export (C, u00013, "system__exception_tableB");
21471    pragma Export (C, u00014, "system__exception_tableS");
21472    pragma Export (C, u00015, "gnat__htableB");
21473    pragma Export (C, u00016, "gnat__htableS");
21474    pragma Export (C, u00017, "system__exceptionsS");
21475    pragma Export (C, u00018, "system__machine_state_operationsB");
21476    pragma Export (C, u00019, "system__machine_state_operationsS");
21477    pragma Export (C, u00020, "system__machine_codeS");
21478    pragma Export (C, u00021, "system__storage_elementsB");
21479    pragma Export (C, u00022, "system__storage_elementsS");
21480    pragma Export (C, u00023, "system__secondary_stackB");
21481    pragma Export (C, u00024, "system__secondary_stackS");
21482    pragma Export (C, u00025, "system__parametersB");
21483    pragma Export (C, u00026, "system__parametersS");
21484    pragma Export (C, u00027, "system__soft_linksB");
21485    pragma Export (C, u00028, "system__soft_linksS");
21486    pragma Export (C, u00029, "system__stack_checkingB");
21487    pragma Export (C, u00030, "system__stack_checkingS");
21488    pragma Export (C, u00031, "system__tracebackB");
21489    pragma Export (C, u00032, "system__tracebackS");
21490    pragma Export (C, u00033, "ada__streamsS");
21491    pragma Export (C, u00034, "ada__tagsB");
21492    pragma Export (C, u00035, "ada__tagsS");
21493    pragma Export (C, u00036, "system__string_opsB");
21494    pragma Export (C, u00037, "system__string_opsS");
21495    pragma Export (C, u00038, "interfacesS");
21496    pragma Export (C, u00039, "interfaces__c_streamsB");
21497    pragma Export (C, u00040, "interfaces__c_streamsS");
21498    pragma Export (C, u00041, "system__file_ioB");
21499    pragma Export (C, u00042, "system__file_ioS");
21500    pragma Export (C, u00043, "ada__finalizationB");
21501    pragma Export (C, u00044, "ada__finalizationS");
21502    pragma Export (C, u00045, "system__finalization_rootB");
21503    pragma Export (C, u00046, "system__finalization_rootS");
21504    pragma Export (C, u00047, "system__finalization_implementationB");
21505    pragma Export (C, u00048, "system__finalization_implementationS");
21506    pragma Export (C, u00049, "system__string_ops_concat_3B");
21507    pragma Export (C, u00050, "system__string_ops_concat_3S");
21508    pragma Export (C, u00051, "system__stream_attributesB");
21509    pragma Export (C, u00052, "system__stream_attributesS");
21510    pragma Export (C, u00053, "ada__io_exceptionsS");
21511    pragma Export (C, u00054, "system__unsigned_typesS");
21512    pragma Export (C, u00055, "system__file_control_blockS");
21513    pragma Export (C, u00056, "ada__finalization__list_controllerB");
21514    pragma Export (C, u00057, "ada__finalization__list_controllerS");
21515
21516    -- BEGIN ELABORATION ORDER
21517    -- ada (spec)
21518    -- gnat (spec)
21519    -- gnat.heap_sort_a (spec)
21520    -- gnat.heap_sort_a (body)
21521    -- gnat.htable (spec)
21522    -- gnat.htable (body)
21523    -- interfaces (spec)
21524    -- system (spec)
21525    -- system.machine_code (spec)
21526    -- system.parameters (spec)
21527    -- system.parameters (body)
21528    -- interfaces.c_streams (spec)
21529    -- interfaces.c_streams (body)
21530    -- system.standard_library (spec)
21531    -- ada.exceptions (spec)
21532    -- system.exception_table (spec)
21533    -- system.exception_table (body)
21534    -- ada.io_exceptions (spec)
21535    -- system.exceptions (spec)
21536    -- system.storage_elements (spec)
21537    -- system.storage_elements (body)
21538    -- system.machine_state_operations (spec)
21539    -- system.machine_state_operations (body)
21540    -- system.secondary_stack (spec)
21541    -- system.stack_checking (spec)
21542    -- system.soft_links (spec)
21543    -- system.soft_links (body)
21544    -- system.stack_checking (body)
21545    -- system.secondary_stack (body)
21546    -- system.standard_library (body)
21547    -- system.string_ops (spec)
21548    -- system.string_ops (body)
21549    -- ada.tags (spec)
21550    -- ada.tags (body)
21551    -- ada.streams (spec)
21552    -- system.finalization_root (spec)
21553    -- system.finalization_root (body)
21554    -- system.string_ops_concat_3 (spec)
21555    -- system.string_ops_concat_3 (body)
21556    -- system.traceback (spec)
21557    -- system.traceback (body)
21558    -- ada.exceptions (body)
21559    -- system.unsigned_types (spec)
21560    -- system.stream_attributes (spec)
21561    -- system.stream_attributes (body)
21562    -- system.finalization_implementation (spec)
21563    -- system.finalization_implementation (body)
21564    -- ada.finalization (spec)
21565    -- ada.finalization (body)
21566    -- ada.finalization.list_controller (spec)
21567    -- ada.finalization.list_controller (body)
21568    -- system.file_control_block (spec)
21569    -- system.file_io (spec)
21570    -- system.file_io (body)
21571    -- ada.text_io (spec)
21572    -- ada.text_io (body)
21573    -- hello (body)
21574    -- END ELABORATION ORDER
21575
21576 end ada_main;
21577
21578 --  The following source file name pragmas allow the generated file
21579 --  names to be unique for different main programs. They are needed
21580 --  since the package name will always be Ada_Main.
21581
21582 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
21583 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
21584
21585 --  Generated package body for Ada_Main starts here
21586
21587 package body ada_main is
21588
21589    --  The actual finalization is performed by calling the
21590    --  library routine in System.Standard_Library.Adafinal
21591
21592    procedure Do_Finalize;
21593    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
21594
21595    -------------
21596    -- adainit --
21597    -------------
21598
21599 @findex adainit
21600    procedure adainit is
21601
21602       --  These booleans are set to True once the associated unit has
21603       --  been elaborated. It is also used to avoid elaborating the
21604       --  same unit twice.
21605
21606       E040 : Boolean;
21607       pragma Import (Ada, E040, "interfaces__c_streams_E");
21608
21609       E008 : Boolean;
21610       pragma Import (Ada, E008, "ada__exceptions_E");
21611
21612       E014 : Boolean;
21613       pragma Import (Ada, E014, "system__exception_table_E");
21614
21615       E053 : Boolean;
21616       pragma Import (Ada, E053, "ada__io_exceptions_E");
21617
21618       E017 : Boolean;
21619       pragma Import (Ada, E017, "system__exceptions_E");
21620
21621       E024 : Boolean;
21622       pragma Import (Ada, E024, "system__secondary_stack_E");
21623
21624       E030 : Boolean;
21625       pragma Import (Ada, E030, "system__stack_checking_E");
21626
21627       E028 : Boolean;
21628       pragma Import (Ada, E028, "system__soft_links_E");
21629
21630       E035 : Boolean;
21631       pragma Import (Ada, E035, "ada__tags_E");
21632
21633       E033 : Boolean;
21634       pragma Import (Ada, E033, "ada__streams_E");
21635
21636       E046 : Boolean;
21637       pragma Import (Ada, E046, "system__finalization_root_E");
21638
21639       E048 : Boolean;
21640       pragma Import (Ada, E048, "system__finalization_implementation_E");
21641
21642       E044 : Boolean;
21643       pragma Import (Ada, E044, "ada__finalization_E");
21644
21645       E057 : Boolean;
21646       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
21647
21648       E055 : Boolean;
21649       pragma Import (Ada, E055, "system__file_control_block_E");
21650
21651       E042 : Boolean;
21652       pragma Import (Ada, E042, "system__file_io_E");
21653
21654       E006 : Boolean;
21655       pragma Import (Ada, E006, "ada__text_io_E");
21656
21657       --  Set_Globals is a library routine that stores away the
21658       --  value of the indicated set of global values in global
21659       --  variables within the library.
21660
21661       procedure Set_Globals
21662         (Main_Priority            : Integer;
21663          Time_Slice_Value         : Integer;
21664          WC_Encoding              : Character;
21665          Locking_Policy           : Character;
21666          Queuing_Policy           : Character;
21667          Task_Dispatching_Policy  : Character;
21668          Adafinal                 : System.Address;
21669          Unreserve_All_Interrupts : Integer;
21670          Exception_Tracebacks     : Integer);
21671 @findex __gnat_set_globals
21672       pragma Import (C, Set_Globals, "__gnat_set_globals");
21673
21674       --  SDP_Table_Build is a library routine used to build the
21675       --  exception tables. See unit Ada.Exceptions in files
21676       --  a-except.ads/adb for full details of how zero cost
21677       --  exception handling works. This procedure, the call to
21678       --  it, and the two following tables are all omitted if the
21679       --  build is in longjmp/setjump exception mode.
21680
21681 @findex SDP_Table_Build
21682 @findex Zero Cost Exceptions
21683       procedure SDP_Table_Build
21684         (SDP_Addresses   : System.Address;
21685          SDP_Count       : Natural;
21686          Elab_Addresses  : System.Address;
21687          Elab_Addr_Count : Natural);
21688       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
21689
21690       --  Table of Unit_Exception_Table addresses. Used for zero
21691       --  cost exception handling to build the top level table.
21692
21693       ST : aliased constant array (1 .. 23) of System.Address := (
21694         Hello'UET_Address,
21695         Ada.Text_Io'UET_Address,
21696         Ada.Exceptions'UET_Address,
21697         Gnat.Heap_Sort_A'UET_Address,
21698         System.Exception_Table'UET_Address,
21699         System.Machine_State_Operations'UET_Address,
21700         System.Secondary_Stack'UET_Address,
21701         System.Parameters'UET_Address,
21702         System.Soft_Links'UET_Address,
21703         System.Stack_Checking'UET_Address,
21704         System.Traceback'UET_Address,
21705         Ada.Streams'UET_Address,
21706         Ada.Tags'UET_Address,
21707         System.String_Ops'UET_Address,
21708         Interfaces.C_Streams'UET_Address,
21709         System.File_Io'UET_Address,
21710         Ada.Finalization'UET_Address,
21711         System.Finalization_Root'UET_Address,
21712         System.Finalization_Implementation'UET_Address,
21713         System.String_Ops_Concat_3'UET_Address,
21714         System.Stream_Attributes'UET_Address,
21715         System.File_Control_Block'UET_Address,
21716         Ada.Finalization.List_Controller'UET_Address);
21717
21718       --  Table of addresses of elaboration routines. Used for
21719       --  zero cost exception handling to make sure these
21720       --  addresses are included in the top level procedure
21721       --  address table.
21722
21723       EA : aliased constant array (1 .. 23) of System.Address := (
21724         adainit'Code_Address,
21725         Do_Finalize'Code_Address,
21726         Ada.Exceptions'Elab_Spec'Address,
21727         System.Exceptions'Elab_Spec'Address,
21728         Interfaces.C_Streams'Elab_Spec'Address,
21729         System.Exception_Table'Elab_Body'Address,
21730         Ada.Io_Exceptions'Elab_Spec'Address,
21731         System.Stack_Checking'Elab_Spec'Address,
21732         System.Soft_Links'Elab_Body'Address,
21733         System.Secondary_Stack'Elab_Body'Address,
21734         Ada.Tags'Elab_Spec'Address,
21735         Ada.Tags'Elab_Body'Address,
21736         Ada.Streams'Elab_Spec'Address,
21737         System.Finalization_Root'Elab_Spec'Address,
21738         Ada.Exceptions'Elab_Body'Address,
21739         System.Finalization_Implementation'Elab_Spec'Address,
21740         System.Finalization_Implementation'Elab_Body'Address,
21741         Ada.Finalization'Elab_Spec'Address,
21742         Ada.Finalization.List_Controller'Elab_Spec'Address,
21743         System.File_Control_Block'Elab_Spec'Address,
21744         System.File_Io'Elab_Body'Address,
21745         Ada.Text_Io'Elab_Spec'Address,
21746         Ada.Text_Io'Elab_Body'Address);
21747
21748    --  Start of processing for adainit
21749
21750    begin
21751
21752       --  Call SDP_Table_Build to build the top level procedure
21753       --  table for zero cost exception handling (omitted in
21754       --  longjmp/setjump mode).
21755
21756       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
21757
21758       --  Call Set_Globals to record various information for
21759       --  this partition.  The values are derived by the binder
21760       --  from information stored in the ali files by the compiler.
21761
21762 @findex __gnat_set_globals
21763       Set_Globals
21764         (Main_Priority            => -1,
21765          --  Priority of main program, -1 if no pragma Priority used
21766
21767          Time_Slice_Value         => -1,
21768          --  Time slice from Time_Slice pragma, -1 if none used
21769
21770          WC_Encoding              => 'b',
21771          --  Wide_Character encoding used, default is brackets
21772
21773          Locking_Policy           => ' ',
21774          --  Locking_Policy used, default of space means not
21775          --  specified, otherwise it is the first character of
21776          --  the policy name.
21777
21778          Queuing_Policy           => ' ',
21779          --  Queuing_Policy used, default of space means not
21780          --  specified, otherwise it is the first character of
21781          --  the policy name.
21782
21783          Task_Dispatching_Policy  => ' ',
21784          --  Task_Dispatching_Policy used, default of space means
21785          --  not specified, otherwise first character of the
21786          --  policy name.
21787
21788          Adafinal                 => System.Null_Address,
21789          --  Address of Adafinal routine, not used anymore
21790
21791          Unreserve_All_Interrupts => 0,
21792          --  Set true if pragma Unreserve_All_Interrupts was used
21793
21794          Exception_Tracebacks     => 0);
21795          --  Indicates if exception tracebacks are enabled
21796
21797       Elab_Final_Code := 1;
21798
21799       --  Now we have the elaboration calls for all units in the partition.
21800       --  The Elab_Spec and Elab_Body attributes generate references to the
21801       --  implicit elaboration procedures generated by the compiler for
21802       --  each unit that requires elaboration.
21803
21804       if not E040 then
21805          Interfaces.C_Streams'Elab_Spec;
21806       end if;
21807       E040 := True;
21808       if not E008 then
21809          Ada.Exceptions'Elab_Spec;
21810       end if;
21811       if not E014 then
21812          System.Exception_Table'Elab_Body;
21813          E014 := True;
21814       end if;
21815       if not E053 then
21816          Ada.Io_Exceptions'Elab_Spec;
21817          E053 := True;
21818       end if;
21819       if not E017 then
21820          System.Exceptions'Elab_Spec;
21821          E017 := True;
21822       end if;
21823       if not E030 then
21824          System.Stack_Checking'Elab_Spec;
21825       end if;
21826       if not E028 then
21827          System.Soft_Links'Elab_Body;
21828          E028 := True;
21829       end if;
21830       E030 := True;
21831       if not E024 then
21832          System.Secondary_Stack'Elab_Body;
21833          E024 := True;
21834       end if;
21835       if not E035 then
21836          Ada.Tags'Elab_Spec;
21837       end if;
21838       if not E035 then
21839          Ada.Tags'Elab_Body;
21840          E035 := True;
21841       end if;
21842       if not E033 then
21843          Ada.Streams'Elab_Spec;
21844          E033 := True;
21845       end if;
21846       if not E046 then
21847          System.Finalization_Root'Elab_Spec;
21848       end if;
21849       E046 := True;
21850       if not E008 then
21851          Ada.Exceptions'Elab_Body;
21852          E008 := True;
21853       end if;
21854       if not E048 then
21855          System.Finalization_Implementation'Elab_Spec;
21856       end if;
21857       if not E048 then
21858          System.Finalization_Implementation'Elab_Body;
21859          E048 := True;
21860       end if;
21861       if not E044 then
21862          Ada.Finalization'Elab_Spec;
21863       end if;
21864       E044 := True;
21865       if not E057 then
21866          Ada.Finalization.List_Controller'Elab_Spec;
21867       end if;
21868       E057 := True;
21869       if not E055 then
21870          System.File_Control_Block'Elab_Spec;
21871          E055 := True;
21872       end if;
21873       if not E042 then
21874          System.File_Io'Elab_Body;
21875          E042 := True;
21876       end if;
21877       if not E006 then
21878          Ada.Text_Io'Elab_Spec;
21879       end if;
21880       if not E006 then
21881          Ada.Text_Io'Elab_Body;
21882          E006 := True;
21883       end if;
21884
21885       Elab_Final_Code := 0;
21886    end adainit;
21887
21888    --------------
21889    -- adafinal --
21890    --------------
21891
21892 @findex adafinal
21893    procedure adafinal is
21894    begin
21895       Do_Finalize;
21896    end adafinal;
21897
21898    ----------
21899    -- main --
21900    ----------
21901
21902    --  main is actually a function, as in the ANSI C standard,
21903    --  defined to return the exit status. The three parameters
21904    --  are the argument count, argument values and environment
21905    --  pointer.
21906
21907 @findex Main Program
21908    function main
21909      (argc : Integer;
21910       argv : System.Address;
21911       envp : System.Address)
21912       return Integer
21913    is
21914       --  The initialize routine performs low level system
21915       --  initialization using a standard library routine which
21916       --  sets up signal handling and performs any other
21917       --  required setup. The routine can be found in file
21918       --  a-init.c.
21919
21920 @findex __gnat_initialize
21921       procedure initialize;
21922       pragma Import (C, initialize, "__gnat_initialize");
21923
21924       --  The finalize routine performs low level system
21925       --  finalization using a standard library routine. The
21926       --  routine is found in file a-final.c and in the standard
21927       --  distribution is a dummy routine that does nothing, so
21928       --  really this is a hook for special user finalization.
21929
21930 @findex __gnat_finalize
21931       procedure finalize;
21932       pragma Import (C, finalize, "__gnat_finalize");
21933
21934       --  We get to the main program of the partition by using
21935       --  pragma Import because if we try to with the unit and
21936       --  call it Ada style, then not only do we waste time
21937       --  recompiling it, but also, we don't really know the right
21938       --  switches (e.g. identifier character set) to be used
21939       --  to compile it.
21940
21941       procedure Ada_Main_Program;
21942       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
21943
21944    --  Start of processing for main
21945
21946    begin
21947       --  Save global variables
21948
21949       gnat_argc := argc;
21950       gnat_argv := argv;
21951       gnat_envp := envp;
21952
21953       --  Call low level system initialization
21954
21955       Initialize;
21956
21957       --  Call our generated Ada initialization routine
21958
21959       adainit;
21960
21961       --  This is the point at which we want the debugger to get
21962       --  control
21963
21964       Break_Start;
21965
21966       --  Now we call the main program of the partition
21967
21968       Ada_Main_Program;
21969
21970       --  Perform Ada finalization
21971
21972       adafinal;
21973
21974       --  Perform low level system finalization
21975
21976       Finalize;
21977
21978       --  Return the proper exit status
21979       return (gnat_exit_status);
21980    end;
21981
21982 --  This section is entirely comments, so it has no effect on the
21983 --  compilation of the Ada_Main package. It provides the list of
21984 --  object files and linker options, as well as some standard
21985 --  libraries needed for the link. The gnatlink utility parses
21986 --  this b~hello.adb file to read these comment lines to generate
21987 --  the appropriate command line arguments for the call to the
21988 --  system linker. The BEGIN/END lines are used for sentinels for
21989 --  this parsing operation.
21990
21991 --  The exact file names will of course depend on the environment,
21992 --  host/target and location of files on the host system.
21993
21994 @findex Object file list
21995 -- BEGIN Object file/option list
21996    --   ./hello.o
21997    --   -L./
21998    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
21999    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22000 -- END Object file/option list
22001
22002 end ada_main;
22003 @end smallexample
22004
22005 @noindent
22006 The Ada code in the above example is exactly what is generated by the
22007 binder. We have added comments to more clearly indicate the function
22008 of each part of the generated @code{Ada_Main} package.
22009
22010 The code is standard Ada in all respects, and can be processed by any
22011 tools that handle Ada. In particular, it is possible to use the debugger
22012 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22013 suppose that for reasons that you do not understand, your program is crashing
22014 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22015 you can place a breakpoint on the call:
22016
22017 @smallexample @c ada
22018 Ada.Text_Io'Elab_Body;
22019 @end smallexample
22020
22021 @noindent
22022 and trace the elaboration routine for this package to find out where
22023 the problem might be (more usually of course you would be debugging
22024 elaboration code in your own application).
22025
22026
22027 @node Elaboration Order Handling in GNAT
22028 @appendix Elaboration Order Handling in GNAT
22029 @cindex Order of elaboration
22030 @cindex Elaboration control
22031
22032 @menu
22033 * Elaboration Code in Ada 95::
22034 * Checking the Elaboration Order in Ada 95::
22035 * Controlling the Elaboration Order in Ada 95::
22036 * Controlling Elaboration in GNAT - Internal Calls::
22037 * Controlling Elaboration in GNAT - External Calls::
22038 * Default Behavior in GNAT - Ensuring Safety::
22039 * Treatment of Pragma Elaborate::
22040 * Elaboration Issues for Library Tasks::
22041 * Mixing Elaboration Models::
22042 * What to Do If the Default Elaboration Behavior Fails::
22043 * Elaboration for Access-to-Subprogram Values::
22044 * Summary of Procedures for Elaboration Control::
22045 * Other Elaboration Order Considerations::
22046 @end menu
22047
22048 @noindent
22049 This chapter describes the handling of elaboration code in Ada 95 and
22050 in GNAT, and discusses how the order of elaboration of program units can
22051 be controlled in GNAT, either automatically or with explicit programming
22052 features.
22053
22054 @node Elaboration Code in Ada 95
22055 @section Elaboration Code in Ada 95
22056
22057 @noindent
22058 Ada 95 provides rather general mechanisms for executing code at elaboration
22059 time, that is to say before the main program starts executing. Such code arises
22060 in three contexts:
22061
22062 @table @asis
22063 @item Initializers for variables.
22064 Variables declared at the library level, in package specs or bodies, can
22065 require initialization that is performed at elaboration time, as in:
22066 @smallexample @c ada
22067 @cartouche
22068 Sqrt_Half : Float := Sqrt (0.5);
22069 @end cartouche
22070 @end smallexample
22071
22072 @item Package initialization code
22073 Code in a @code{BEGIN-END} section at the outer level of a package body is
22074 executed as part of the package body elaboration code.
22075
22076 @item Library level task allocators
22077 Tasks that are declared using task allocators at the library level
22078 start executing immediately and hence can execute at elaboration time.
22079 @end table
22080
22081 @noindent
22082 Subprogram calls are possible in any of these contexts, which means that
22083 any arbitrary part of the program may be executed as part of the elaboration
22084 code. It is even possible to write a program which does all its work at
22085 elaboration time, with a null main program, although stylistically this
22086 would usually be considered an inappropriate way to structure
22087 a program.
22088
22089 An important concern arises in the context of elaboration code:
22090 we have to be sure that it is executed in an appropriate order. What we
22091 have is a series of elaboration code sections, potentially one section
22092 for each unit in the program. It is important that these execute
22093 in the correct order. Correctness here means that, taking the above
22094 example of the declaration of @code{Sqrt_Half},
22095 if some other piece of
22096 elaboration code references @code{Sqrt_Half},
22097 then it must run after the
22098 section of elaboration code that contains the declaration of
22099 @code{Sqrt_Half}.
22100
22101 There would never be any order of elaboration problem if we made a rule
22102 that whenever you @code{with} a unit, you must elaborate both the spec and body
22103 of that unit before elaborating the unit doing the @code{with}'ing:
22104
22105 @smallexample @c ada
22106 @group
22107 @cartouche
22108 with Unit_1;
22109 package Unit_2 is ...
22110 @end cartouche
22111 @end group
22112 @end smallexample
22113
22114 @noindent
22115 would require that both the body and spec of @code{Unit_1} be elaborated
22116 before the spec of @code{Unit_2}. However, a rule like that would be far too
22117 restrictive. In particular, it would make it impossible to have routines
22118 in separate packages that were mutually recursive.
22119
22120 You might think that a clever enough compiler could look at the actual
22121 elaboration code and determine an appropriate correct order of elaboration,
22122 but in the general case, this is not possible. Consider the following
22123 example.
22124
22125 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22126 that references
22127 the variable @code{Sqrt_1}, which is declared in the elaboration code
22128 of the body of @code{Unit_1}:
22129
22130 @smallexample @c ada
22131 @cartouche
22132 Sqrt_1 : Float := Sqrt (0.1);
22133 @end cartouche
22134 @end smallexample
22135
22136 @noindent
22137 The elaboration code of the body of @code{Unit_1} also contains:
22138
22139 @smallexample @c ada
22140 @group
22141 @cartouche
22142 if expression_1 = 1 then
22143    Q := Unit_2.Func_2;
22144 end if;
22145 @end cartouche
22146 @end group
22147 @end smallexample
22148
22149 @noindent
22150 @code{Unit_2} is exactly parallel,
22151 it has a procedure @code{Func_2} that references
22152 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22153 the body @code{Unit_2}:
22154
22155 @smallexample @c ada
22156 @cartouche
22157 Sqrt_2 : Float := Sqrt (0.1);
22158 @end cartouche
22159 @end smallexample
22160
22161 @noindent
22162 The elaboration code of the body of @code{Unit_2} also contains:
22163
22164 @smallexample @c ada
22165 @group
22166 @cartouche
22167 if expression_2 = 2 then
22168    Q := Unit_1.Func_1;
22169 end if;
22170 @end cartouche
22171 @end group
22172 @end smallexample
22173
22174 @noindent
22175 Now the question is, which of the following orders of elaboration is
22176 acceptable:
22177
22178 @smallexample
22179 @group
22180 Spec of Unit_1
22181 Spec of Unit_2
22182 Body of Unit_1
22183 Body of Unit_2
22184 @end group
22185 @end smallexample
22186
22187 @noindent
22188 or
22189
22190 @smallexample
22191 @group
22192 Spec of Unit_2
22193 Spec of Unit_1
22194 Body of Unit_2
22195 Body of Unit_1
22196 @end group
22197 @end smallexample
22198
22199 @noindent
22200 If you carefully analyze the flow here, you will see that you cannot tell
22201 at compile time the answer to this question.
22202 If @code{expression_1} is not equal to 1,
22203 and @code{expression_2} is not equal to 2,
22204 then either order is acceptable, because neither of the function calls is
22205 executed. If both tests evaluate to true, then neither order is acceptable
22206 and in fact there is no correct order.
22207
22208 If one of the two expressions is true, and the other is false, then one
22209 of the above orders is correct, and the other is incorrect. For example,
22210 if @code{expression_1} = 1 and @code{expression_2} /= 2,
22211 then the call to @code{Func_2}
22212 will occur, but not the call to @code{Func_1.}
22213 This means that it is essential
22214 to elaborate the body of @code{Unit_1} before
22215 the body of @code{Unit_2}, so the first
22216 order of elaboration is correct and the second is wrong.
22217
22218 By making @code{expression_1} and @code{expression_2}
22219 depend on input data, or perhaps
22220 the time of day, we can make it impossible for the compiler or binder
22221 to figure out which of these expressions will be true, and hence it
22222 is impossible to guarantee a safe order of elaboration at run time.
22223
22224 @node Checking the Elaboration Order in Ada 95
22225 @section Checking the Elaboration Order in Ada 95
22226
22227 @noindent
22228 In some languages that involve the same kind of elaboration problems,
22229 e.g. Java and C++, the programmer is expected to worry about these
22230 ordering problems himself, and it is common to
22231 write a program in which an incorrect elaboration order  gives
22232 surprising results, because it references variables before they
22233 are initialized.
22234 Ada 95 is designed to be a safe language, and a programmer-beware approach is
22235 clearly not sufficient. Consequently, the language provides three lines
22236 of defense:
22237
22238 @table @asis
22239 @item Standard rules
22240 Some standard rules restrict the possible choice of elaboration
22241 order. In particular, if you @code{with} a unit, then its spec is always
22242 elaborated before the unit doing the @code{with}. Similarly, a parent
22243 spec is always elaborated before the child spec, and finally
22244 a spec is always elaborated before its corresponding body.
22245
22246 @item Dynamic elaboration checks
22247 @cindex Elaboration checks
22248 @cindex Checks, elaboration
22249 Dynamic checks are made at run time, so that if some entity is accessed
22250 before it is elaborated (typically  by means of a subprogram call)
22251 then the exception (@code{Program_Error}) is raised.
22252
22253 @item Elaboration control
22254 Facilities are provided for the programmer to specify the desired order
22255 of elaboration.
22256 @end table
22257
22258 Let's look at these facilities in more detail. First, the rules for
22259 dynamic checking. One possible rule would be simply to say that the
22260 exception is raised if you access a variable which has not yet been
22261 elaborated. The trouble with this approach is that it could require
22262 expensive checks on every variable reference. Instead Ada 95 has two
22263 rules which are a little more restrictive, but easier to check, and
22264 easier to state:
22265
22266 @table @asis
22267 @item Restrictions on calls
22268 A subprogram can only be called at elaboration time if its body
22269 has been elaborated. The rules for elaboration given above guarantee
22270 that the spec of the subprogram has been elaborated before the
22271 call, but not the body. If this rule is violated, then the
22272 exception @code{Program_Error} is raised.
22273
22274 @item Restrictions on instantiations
22275 A generic unit can only be instantiated if the body of the generic
22276 unit has been elaborated. Again, the rules for elaboration given above
22277 guarantee that the spec of the generic unit has been elaborated
22278 before the instantiation, but not the body. If this rule is
22279 violated, then the exception @code{Program_Error} is raised.
22280 @end table
22281
22282 @noindent
22283 The idea is that if the body has been elaborated, then any variables
22284 it references must have been elaborated; by checking for the body being
22285 elaborated we guarantee that none of its references causes any
22286 trouble. As we noted above, this is a little too restrictive, because a
22287 subprogram that has no non-local references in its body may in fact be safe
22288 to call. However, it really would be unsafe to rely on this, because
22289 it would mean that the caller was aware of details of the implementation
22290 in the body. This goes against the basic tenets of Ada.
22291
22292 A plausible implementation can be described as follows.
22293 A Boolean variable is associated with each subprogram
22294 and each generic unit. This variable is initialized to False, and is set to
22295 True at the point body is elaborated. Every call or instantiation checks the
22296 variable, and raises @code{Program_Error} if the variable is False.
22297
22298 Note that one might think that it would be good enough to have one Boolean
22299 variable for each package, but that would not deal with cases of trying
22300 to call a body in the same package as the call
22301 that has not been elaborated yet.
22302 Of course a compiler may be able to do enough analysis to optimize away
22303 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
22304 does such optimizations, but still the easiest conceptual model is to
22305 think of there being one variable per subprogram.
22306
22307 @node Controlling the Elaboration Order in Ada 95
22308 @section Controlling the Elaboration Order in Ada 95
22309
22310 @noindent
22311 In the previous section we discussed the rules in Ada 95 which ensure
22312 that @code{Program_Error} is raised if an incorrect elaboration order is
22313 chosen. This prevents erroneous executions, but we need mechanisms to
22314 specify a correct execution and avoid the exception altogether.
22315 To achieve this, Ada 95 provides a number of features for controlling
22316 the order of elaboration. We discuss these features in this section.
22317
22318 First, there are several ways of indicating to the compiler that a given
22319 unit has no elaboration problems:
22320
22321 @table @asis
22322 @item packages that do not require a body
22323 In Ada 95, a library package that does not require a body does not permit
22324 a body. This means that if we have a such a package, as in:
22325
22326 @smallexample @c ada
22327 @group
22328 @cartouche
22329 package Definitions is
22330    generic
22331       type m is new integer;
22332    package Subp is
22333       type a is array (1 .. 10) of m;
22334       type b is array (1 .. 20) of m;
22335    end Subp;
22336 end Definitions;
22337 @end cartouche
22338 @end group
22339 @end smallexample
22340
22341 @noindent
22342 A package that @code{with}'s @code{Definitions} may safely instantiate
22343 @code{Definitions.Subp} because the compiler can determine that there
22344 definitely is no package body to worry about in this case
22345
22346 @item pragma Pure
22347 @cindex pragma Pure
22348 @findex Pure
22349 Places sufficient restrictions on a unit to guarantee that
22350 no call to any subprogram in the unit can result in an
22351 elaboration problem. This means that the compiler does not need
22352 to worry about the point of elaboration of such units, and in
22353 particular, does not need to check any calls to any subprograms
22354 in this unit.
22355
22356 @item pragma Preelaborate
22357 @findex Preelaborate
22358 @cindex pragma Preelaborate
22359 This pragma places slightly less stringent restrictions on a unit than
22360 does pragma Pure,
22361 but these restrictions are still sufficient to ensure that there
22362 are no elaboration problems with any calls to the unit.
22363
22364 @item pragma Elaborate_Body
22365 @findex Elaborate_Body
22366 @cindex pragma Elaborate_Body
22367 This pragma requires that the body of a unit be elaborated immediately
22368 after its spec. Suppose a unit @code{A} has such a pragma,
22369 and unit @code{B} does
22370 a @code{with} of unit @code{A}. Recall that the standard rules require
22371 the spec of unit @code{A}
22372 to be elaborated before the @code{with}'ing unit; given the pragma in
22373 @code{A}, we also know that the body of @code{A}
22374 will be elaborated before @code{B}, so
22375 that calls to @code{A} are safe and do not need a check.
22376 @end table
22377
22378 @noindent
22379 Note that,
22380 unlike pragma @code{Pure} and pragma @code{Preelaborate},
22381 the use of
22382 @code{Elaborate_Body} does not guarantee that the program is
22383 free of elaboration problems, because it may not be possible
22384 to satisfy the requested elaboration order.
22385 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
22386 If a programmer
22387 marks @code{Unit_1} as @code{Elaborate_Body},
22388 and not @code{Unit_2,} then the order of
22389 elaboration will be:
22390
22391 @smallexample
22392 @group
22393 Spec of Unit_2
22394 Spec of Unit_1
22395 Body of Unit_1
22396 Body of Unit_2
22397 @end group
22398 @end smallexample
22399
22400 @noindent
22401 Now that means that the call to @code{Func_1} in @code{Unit_2}
22402 need not be checked,
22403 it must be safe. But the call to @code{Func_2} in
22404 @code{Unit_1} may still fail if
22405 @code{Expression_1} is equal to 1,
22406 and the programmer must still take
22407 responsibility for this not being the case.
22408
22409 If all units carry a pragma @code{Elaborate_Body}, then all problems are
22410 eliminated, except for calls entirely within a body, which are
22411 in any case fully under programmer control. However, using the pragma
22412 everywhere is not always possible.
22413 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
22414 we marked both of them as having pragma @code{Elaborate_Body}, then
22415 clearly there would be no possible elaboration order.
22416
22417 The above pragmas allow a server to guarantee safe use by clients, and
22418 clearly this is the preferable approach. Consequently a good rule in
22419 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
22420 and if this is not possible,
22421 mark them as @code{Elaborate_Body} if possible.
22422 As we have seen, there are situations where neither of these
22423 three pragmas can be used.
22424 So we also provide methods for clients to control the
22425 order of elaboration of the servers on which they depend:
22426
22427 @table @asis
22428 @item pragma Elaborate (unit)
22429 @findex Elaborate
22430 @cindex pragma Elaborate
22431 This pragma is placed in the context clause, after a @code{with} clause,
22432 and it requires that the body of the named unit be elaborated before
22433 the unit in which the pragma occurs. The idea is to use this pragma
22434 if the current unit calls at elaboration time, directly or indirectly,
22435 some subprogram in the named unit.
22436
22437 @item pragma Elaborate_All (unit)
22438 @findex Elaborate_All
22439 @cindex pragma Elaborate_All
22440 This is a stronger version of the Elaborate pragma. Consider the
22441 following example:
22442
22443 @smallexample
22444 Unit A @code{with}'s unit B and calls B.Func in elab code
22445 Unit B @code{with}'s unit C, and B.Func calls C.Func
22446 @end smallexample
22447
22448 @noindent
22449 Now if we put a pragma @code{Elaborate (B)}
22450 in unit @code{A}, this ensures that the
22451 body of @code{B} is elaborated before the call, but not the
22452 body of @code{C}, so
22453 the call to @code{C.Func} could still cause @code{Program_Error} to
22454 be raised.
22455
22456 The effect of a pragma @code{Elaborate_All} is stronger, it requires
22457 not only that the body of the named unit be elaborated before the
22458 unit doing the @code{with}, but also the bodies of all units that the
22459 named unit uses, following @code{with} links transitively. For example,
22460 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
22461 then it requires
22462 not only that the body of @code{B} be elaborated before @code{A},
22463 but also the
22464 body of @code{C}, because @code{B} @code{with}'s @code{C}.
22465 @end table
22466
22467 @noindent
22468 We are now in a position to give a usage rule in Ada 95 for avoiding
22469 elaboration problems, at least if dynamic dispatching and access to
22470 subprogram values are not used. We will handle these cases separately
22471 later.
22472
22473 The rule is simple. If a unit has elaboration code that can directly or
22474 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
22475 a generic unit in a @code{with}'ed unit,
22476 then if the @code{with}'ed unit does not have
22477 pragma @code{Pure} or @code{Preelaborate}, then the client should have
22478 a pragma @code{Elaborate_All}
22479 for the @code{with}'ed unit. By following this rule a client is
22480 assured that calls can be made without risk of an exception.
22481 If this rule is not followed, then a program may be in one of four
22482 states:
22483
22484 @table @asis
22485 @item No order exists
22486 No order of elaboration exists which follows the rules, taking into
22487 account any @code{Elaborate}, @code{Elaborate_All},
22488 or @code{Elaborate_Body} pragmas. In
22489 this case, an Ada 95 compiler must diagnose the situation at bind
22490 time, and refuse to build an executable program.
22491
22492 @item One or more orders exist, all incorrect
22493 One or more acceptable elaboration orders exists, and all of them
22494 generate an elaboration order problem. In this case, the binder
22495 can build an executable program, but @code{Program_Error} will be raised
22496 when the program is run.
22497
22498 @item Several orders exist, some right, some incorrect
22499 One or more acceptable elaboration orders exists, and some of them
22500 work, and some do not. The programmer has not controlled
22501 the order of elaboration, so the binder may or may not pick one of
22502 the correct orders, and the program may or may not raise an
22503 exception when it is run. This is the worst case, because it means
22504 that the program may fail when moved to another compiler, or even
22505 another version of the same compiler.
22506
22507 @item One or more orders exists, all correct
22508 One ore more acceptable elaboration orders exist, and all of them
22509 work. In this case the program runs successfully. This state of
22510 affairs can be guaranteed by following the rule we gave above, but
22511 may be true even if the rule is not followed.
22512 @end table
22513
22514 @noindent
22515 Note that one additional advantage of following our Elaborate_All rule
22516 is that the program continues to stay in the ideal (all orders OK) state
22517 even if maintenance
22518 changes some bodies of some subprograms. Conversely, if a program that does
22519 not follow this rule happens to be safe at some point, this state of affairs
22520 may deteriorate silently as a result of maintenance changes.
22521
22522 You may have noticed that the above discussion did not mention
22523 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
22524 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
22525 code in the body makes calls to some other unit, so it is still necessary
22526 to use @code{Elaborate_All} on such units.
22527
22528 @node Controlling Elaboration in GNAT - Internal Calls
22529 @section Controlling Elaboration in GNAT - Internal Calls
22530
22531 @noindent
22532 In the case of internal calls, i.e. calls within a single package, the
22533 programmer has full control over the order of elaboration, and it is up
22534 to the programmer to elaborate declarations in an appropriate order. For
22535 example writing:
22536
22537 @smallexample @c ada
22538 @group
22539 @cartouche
22540 function One return Float;
22541
22542 Q : Float := One;
22543
22544 function One return Float is
22545 begin
22546      return 1.0;
22547 end One;
22548 @end cartouche
22549 @end group
22550 @end smallexample
22551
22552 @noindent
22553 will obviously raise @code{Program_Error} at run time, because function
22554 One will be called before its body is elaborated. In this case GNAT will
22555 generate a warning that the call will raise @code{Program_Error}:
22556
22557 @smallexample
22558 @group
22559 @cartouche
22560  1. procedure y is
22561  2.    function One return Float;
22562  3.
22563  4.    Q : Float := One;
22564                     |
22565     >>> warning: cannot call "One" before body is elaborated
22566     >>> warning: Program_Error will be raised at run time
22567
22568  5.
22569  6.    function One return Float is
22570  7.    begin
22571  8.         return 1.0;
22572  9.    end One;
22573 10.
22574 11. begin
22575 12.    null;
22576 13. end;
22577 @end cartouche
22578 @end group
22579 @end smallexample
22580
22581 @noindent
22582 Note that in this particular case, it is likely that the call is safe, because
22583 the function @code{One} does not access any global variables.
22584 Nevertheless in Ada 95, we do not want the validity of the check to depend on
22585 the contents of the body (think about the separate compilation case), so this
22586 is still wrong, as we discussed in the previous sections.
22587
22588 The error is easily corrected by rearranging the declarations so that the
22589 body of One appears before the declaration containing the call
22590 (note that in Ada 95,
22591 declarations can appear in any order, so there is no restriction that
22592 would prevent this reordering, and if we write:
22593
22594 @smallexample @c ada
22595 @group
22596 @cartouche
22597 function One return Float;
22598
22599 function One return Float is
22600 begin
22601      return 1.0;
22602 end One;
22603
22604 Q : Float := One;
22605 @end cartouche
22606 @end group
22607 @end smallexample
22608
22609 @noindent
22610 then all is well, no warning is generated, and no
22611 @code{Program_Error} exception
22612 will be raised.
22613 Things are more complicated when a chain of subprograms is executed:
22614
22615 @smallexample @c ada
22616 @group
22617 @cartouche
22618 function A return Integer;
22619 function B return Integer;
22620 function C return Integer;
22621
22622 function B return Integer is begin return A; end;
22623 function C return Integer is begin return B; end;
22624
22625 X : Integer := C;
22626
22627 function A return Integer is begin return 1; end;
22628 @end cartouche
22629 @end group
22630 @end smallexample
22631
22632 @noindent
22633 Now the call to @code{C}
22634 at elaboration time in the declaration of @code{X} is correct, because
22635 the body of @code{C} is already elaborated,
22636 and the call to @code{B} within the body of
22637 @code{C} is correct, but the call
22638 to @code{A} within the body of @code{B} is incorrect, because the body
22639 of @code{A} has not been elaborated, so @code{Program_Error}
22640 will be raised on the call to @code{A}.
22641 In this case GNAT will generate a
22642 warning that @code{Program_Error} may be
22643 raised at the point of the call. Let's look at the warning:
22644
22645 @smallexample
22646 @group
22647 @cartouche
22648  1. procedure x is
22649  2.    function A return Integer;
22650  3.    function B return Integer;
22651  4.    function C return Integer;
22652  5.
22653  6.    function B return Integer is begin return A; end;
22654                                                     |
22655     >>> warning: call to "A" before body is elaborated may
22656                  raise Program_Error
22657     >>> warning: "B" called at line 7
22658     >>> warning: "C" called at line 9
22659
22660  7.    function C return Integer is begin return B; end;
22661  8.
22662  9.    X : Integer := C;
22663 10.
22664 11.    function A return Integer is begin return 1; end;
22665 12.
22666 13. begin
22667 14.    null;
22668 15. end;
22669 @end cartouche
22670 @end group
22671 @end smallexample
22672
22673 @noindent
22674 Note that the message here says ``may raise'', instead of the direct case,
22675 where the message says ``will be raised''. That's because whether
22676 @code{A} is
22677 actually called depends in general on run-time flow of control.
22678 For example, if the body of @code{B} said
22679
22680 @smallexample @c ada
22681 @group
22682 @cartouche
22683 function B return Integer is
22684 begin
22685    if some-condition-depending-on-input-data then
22686       return A;
22687    else
22688       return 1;
22689    end if;
22690 end B;
22691 @end cartouche
22692 @end group
22693 @end smallexample
22694
22695 @noindent
22696 then we could not know until run time whether the incorrect call to A would
22697 actually occur, so @code{Program_Error} might
22698 or might not be raised. It is possible for a compiler to
22699 do a better job of analyzing bodies, to
22700 determine whether or not @code{Program_Error}
22701 might be raised, but it certainly
22702 couldn't do a perfect job (that would require solving the halting problem
22703 and is provably impossible), and because this is a warning anyway, it does
22704 not seem worth the effort to do the analysis. Cases in which it
22705 would be relevant are rare.
22706
22707 In practice, warnings of either of the forms given
22708 above will usually correspond to
22709 real errors, and should be examined carefully and eliminated.
22710 In the rare case where a warning is bogus, it can be suppressed by any of
22711 the following methods:
22712
22713 @itemize @bullet
22714 @item
22715 Compile with the @option{-gnatws} switch set
22716
22717 @item
22718 Suppress @code{Elaboration_Check} for the called subprogram
22719
22720 @item
22721 Use pragma @code{Warnings_Off} to turn warnings off for the call
22722 @end itemize
22723
22724 @noindent
22725 For the internal elaboration check case,
22726 GNAT by default generates the
22727 necessary run-time checks to ensure
22728 that @code{Program_Error} is raised if any
22729 call fails an elaboration check. Of course this can only happen if a
22730 warning has been issued as described above. The use of pragma
22731 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
22732 some of these checks, meaning that it may be possible (but is not
22733 guaranteed) for a program to be able to call a subprogram whose body
22734 is not yet elaborated, without raising a @code{Program_Error} exception.
22735
22736 @node Controlling Elaboration in GNAT - External Calls
22737 @section Controlling Elaboration in GNAT - External Calls
22738
22739 @noindent
22740 The previous section discussed the case in which the execution of a
22741 particular thread of elaboration code occurred entirely within a
22742 single unit. This is the easy case to handle, because a programmer
22743 has direct and total control over the order of elaboration, and
22744 furthermore, checks need only be generated in cases which are rare
22745 and which the compiler can easily detect.
22746 The situation is more complex when separate compilation is taken into account.
22747 Consider the following:
22748
22749 @smallexample @c ada
22750 @cartouche
22751 @group
22752 package Math is
22753    function Sqrt (Arg : Float) return Float;
22754 end Math;
22755
22756 package body Math is
22757    function Sqrt (Arg : Float) return Float is
22758    begin
22759          ...
22760    end Sqrt;
22761 end Math;
22762 @end group
22763 @group
22764 with Math;
22765 package Stuff is
22766    X : Float := Math.Sqrt (0.5);
22767 end Stuff;
22768
22769 with Stuff;
22770 procedure Main is
22771 begin
22772    ...
22773 end Main;
22774 @end group
22775 @end cartouche
22776 @end smallexample
22777
22778 @noindent
22779 where @code{Main} is the main program. When this program is executed, the
22780 elaboration code must first be executed, and one of the jobs of the
22781 binder is to determine the order in which the units of a program are
22782 to be elaborated. In this case we have four units: the spec and body
22783 of @code{Math},
22784 the spec of @code{Stuff} and the body of @code{Main}).
22785 In what order should the four separate sections of elaboration code
22786 be executed?
22787
22788 There are some restrictions in the order of elaboration that the binder
22789 can choose. In particular, if unit U has a @code{with}
22790 for a package @code{X}, then you
22791 are assured that the spec of @code{X}
22792 is elaborated before U , but you are
22793 not assured that the body of @code{X}
22794 is elaborated before U.
22795 This means that in the above case, the binder is allowed to choose the
22796 order:
22797
22798 @smallexample
22799 spec of Math
22800 spec of Stuff
22801 body of Math
22802 body of Main
22803 @end smallexample
22804
22805 @noindent
22806 but that's not good, because now the call to @code{Math.Sqrt}
22807 that happens during
22808 the elaboration of the @code{Stuff}
22809 spec happens before the body of @code{Math.Sqrt} is
22810 elaborated, and hence causes @code{Program_Error} exception to be raised.
22811 At first glance, one might say that the binder is misbehaving, because
22812 obviously you want to elaborate the body of something you @code{with}
22813 first, but
22814 that is not a general rule that can be followed in all cases. Consider
22815
22816 @smallexample @c ada
22817 @group
22818 @cartouche
22819 package X is ...
22820
22821 package Y is ...
22822
22823 with X;
22824 package body Y is ...
22825
22826 with Y;
22827 package body X is ...
22828 @end cartouche
22829 @end group
22830 @end smallexample
22831
22832 @noindent
22833 This is a common arrangement, and, apart from the order of elaboration
22834 problems that might arise in connection with elaboration code, this works fine.
22835 A rule that says that you must first elaborate the body of anything you
22836 @code{with} cannot work in this case:
22837 the body of @code{X} @code{with}'s @code{Y},
22838 which means you would have to
22839 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
22840 which means
22841 you have to elaborate the body of @code{X} first, but ... and we have a
22842 loop that cannot be broken.
22843
22844 It is true that the binder can in many cases guess an order of elaboration
22845 that is unlikely to cause a @code{Program_Error}
22846 exception to be raised, and it tries to do so (in the
22847 above example of @code{Math/Stuff/Spec}, the GNAT binder will
22848 by default
22849 elaborate the body of @code{Math} right after its spec, so all will be well).
22850
22851 However, a program that blindly relies on the binder to be helpful can
22852 get into trouble, as we discussed in the previous sections, so
22853 GNAT
22854 provides a number of facilities for assisting the programmer in
22855 developing programs that are robust with respect to elaboration order.
22856
22857 @node Default Behavior in GNAT - Ensuring Safety
22858 @section Default Behavior in GNAT - Ensuring Safety
22859
22860 @noindent
22861 The default behavior in GNAT ensures elaboration safety. In its
22862 default mode GNAT implements the
22863 rule we previously described as the right approach. Let's restate it:
22864
22865 @itemize
22866 @item
22867 @emph{If a unit has elaboration code that can directly or indirectly make a
22868 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
22869 in a @code{with}'ed unit, then if the @code{with}'ed unit
22870 does not have pragma @code{Pure} or
22871 @code{Preelaborate}, then the client should have an
22872 @code{Elaborate_All} for the @code{with}'ed unit.}
22873 @end itemize
22874
22875 @noindent
22876 By following this rule a client is assured that calls and instantiations
22877 can be made without risk of an exception.
22878
22879 In this mode GNAT traces all calls that are potentially made from
22880 elaboration code, and puts in any missing implicit @code{Elaborate_All}
22881 pragmas.
22882 The advantage of this approach is that no elaboration problems
22883 are possible if the binder can find an elaboration order that is
22884 consistent with these implicit @code{Elaborate_All} pragmas. The
22885 disadvantage of this approach is that no such order may exist.
22886
22887 If the binder does not generate any diagnostics, then it means that it
22888 has found an elaboration order that is guaranteed to be safe. However,
22889 the binder may still be relying on implicitly generated
22890 @code{Elaborate_All} pragmas so portability to other compilers than
22891 GNAT is not guaranteed.
22892
22893 If it is important to guarantee portability, then the compilations should
22894 use the
22895 @option{-gnatwl}
22896 (warn on elaboration problems) switch. This will cause warning messages
22897 to be generated indicating the missing @code{Elaborate_All} pragmas.
22898 Consider the following source program:
22899
22900 @smallexample @c ada
22901 @group
22902 @cartouche
22903 with k;
22904 package j is
22905   m : integer := k.r;
22906 end;
22907 @end cartouche
22908 @end group
22909 @end smallexample
22910
22911 @noindent
22912 where it is clear that there
22913 should be a pragma @code{Elaborate_All}
22914 for unit @code{k}. An implicit pragma will be generated, and it is
22915 likely that the binder will be able to honor it. However, if you want
22916 to port this program to some other Ada compiler than GNAT.
22917 it is safer to include the pragma explicitly in the source. If this
22918 unit is compiled with the
22919 @option{-gnatwl}
22920 switch, then the compiler outputs a warning:
22921
22922 @smallexample
22923 @group
22924 @cartouche
22925 1. with k;
22926 2. package j is
22927 3.   m : integer := k.r;
22928                      |
22929    >>> warning: call to "r" may raise Program_Error
22930    >>> warning: missing pragma Elaborate_All for "k"
22931
22932 4. end;
22933 @end cartouche
22934 @end group
22935 @end smallexample
22936
22937 @noindent
22938 and these warnings can be used as a guide for supplying manually
22939 the missing pragmas. It is usually a bad idea to use this warning
22940 option during development. That's because it will warn you when
22941 you need to put in a pragma, but cannot warn you when it is time
22942 to take it out. So the use of pragma Elaborate_All may lead to
22943 unnecessary dependencies and even false circularities.
22944
22945 This default mode is more restrictive than the Ada Reference
22946 Manual, and it is possible to construct programs which will compile
22947 using the dynamic model described there, but will run into a
22948 circularity using the safer static model we have described.
22949
22950 Of course any Ada compiler must be able to operate in a mode
22951 consistent with the requirements of the Ada Reference Manual,
22952 and in particular must have the capability of implementing the
22953 standard dynamic model of elaboration with run-time checks.
22954
22955 In GNAT, this standard mode can be achieved either by the use of
22956 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
22957 command, or by the use of the configuration pragma:
22958
22959 @smallexample @c ada
22960 pragma Elaboration_Checks (RM);
22961 @end smallexample
22962
22963 @noindent
22964 Either approach will cause the unit affected to be compiled using the
22965 standard dynamic run-time elaboration checks described in the Ada
22966 Reference Manual. The static model is generally preferable, since it
22967 is clearly safer to rely on compile and link time checks rather than
22968 run-time checks. However, in the case of legacy code, it may be
22969 difficult to meet the requirements of the static model. This
22970 issue is further discussed in
22971 @ref{What to Do If the Default Elaboration Behavior Fails}.
22972
22973 Note that the static model provides a strict subset of the allowed
22974 behavior and programs of the Ada Reference Manual, so if you do
22975 adhere to the static model and no circularities exist,
22976 then you are assured that your program will
22977 work using the dynamic model, providing that you remove any
22978 pragma Elaborate statements from the source.
22979
22980 @node Treatment of Pragma Elaborate
22981 @section Treatment of Pragma Elaborate
22982 @cindex Pragma Elaborate
22983
22984 @noindent
22985 The use of @code{pragma Elaborate}
22986 should generally be avoided in Ada 95 programs.
22987 The reason for this is that there is no guarantee that transitive calls
22988 will be properly handled. Indeed at one point, this pragma was placed
22989 in Annex J (Obsolescent Features), on the grounds that it is never useful.
22990
22991 Now that's a bit restrictive. In practice, the case in which
22992 @code{pragma Elaborate} is useful is when the caller knows that there
22993 are no transitive calls, or that the called unit contains all necessary
22994 transitive @code{pragma Elaborate} statements, and legacy code often
22995 contains such uses.
22996
22997 Strictly speaking the static mode in GNAT should ignore such pragmas,
22998 since there is no assurance at compile time that the necessary safety
22999 conditions are met. In practice, this would cause GNAT to be incompatible
23000 with correctly written Ada 83 code that had all necessary
23001 @code{pragma Elaborate} statements in place. Consequently, we made the
23002 decision that GNAT in its default mode will believe that if it encounters
23003 a @code{pragma Elaborate} then the programmer knows what they are doing,
23004 and it will trust that no elaboration errors can occur.
23005
23006 The result of this decision is two-fold. First to be safe using the
23007 static mode, you should remove all @code{pragma Elaborate} statements.
23008 Second, when fixing circularities in existing code, you can selectively
23009 use @code{pragma Elaborate} statements to convince the static mode of
23010 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23011 statement.
23012
23013 When using the static mode with @option{-gnatwl}, any use of
23014 @code{pragma Elaborate} will generate a warning about possible
23015 problems.
23016
23017 @node Elaboration Issues for Library Tasks
23018 @section Elaboration Issues for Library Tasks
23019 @cindex Library tasks, elaboration issues
23020 @cindex Elaboration of library tasks
23021
23022 @noindent
23023 In this section we examine special elaboration issues that arise for
23024 programs that declare library level tasks.
23025
23026 Generally the model of execution of an Ada program is that all units are
23027 elaborated, and then execution of the program starts. However, the
23028 declaration of library tasks definitely does not fit this model. The
23029 reason for this is that library tasks start as soon as they are declared
23030 (more precisely, as soon as the statement part of the enclosing package
23031 body is reached), that is to say before elaboration
23032 of the program is complete. This means that if such a task calls a
23033 subprogram, or an entry in another task, the callee may or may not be
23034 elaborated yet, and in the standard
23035 Reference Manual model of dynamic elaboration checks, you can even
23036 get timing dependent Program_Error exceptions, since there can be
23037 a race between the elaboration code and the task code.
23038
23039 The static model of elaboration in GNAT seeks to avoid all such
23040 dynamic behavior, by being conservative, and the conservative
23041 approach in this particular case is to assume that all the code
23042 in a task body is potentially executed at elaboration time if
23043 a task is declared at the library level.
23044
23045 This can definitely result in unexpected circularities. Consider
23046 the following example
23047
23048 @smallexample @c ada
23049 package Decls is
23050   task Lib_Task is
23051      entry Start;
23052   end Lib_Task;
23053
23054   type My_Int is new Integer;
23055
23056   function Ident (M : My_Int) return My_Int;
23057 end Decls;
23058
23059 with Utils;
23060 package body Decls is
23061   task body Lib_Task is
23062   begin
23063      accept Start;
23064      Utils.Put_Val (2);
23065   end Lib_Task;
23066
23067   function Ident (M : My_Int) return My_Int is
23068   begin
23069      return M;
23070   end Ident;
23071 end Decls;
23072
23073 with Decls;
23074 package Utils is
23075   procedure Put_Val (Arg : Decls.My_Int);
23076 end Utils;
23077
23078 with Text_IO;
23079 package body Utils is
23080   procedure Put_Val (Arg : Decls.My_Int) is
23081   begin
23082      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23083   end Put_Val;
23084 end Utils;
23085
23086 with Decls;
23087 procedure Main is
23088 begin
23089    Decls.Lib_Task.Start;
23090 end;
23091 @end smallexample
23092
23093 @noindent
23094 If the above example is compiled in the default static elaboration
23095 mode, then a circularity occurs. The circularity comes from the call
23096 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23097 this call occurs in elaboration code, we need an implicit pragma
23098 @code{Elaborate_All} for @code{Utils}. This means that not only must
23099 the spec and body of @code{Utils} be elaborated before the body
23100 of @code{Decls}, but also the spec and body of any unit that is
23101 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23102 the body of @code{Decls}. This is the transitive implication of
23103 pragma @code{Elaborate_All} and it makes sense, because in general
23104 the body of @code{Put_Val} might have a call to something in a
23105 @code{with'ed} unit.
23106
23107 In this case, the body of Utils (actually its spec) @code{with's}
23108 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23109 must be elaborated before itself, in case there is a call from the
23110 body of @code{Utils}.
23111
23112 Here is the exact chain of events we are worrying about:
23113
23114 @enumerate
23115 @item
23116 In the body of @code{Decls} a call is made from within the body of a library
23117 task to a subprogram in the package @code{Utils}. Since this call may
23118 occur at elaboration time (given that the task is activated at elaboration
23119 time), we have to assume the worst, i.e. that the
23120 call does happen at elaboration time.
23121
23122 @item
23123 This means that the body and spec of @code{Util} must be elaborated before
23124 the body of @code{Decls} so that this call does not cause an access before
23125 elaboration.
23126
23127 @item
23128 Within the body of @code{Util}, specifically within the body of
23129 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23130 by this package.
23131
23132 @item
23133 One such @code{with}'ed package is package @code{Decls}, so there
23134 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23135 In fact there is such a call in this example, but we would have to
23136 assume that there was such a call even if it were not there, since
23137 we are not supposed to write the body of @code{Decls} knowing what
23138 is in the body of @code{Utils}; certainly in the case of the
23139 static elaboration model, the compiler does not know what is in
23140 other bodies and must assume the worst.
23141
23142 @item
23143 This means that the spec and body of @code{Decls} must also be
23144 elaborated before we elaborate the unit containing the call, but
23145 that unit is @code{Decls}! This means that the body of @code{Decls}
23146 must be elaborated before itself, and that's a circularity.
23147 @end enumerate
23148
23149 @noindent
23150 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
23151 the body of @code{Decls} you will get a true Ada Reference Manual
23152 circularity that makes the program illegal.
23153
23154 In practice, we have found that problems with the static model of
23155 elaboration in existing code often arise from library tasks, so
23156 we must address this particular situation.
23157
23158 Note that if we compile and run the program above, using the dynamic model of
23159 elaboration (that is to say use the @option{-gnatE} switch),
23160 then it compiles, binds,
23161 links, and runs, printing the expected result of 2. Therefore in some sense
23162 the circularity here is only apparent, and we need to capture
23163 the properties of this program that  distinguish it from other library-level
23164 tasks that have real elaboration problems.
23165
23166 We have four possible answers to this question:
23167
23168 @itemize @bullet
23169
23170 @item
23171 Use the dynamic model of elaboration.
23172
23173 If we use the @option{-gnatE} switch, then as noted above, the program works.
23174 Why is this? If we examine the task body, it is apparent that the task cannot
23175 proceed past the
23176 @code{accept} statement until after elaboration has been completed, because
23177 the corresponding entry call comes from the main program, not earlier.
23178 This is why the dynamic model works here. But that's really giving
23179 up on a precise analysis, and we prefer to take this approach only if we cannot
23180 solve the
23181 problem in any other manner. So let us examine two ways to reorganize
23182 the program to avoid the potential elaboration problem.
23183
23184 @item
23185 Split library tasks into separate packages.
23186
23187 Write separate packages, so that library tasks are isolated from
23188 other declarations as much as possible. Let us look at a variation on
23189 the above program.
23190
23191 @smallexample @c ada
23192 package Decls1 is
23193   task Lib_Task is
23194      entry Start;
23195   end Lib_Task;
23196 end Decls1;
23197
23198 with Utils;
23199 package body Decls1 is
23200   task body Lib_Task is
23201   begin
23202      accept Start;
23203      Utils.Put_Val (2);
23204   end Lib_Task;
23205 end Decls1;
23206
23207 package Decls2 is
23208   type My_Int is new Integer;
23209   function Ident (M : My_Int) return My_Int;
23210 end Decls2;
23211
23212 with Utils;
23213 package body Decls2 is
23214   function Ident (M : My_Int) return My_Int is
23215   begin
23216      return M;
23217   end Ident;
23218 end Decls2;
23219
23220 with Decls2;
23221 package Utils is
23222   procedure Put_Val (Arg : Decls2.My_Int);
23223 end Utils;
23224
23225 with Text_IO;
23226 package body Utils is
23227   procedure Put_Val (Arg : Decls2.My_Int) is
23228   begin
23229      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23230   end Put_Val;
23231 end Utils;
23232
23233 with Decls1;
23234 procedure Main is
23235 begin
23236    Decls1.Lib_Task.Start;
23237 end;
23238 @end smallexample
23239
23240 @noindent
23241 All we have done is to split @code{Decls} into two packages, one
23242 containing the library task, and one containing everything else. Now
23243 there is no cycle, and the program compiles, binds, links and executes
23244 using the default static model of elaboration.
23245
23246 @item
23247 Declare separate task types.
23248
23249 A significant part of the problem arises because of the use of the
23250 single task declaration form. This means that the elaboration of
23251 the task type, and the elaboration of the task itself (i.e. the
23252 creation of the task) happen at the same time. A good rule
23253 of style in Ada 95 is to always create explicit task types. By
23254 following the additional step of placing task objects in separate
23255 packages from the task type declaration, many elaboration problems
23256 are avoided. Here is another modified example of the example program:
23257
23258 @smallexample @c ada
23259 package Decls is
23260   task type Lib_Task_Type is
23261      entry Start;
23262   end Lib_Task_Type;
23263
23264   type My_Int is new Integer;
23265
23266   function Ident (M : My_Int) return My_Int;
23267 end Decls;
23268
23269 with Utils;
23270 package body Decls is
23271   task body Lib_Task_Type is
23272   begin
23273      accept Start;
23274      Utils.Put_Val (2);
23275   end Lib_Task_Type;
23276
23277   function Ident (M : My_Int) return My_Int is
23278   begin
23279      return M;
23280   end Ident;
23281 end Decls;
23282
23283 with Decls;
23284 package Utils is
23285   procedure Put_Val (Arg : Decls.My_Int);
23286 end Utils;
23287
23288 with Text_IO;
23289 package body Utils is
23290   procedure Put_Val (Arg : Decls.My_Int) is
23291   begin
23292      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23293   end Put_Val;
23294 end Utils;
23295
23296 with Decls;
23297 package Declst is
23298    Lib_Task : Decls.Lib_Task_Type;
23299 end Declst;
23300
23301 with Declst;
23302 procedure Main is
23303 begin
23304    Declst.Lib_Task.Start;
23305 end;
23306 @end smallexample
23307
23308 @noindent
23309 What we have done here is to replace the @code{task} declaration in
23310 package @code{Decls} with a @code{task type} declaration. Then we
23311 introduce a separate package @code{Declst} to contain the actual
23312 task object. This separates the elaboration issues for
23313 the @code{task type}
23314 declaration, which causes no trouble, from the elaboration issues
23315 of the task object, which is also unproblematic, since it is now independent
23316 of the elaboration of  @code{Utils}.
23317 This separation of concerns also corresponds to
23318 a generally sound engineering principle of separating declarations
23319 from instances. This version of the program also compiles, binds, links,
23320 and executes, generating the expected output.
23321
23322 @item
23323 Use No_Entry_Calls_In_Elaboration_Code restriction.
23324 @cindex No_Entry_Calls_In_Elaboration_Code
23325
23326 The previous two approaches described how a program can be restructured
23327 to avoid the special problems caused by library task bodies. in practice,
23328 however, such restructuring may be difficult to apply to existing legacy code,
23329 so we must consider solutions that do not require massive rewriting.
23330
23331 Let us consider more carefully why our original sample program works
23332 under the dynamic model of elaboration. The reason is that the code
23333 in the task body blocks immediately on the @code{accept}
23334 statement. Now of course there is nothing to prohibit elaboration
23335 code from making entry calls (for example from another library level task),
23336 so we cannot tell in isolation that
23337 the task will not execute the accept statement  during elaboration.
23338
23339 However, in practice it is very unusual to see elaboration code
23340 make any entry calls, and the pattern of tasks starting
23341 at elaboration time and then immediately blocking on @code{accept} or
23342 @code{select} statements is very common. What this means is that
23343 the compiler is being too pessimistic when it analyzes the
23344 whole package body as though it might be executed at elaboration
23345 time.
23346
23347 If we know that the elaboration code contains no entry calls, (a very safe
23348 assumption most of the time, that could almost be made the default
23349 behavior), then we can compile all units of the program under control
23350 of the following configuration pragma:
23351
23352 @smallexample
23353 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
23354 @end smallexample
23355
23356 @noindent
23357 This pragma can be placed in the @file{gnat.adc} file in the usual
23358 manner. If we take our original unmodified program and compile it
23359 in the presence of a @file{gnat.adc} containing the above pragma,
23360 then once again, we can compile, bind, link, and execute, obtaining
23361 the expected result. In the presence of this pragma, the compiler does
23362 not trace calls in a task body, that appear after the first @code{accept}
23363 or @code{select} statement, and therefore does not report a potential
23364 circularity in the original program.
23365
23366 The compiler will check to the extent it can that the above
23367 restriction is not violated, but it is not always possible to do a
23368 complete check at compile time, so it is important to use this
23369 pragma only if the stated restriction is in fact met, that is to say
23370 no task receives an entry call before elaboration of all units is completed.
23371
23372 @end itemize
23373
23374 @node Mixing Elaboration Models
23375 @section Mixing Elaboration Models
23376 @noindent
23377 So far, we have assumed that the entire program is either compiled
23378 using the dynamic model or static model, ensuring consistency. It
23379 is possible to mix the two models, but rules have to be followed
23380 if this mixing is done to ensure that elaboration checks are not
23381 omitted.
23382
23383 The basic rule is that @emph{a unit compiled with the static model cannot
23384 be @code{with'ed} by a unit compiled with the dynamic model}. The
23385 reason for this is that in the static model, a unit assumes that
23386 its clients guarantee to use (the equivalent of) pragma
23387 @code{Elaborate_All} so that no elaboration checks are required
23388 in inner subprograms, and this assumption is violated if the
23389 client is compiled with dynamic checks.
23390
23391 The precise rule is as follows. A unit that is compiled with dynamic
23392 checks can only @code{with} a unit that meets at least one of the
23393 following criteria:
23394
23395 @itemize @bullet
23396
23397 @item
23398 The @code{with'ed} unit is itself compiled with dynamic elaboration
23399 checks (that is with the @option{-gnatE} switch.
23400
23401 @item
23402 The @code{with'ed} unit is an internal GNAT implementation unit from
23403 the System, Interfaces, Ada, or GNAT hierarchies.
23404
23405 @item
23406 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
23407
23408 @item
23409 The @code{with'ing} unit (that is the client) has an explicit pragma
23410 @code{Elaborate_All} for the @code{with'ed} unit.
23411
23412 @end itemize
23413
23414 @noindent
23415 If this rule is violated, that is if a unit with dynamic elaboration
23416 checks @code{with's} a unit that does not meet one of the above four
23417 criteria, then the binder (@code{gnatbind}) will issue a warning
23418 similar to that in the following example:
23419
23420 @smallexample
23421 warning: "x.ads" has dynamic elaboration checks and with's
23422 warning:   "y.ads" which has static elaboration checks
23423 @end smallexample
23424
23425 @noindent
23426 These warnings indicate that the rule has been violated, and that as a result
23427 elaboration checks may be missed in the resulting executable file.
23428 This warning may be suppressed using the @option{-ws} binder switch
23429 in the usual manner.
23430
23431 One useful application of this mixing rule is in the case of a subsystem
23432 which does not itself @code{with} units from the remainder of the
23433 application. In this case, the entire subsystem can be compiled with
23434 dynamic checks to resolve a circularity in the subsystem, while
23435 allowing the main application that uses this subsystem to be compiled
23436 using the more reliable default static model.
23437
23438 @node What to Do If the Default Elaboration Behavior Fails
23439 @section What to Do If the Default Elaboration Behavior Fails
23440
23441 @noindent
23442 If the binder cannot find an acceptable order, it outputs detailed
23443 diagnostics. For example:
23444 @smallexample
23445 @group
23446 @iftex
23447 @leftskip=0cm
23448 @end iftex
23449 error: elaboration circularity detected
23450 info:   "proc (body)" must be elaborated before "pack (body)"
23451 info:     reason: Elaborate_All probably needed in unit "pack (body)"
23452 info:     recompile "pack (body)" with -gnatwl
23453 info:                             for full details
23454 info:       "proc (body)"
23455 info:         is needed by its spec:
23456 info:       "proc (spec)"
23457 info:         which is withed by:
23458 info:       "pack (body)"
23459 info:  "pack (body)" must be elaborated before "proc (body)"
23460 info:     reason: pragma Elaborate in unit "proc (body)"
23461 @end group
23462
23463 @end smallexample
23464
23465 @noindent
23466 In this case we have a cycle that the binder cannot break. On the one
23467 hand, there is an explicit pragma Elaborate in @code{proc} for
23468 @code{pack}. This means that the body of @code{pack} must be elaborated
23469 before the body of @code{proc}. On the other hand, there is elaboration
23470 code in @code{pack} that calls a subprogram in @code{proc}. This means
23471 that for maximum safety, there should really be a pragma
23472 Elaborate_All in @code{pack} for @code{proc} which would require that
23473 the body of @code{proc} be elaborated before the body of
23474 @code{pack}. Clearly both requirements cannot be satisfied.
23475 Faced with a circularity of this kind, you have three different options.
23476
23477 @table @asis
23478 @item Fix the program
23479 The most desirable option from the point of view of long-term maintenance
23480 is to rearrange the program so that the elaboration problems are avoided.
23481 One useful technique is to place the elaboration code into separate
23482 child packages. Another is to move some of the initialization code to
23483 explicitly called subprograms, where the program controls the order
23484 of initialization explicitly. Although this is the most desirable option,
23485 it may be impractical and involve too much modification, especially in
23486 the case of complex legacy code.
23487
23488 @item Perform dynamic checks
23489 If the compilations are done using the
23490 @option{-gnatE}
23491 (dynamic elaboration check) switch, then GNAT behaves in
23492 a quite different manner. Dynamic checks are generated for all calls
23493 that could possibly result in raising an exception. With this switch,
23494 the compiler does not generate implicit @code{Elaborate_All} pragmas.
23495 The behavior then is exactly as specified in the Ada 95 Reference Manual.
23496 The binder will generate an executable program that may or may not
23497 raise @code{Program_Error}, and then it is the programmer's job to ensure
23498 that it does not raise an exception. Note that it is important to
23499 compile all units with the switch, it cannot be used selectively.
23500
23501 @item Suppress checks
23502 The drawback of dynamic checks is that they generate a
23503 significant overhead at run time, both in space and time. If you
23504 are absolutely sure that your program cannot raise any elaboration
23505 exceptions, and you still want to use the dynamic elaboration model,
23506 then you can use the configuration pragma
23507 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
23508 example this pragma could be placed in the @file{gnat.adc} file.
23509
23510 @item Suppress checks selectively
23511 When you know that certain calls in elaboration code cannot possibly
23512 lead to an elaboration error, and the binder nevertheless generates warnings
23513 on those calls and inserts Elaborate_All pragmas that lead to elaboration
23514 circularities, it is possible to remove those warnings locally and obtain
23515 a program that will bind. Clearly this can be unsafe, and it is the
23516 responsibility of the programmer to make sure that the resulting program has
23517 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
23518 be used with different granularity to suppress warnings and break
23519 elaboration circularities:
23520
23521 @itemize @bullet
23522 @item
23523 Place the pragma that names the called subprogram in the declarative part
23524 that contains the call.
23525
23526 @item
23527 Place the pragma in the declarative part, without naming an entity. This
23528 disables warnings on all calls in the corresponding  declarative region.
23529
23530 @item
23531 Place the pragma in the package spec that declares the called subprogram,
23532 and name the subprogram. This disables warnings on all elaboration calls to
23533 that subprogram.
23534
23535 @item
23536 Place the pragma in the package spec that declares the called subprogram,
23537 without naming any entity. This disables warnings on all elaboration calls to
23538 all subprograms declared in this spec.
23539
23540 @item Use Pragma Elaborate
23541 As previously described in section @xref{Treatment of Pragma Elaborate},
23542 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
23543 that no elaboration checks are required on calls to the designated unit.
23544 There may be cases in which the caller knows that no transitive calls
23545 can occur, so that a @code{pragma Elaborate} will be sufficient in a
23546 case where @code{pragma Elaborate_All} would cause a circularity.
23547 @end itemize
23548
23549 @noindent
23550 These five cases are listed in order of decreasing safety, and therefore
23551 require increasing programmer care in their application. Consider the
23552 following program:
23553
23554 @smallexample @c adanocomment
23555 package Pack1 is
23556   function F1 return Integer;
23557   X1 : Integer;
23558 end Pack1;
23559
23560 package Pack2 is
23561   function F2 return Integer;
23562   function Pure (x : integer) return integer;
23563   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
23564   --  pragma Suppress (Elaboration_Check);              -- (4)
23565 end Pack2;
23566
23567 with Pack2;
23568 package body Pack1 is
23569   function F1 return Integer is
23570   begin
23571     return 100;
23572   end F1;
23573   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
23574 begin
23575   declare
23576     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
23577     --  pragma Suppress(Elaboration_Check);             -- (2)
23578   begin
23579     X1 := Pack2.F2 + 1;                --  Elab. call (2)
23580   end;
23581 end Pack1;
23582
23583 with Pack1;
23584 package body Pack2 is
23585   function F2 return Integer is
23586   begin
23587      return Pack1.F1;
23588   end F2;
23589   function Pure (x : integer) return integer is
23590   begin
23591      return x ** 3 - 3 * x;
23592   end;
23593 end Pack2;
23594
23595 with Pack1, Ada.Text_IO;
23596 procedure Proc3 is
23597 begin
23598   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
23599 end Proc3;
23600 @end smallexample
23601 In the absence of any pragmas, an attempt to bind this program produces
23602 the following diagnostics:
23603 @smallexample
23604 @group
23605 @iftex
23606 @leftskip=.5cm
23607 @end iftex
23608 error: elaboration circularity detected
23609 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
23610 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
23611 info:       recompile "pack1 (body)" with -gnatwl for full details
23612 info:          "pack1 (body)"
23613 info:             must be elaborated along with its spec:
23614 info:          "pack1 (spec)"
23615 info:             which is withed by:
23616 info:          "pack2 (body)"
23617 info:             which must be elaborated along with its spec:
23618 info:          "pack2 (spec)"
23619 info:             which is withed by:
23620 info:          "pack1 (body)"
23621 @end group
23622 @end smallexample
23623 The sources of the circularity are the two calls to @code{Pack2.Pure} and
23624 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
23625 F2 is safe, even though F2 calls F1, because the call appears after the
23626 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
23627 remove the warning on the call. It is also possible to use pragma (2)
23628 because there are no other potentially unsafe calls in the block.
23629
23630 @noindent
23631 The call to @code{Pure} is safe because this function does not depend on the
23632 state of @code{Pack2}. Therefore any call to this function is safe, and it
23633 is correct to place pragma (3) in the corresponding package spec.
23634
23635 @noindent
23636 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
23637 warnings on all calls to functions declared therein. Note that this is not
23638 necessarily safe, and requires more detailed examination of the subprogram
23639 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
23640 be already elaborated.
23641 @end table
23642
23643 @noindent
23644 It is hard to generalize on which of these four approaches should be
23645 taken. Obviously if it is possible to fix the program so that the default
23646 treatment works, this is preferable, but this may not always be practical.
23647 It is certainly simple enough to use
23648 @option{-gnatE}
23649 but the danger in this case is that, even if the GNAT binder
23650 finds a correct elaboration order, it may not always do so,
23651 and certainly a binder from another Ada compiler might not. A
23652 combination of testing and analysis (for which the warnings generated
23653 with the
23654 @option{-gnatwl}
23655 switch can be useful) must be used to ensure that the program is free
23656 of errors. One switch that is useful in this testing is the
23657 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
23658 switch for
23659 @code{gnatbind}.
23660 Normally the binder tries to find an order that has the best chance of
23661 of avoiding elaboration problems. With this switch, the binder
23662 plays a devil's advocate role, and tries to choose the order that
23663 has the best chance of failing. If your program works even with this
23664 switch, then it has a better chance of being error free, but this is still
23665 not a guarantee.
23666
23667 For an example of this approach in action, consider the C-tests (executable
23668 tests) from the ACVC suite. If these are compiled and run with the default
23669 treatment, then all but one of them succeed without generating any error
23670 diagnostics from the binder. However, there is one test that fails, and
23671 this is not surprising, because the whole point of this test is to ensure
23672 that the compiler can handle cases where it is impossible to determine
23673 a correct order statically, and it checks that an exception is indeed
23674 raised at run time.
23675
23676 This one test must be compiled and run using the
23677 @option{-gnatE}
23678 switch, and then it passes. Alternatively, the entire suite can
23679 be run using this switch. It is never wrong to run with the dynamic
23680 elaboration switch if your code is correct, and we assume that the
23681 C-tests are indeed correct (it is less efficient, but efficiency is
23682 not a factor in running the ACVC tests.)
23683
23684 @node Elaboration for Access-to-Subprogram Values
23685 @section Elaboration for Access-to-Subprogram Values
23686 @cindex Access-to-subprogram
23687
23688 @noindent
23689 The introduction of access-to-subprogram types in Ada 95 complicates
23690 the handling of elaboration. The trouble is that it becomes
23691 impossible to tell at compile time which procedure
23692 is being called. This means that it is not possible for the binder
23693 to analyze the elaboration requirements in this case.
23694
23695 If at the point at which the access value is created
23696 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
23697 the body of the subprogram is
23698 known to have been elaborated, then the access value is safe, and its use
23699 does not require a check. This may be achieved by appropriate arrangement
23700 of the order of declarations if the subprogram is in the current unit,
23701 or, if the subprogram is in another unit, by using pragma
23702 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
23703 on the referenced unit.
23704
23705 If the referenced body is not known to have been elaborated at the point
23706 the access value is created, then any use of the access value must do a
23707 dynamic check, and this dynamic check will fail and raise a
23708 @code{Program_Error} exception if the body has not been elaborated yet.
23709 GNAT will generate the necessary checks, and in addition, if the
23710 @option{-gnatwl}
23711 switch is set, will generate warnings that such checks are required.
23712
23713 The use of dynamic dispatching for tagged types similarly generates
23714 a requirement for dynamic checks, and premature calls to any primitive
23715 operation of a tagged type before the body of the operation has been
23716 elaborated, will result in the raising of @code{Program_Error}.
23717
23718 @node Summary of Procedures for Elaboration Control
23719 @section Summary of Procedures for Elaboration Control
23720 @cindex Elaboration control
23721
23722 @noindent
23723 First, compile your program with the default options, using none of
23724 the special elaboration control switches. If the binder successfully
23725 binds your program, then you can be confident that, apart from issues
23726 raised by the use of access-to-subprogram types and dynamic dispatching,
23727 the program is free of elaboration errors. If it is important that the
23728 program be portable, then use the
23729 @option{-gnatwl}
23730 switch to generate warnings about missing @code{Elaborate_All}
23731 pragmas, and supply the missing pragmas.
23732
23733 If the program fails to bind using the default static elaboration
23734 handling, then you can fix the program to eliminate the binder
23735 message, or recompile the entire program with the
23736 @option{-gnatE} switch to generate dynamic elaboration checks,
23737 and, if you are sure there really are no elaboration problems,
23738 use a global pragma @code{Suppress (Elaboration_Check)}.
23739
23740 @node Other Elaboration Order Considerations
23741 @section Other Elaboration Order Considerations
23742 @noindent
23743 This section has been entirely concerned with the issue of finding a valid
23744 elaboration order, as defined by the Ada Reference Manual. In a case
23745 where several elaboration orders are valid, the task is to find one
23746 of the possible valid elaboration orders (and the static model in GNAT
23747 will ensure that this is achieved).
23748
23749 The purpose of the elaboration rules in the Ada Reference Manual is to
23750 make sure that no entity is accessed before it has been elaborated. For
23751 a subprogram, this means that the spec and body must have been elaborated
23752 before the subprogram is called. For an object, this means that the object
23753 must have been elaborated before its value is read or written. A violation
23754 of either of these two requirements is an access before elaboration order,
23755 and this section has been all about avoiding such errors.
23756
23757 In the case where more than one order of elaboration is possible, in the
23758 sense that access before elaboration errors are avoided, then any one of
23759 the orders is ``correct'' in the sense that it meets the requirements of
23760 the Ada Reference Manual, and no such error occurs.
23761
23762 However, it may be the case for a given program, that there are
23763 constraints on the order of elaboration that come not from consideration
23764 of avoiding elaboration errors, but rather from extra-lingual logic
23765 requirements. Consider this example:
23766
23767 @smallexample @c ada
23768 with Init_Constants;
23769 package Constants is
23770    X : Integer := 0;
23771    Y : Integer := 0;
23772 end Constants;
23773
23774 package Init_Constants is
23775    procedure P; -- require a body
23776 end Init_Constants;
23777
23778 with Constants;
23779 package body Init_Constants is
23780    procedure P is begin null; end;
23781 begin
23782    Constants.X := 3;
23783    Constants.Y := 4;
23784 end Init_Constants;
23785
23786 with Constants;
23787 package Calc is
23788    Z : Integer := Constants.X + Constants.Y;
23789 end Calc;
23790
23791 with Calc;
23792 with Text_IO; use Text_IO;
23793 procedure Main is
23794 begin
23795    Put_Line (Calc.Z'Img);
23796 end Main;
23797 @end smallexample
23798
23799 @noindent
23800 In this example, there is more than one valid order of elaboration. For
23801 example both the following are correct orders:
23802
23803 @smallexample
23804 Init_Constants spec
23805 Constants spec
23806 Calc spec
23807 Init_Constants body
23808 Main body
23809
23810   and
23811
23812 Init_Constants spec
23813 Init_Constants body
23814 Constants spec
23815 Calc spec
23816 Main body
23817 @end smallexample
23818
23819 @noindent
23820 There is no language rule to prefer one or the other, both are correct
23821 from an order of elaboration point of view. But the programmatic effects
23822 of the two orders are very different. In the first, the elaboration routine
23823 of @code{Calc} initializes @code{Z} to zero, and then the main program
23824 runs with this value of zero. But in the second order, the elaboration
23825 routine of @code{Calc} runs after the body of Init_Constants has set
23826 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
23827 runs.
23828
23829 One could perhaps by applying pretty clever non-artificial intelligence
23830 to the situation guess that it is more likely that the second order of
23831 elaboration is the one desired, but there is no formal linguistic reason
23832 to prefer one over the other. In fact in this particular case, GNAT will
23833 prefer the second order, because of the rule that bodies are elaborated
23834 as soon as possible, but it's just luck that this is what was wanted
23835 (if indeed the second order was preferred).
23836
23837 If the program cares about the order of elaboration routines in a case like
23838 this, it is important to specify the order required. In this particular
23839 case, that could have been achieved by adding to the spec of Calc:
23840
23841 @smallexample @c ada
23842 pragma Elaborate_All (Constants);
23843 @end smallexample
23844
23845 @noindent
23846 which requires that the body (if any) and spec of @code{Constants},
23847 as well as the body and spec of any unit @code{with}'ed by
23848 @code{Constants} be elaborated before @code{Calc} is elaborated.
23849
23850 Clearly no automatic method can always guess which alternative you require,
23851 and if you are working with legacy code that had constraints of this kind
23852 which were not properly specified by adding @code{Elaborate} or
23853 @code{Elaborate_All} pragmas, then indeed it is possible that two different
23854 compilers can choose different orders.
23855
23856 The @code{gnatbind}
23857 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
23858 out problems. This switch causes bodies to be elaborated as late as possible
23859 instead of as early as possible. In the example above, it would have forced
23860 the choice of the first elaboration order. If you get different results
23861 when using this switch, and particularly if one set of results is right,
23862 and one is wrong as far as you are concerned, it shows that you have some
23863 missing @code{Elaborate} pragmas. For the example above, we have the
23864 following output:
23865
23866 @smallexample
23867 gnatmake -f -q main
23868 main
23869  7
23870 gnatmake -f -q main -bargs -p
23871 main
23872  0
23873 @end smallexample
23874
23875 @noindent
23876 It is of course quite unlikely that both these results are correct, so
23877 it is up to you in a case like this to investigate the source of the
23878 difference, by looking at the two elaboration orders that are chosen,
23879 and figuring out which is correct, and then adding the necessary
23880 @code{Elaborate_All} pragmas to ensure the desired order.
23881
23882
23883 @node Inline Assembler
23884 @appendix Inline Assembler
23885
23886 @noindent
23887 If you need to write low-level software that interacts directly
23888 with the hardware, Ada provides two ways to incorporate assembly
23889 language code into your program.  First, you can import and invoke
23890 external routines written in assembly language, an Ada feature fully
23891 supported by GNAT.  However, for small sections of code it may be simpler
23892 or more efficient to include assembly language statements directly
23893 in your Ada source program, using the facilities of the implementation-defined
23894 package @code{System.Machine_Code}, which incorporates the gcc
23895 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
23896 including the following:
23897
23898 @itemize @bullet
23899 @item No need to use non-Ada tools
23900 @item Consistent interface over different targets
23901 @item Automatic usage of the proper calling conventions
23902 @item Access to Ada constants and variables
23903 @item Definition of intrinsic routines
23904 @item Possibility of inlining a subprogram comprising assembler code
23905 @item Code optimizer can take Inline Assembler code into account
23906 @end itemize
23907
23908 This chapter presents a series of examples to show you how to use
23909 the Inline Assembler.  Although it focuses on the Intel x86,
23910 the general approach applies also to other processors.
23911 It is assumed that you are familiar with Ada
23912 and with assembly language programming.
23913
23914 @menu
23915 * Basic Assembler Syntax::
23916 * A Simple Example of Inline Assembler::
23917 * Output Variables in Inline Assembler::
23918 * Input Variables in Inline Assembler::
23919 * Inlining Inline Assembler Code::
23920 * Other Asm Functionality::
23921 * A Complete Example::
23922 @end menu
23923
23924 @c ---------------------------------------------------------------------------
23925 @node Basic Assembler Syntax
23926 @section Basic Assembler Syntax
23927
23928 @noindent
23929 The assembler used by GNAT and gcc is based not on the Intel assembly
23930 language, but rather on a language that descends from the AT&T Unix
23931 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
23932 The following table summarizes the main features of @emph{as} syntax
23933 and points out the differences from the Intel conventions.
23934 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
23935 pre-processor) documentation for further information.
23936
23937 @table @asis
23938 @item Register names
23939 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
23940 @*
23941 Intel: No extra punctuation; for example @code{eax}
23942
23943 @item Immediate operand
23944 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
23945 @*
23946 Intel: No extra punctuation; for example @code{4}
23947
23948 @item Address
23949 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
23950 @*
23951 Intel: No extra punctuation; for example @code{loc}
23952
23953 @item Memory contents
23954 gcc / @emph{as}: No extra punctuation; for example @code{loc}
23955 @*
23956 Intel: Square brackets; for example @code{[loc]}
23957
23958 @item Register contents
23959 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
23960 @*
23961 Intel: Square brackets; for example @code{[eax]}
23962
23963 @item Hexadecimal numbers
23964 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
23965 @*
23966 Intel: Trailing ``h''; for example @code{A0h}
23967
23968 @item Operand size
23969 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
23970 a 16-bit word
23971 @*
23972 Intel: Implicit, deduced by assembler; for example @code{mov}
23973
23974 @item Instruction repetition
23975 gcc / @emph{as}: Split into two lines; for example
23976 @*
23977 @code{rep}
23978 @*
23979 @code{stosl}
23980 @*
23981 Intel: Keep on one line; for example @code{rep stosl}
23982
23983 @item Order of operands
23984 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
23985 @*
23986 Intel: Destination first; for example @code{mov eax, 4}
23987 @end table
23988
23989 @c ---------------------------------------------------------------------------
23990 @node A Simple Example of Inline Assembler
23991 @section A Simple Example of Inline Assembler
23992
23993 @noindent
23994 The following example will generate a single assembly language statement,
23995 @code{nop}, which does nothing.  Despite its lack of run-time effect,
23996 the example will be useful in illustrating the basics of
23997 the Inline Assembler facility.
23998
23999 @smallexample @c ada
24000 @group
24001 with System.Machine_Code; use System.Machine_Code;
24002 procedure Nothing is
24003 begin
24004    Asm ("nop");
24005 end Nothing;
24006 @end group
24007 @end smallexample
24008
24009 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
24010 here it takes one parameter, a @emph{template string} that must be a static
24011 expression and that will form the generated instruction.
24012 @code{Asm} may be regarded as a compile-time procedure that parses
24013 the template string and additional parameters (none here),
24014 from which it generates a sequence of assembly language instructions.
24015
24016 The examples in this chapter will illustrate several of the forms
24017 for invoking @code{Asm}; a complete specification of the syntax
24018 is found in the @cite{GNAT Reference Manual}.
24019
24020 Under the standard GNAT conventions, the @code{Nothing} procedure
24021 should be in a file named @file{nothing.adb}.
24022 You can build the executable in the usual way:
24023 @smallexample
24024 gnatmake nothing
24025 @end smallexample
24026 However, the interesting aspect of this example is not its run-time behavior
24027 but rather the generated assembly code.
24028 To see this output, invoke the compiler as follows:
24029 @smallexample
24030    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
24031 @end smallexample
24032 where the options are:
24033
24034 @table @code
24035 @item -c
24036 compile only (no bind or link)
24037 @item -S
24038 generate assembler listing
24039 @item -fomit-frame-pointer
24040 do not set up separate stack frames
24041 @item -gnatp
24042 do not add runtime checks
24043 @end table
24044
24045 This gives a human-readable assembler version of the code. The resulting
24046 file will have the same name as the Ada source file, but with a @code{.s}
24047 extension. In our example, the file @file{nothing.s} has the following
24048 contents:
24049
24050 @smallexample
24051 @group
24052 .file "nothing.adb"
24053 gcc2_compiled.:
24054 ___gnu_compiled_ada:
24055 .text
24056    .align 4
24057 .globl __ada_nothing
24058 __ada_nothing:
24059 #APP
24060    nop
24061 #NO_APP
24062    jmp L1
24063    .align 2,0x90
24064 L1:
24065    ret
24066 @end group
24067 @end smallexample
24068
24069 The assembly code you included is clearly indicated by
24070 the compiler, between the @code{#APP} and @code{#NO_APP}
24071 delimiters. The character before the 'APP' and 'NOAPP'
24072 can differ on different targets. For example, GNU/Linux uses '#APP' while
24073 on NT you will see '/APP'.
24074
24075 If you make a mistake in your assembler code (such as using the
24076 wrong size modifier, or using a wrong operand for the instruction) GNAT
24077 will report this error in a temporary file, which will be deleted when
24078 the compilation is finished.  Generating an assembler file will help
24079 in such cases, since you can assemble this file separately using the
24080 @emph{as} assembler that comes with gcc.
24081
24082 Assembling the file using the command
24083
24084 @smallexample
24085 as @file{nothing.s}
24086 @end smallexample
24087 @noindent
24088 will give you error messages whose lines correspond to the assembler
24089 input file, so you can easily find and correct any mistakes you made.
24090 If there are no errors, @emph{as} will generate an object file
24091 @file{nothing.out}.
24092
24093 @c ---------------------------------------------------------------------------
24094 @node Output Variables in Inline Assembler
24095 @section Output Variables in Inline Assembler
24096
24097 @noindent
24098 The examples in this section, showing how to access the processor flags,
24099 illustrate how to specify the destination operands for assembly language
24100 statements.
24101
24102 @smallexample @c ada
24103 @group
24104 with Interfaces; use Interfaces;
24105 with Ada.Text_IO; use Ada.Text_IO;
24106 with System.Machine_Code; use System.Machine_Code;
24107 procedure Get_Flags is
24108    Flags : Unsigned_32;
24109    use ASCII;
24110 begin
24111    Asm ("pushfl"          & LF & HT & -- push flags on stack
24112         "popl %%eax"      & LF & HT & -- load eax with flags
24113         "movl %%eax, %0",             -- store flags in variable
24114         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24115    Put_Line ("Flags register:" & Flags'Img);
24116 end Get_Flags;
24117 @end group
24118 @end smallexample
24119
24120 In order to have a nicely aligned assembly listing, we have separated
24121 multiple assembler statements in the Asm template string with linefeed
24122 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
24123 The resulting section of the assembly output file is:
24124
24125 @smallexample
24126 @group
24127 #APP
24128    pushfl
24129    popl %eax
24130    movl %eax, -40(%ebp)
24131 #NO_APP
24132 @end group
24133 @end smallexample
24134
24135 It would have been legal to write the Asm invocation as:
24136
24137 @smallexample
24138 Asm ("pushfl popl %%eax movl %%eax, %0")
24139 @end smallexample
24140
24141 but in the generated assembler file, this would come out as:
24142
24143 @smallexample
24144 #APP
24145    pushfl popl %eax movl %eax, -40(%ebp)
24146 #NO_APP
24147 @end smallexample
24148
24149 which is not so convenient for the human reader.
24150
24151 We use Ada comments
24152 at the end of each line to explain what the assembler instructions
24153 actually do.  This is a useful convention.
24154
24155 When writing Inline Assembler instructions, you need to precede each register
24156 and variable name with a percent sign.  Since the assembler already requires
24157 a percent sign at the beginning of a register name, you need two consecutive
24158 percent signs for such names in the Asm template string, thus @code{%%eax}.
24159 In the generated assembly code, one of the percent signs will be stripped off.
24160
24161 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
24162 variables: operands you later define using @code{Input} or @code{Output}
24163 parameters to @code{Asm}.
24164 An output variable is illustrated in
24165 the third statement in the Asm template string:
24166 @smallexample
24167 movl %%eax, %0
24168 @end smallexample
24169 The intent is to store the contents of the eax register in a variable that can
24170 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
24171 necessarily work, since the compiler might optimize by using a register
24172 to hold Flags, and the expansion of the @code{movl} instruction would not be
24173 aware of this optimization.  The solution is not to store the result directly
24174 but rather to advise the compiler to choose the correct operand form;
24175 that is the purpose of the @code{%0} output variable.
24176
24177 Information about the output variable is supplied in the @code{Outputs}
24178 parameter to @code{Asm}:
24179 @smallexample
24180 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24181 @end smallexample
24182
24183 The output is defined by the @code{Asm_Output} attribute of the target type;
24184 the general format is
24185 @smallexample
24186 Type'Asm_Output (constraint_string, variable_name)
24187 @end smallexample
24188
24189 The constraint string directs the compiler how
24190 to store/access the associated variable.  In the example
24191 @smallexample
24192 Unsigned_32'Asm_Output ("=m", Flags);
24193 @end smallexample
24194 the @code{"m"} (memory) constraint tells the compiler that the variable
24195 @code{Flags} should be stored in a memory variable, thus preventing
24196 the optimizer from keeping it in a register.  In contrast,
24197 @smallexample
24198 Unsigned_32'Asm_Output ("=r", Flags);
24199 @end smallexample
24200 uses the @code{"r"} (register) constraint, telling the compiler to
24201 store the variable in a register.
24202
24203 If the constraint is preceded by the equal character (@strong{=}), it tells
24204 the compiler that the variable will be used to store data into it.
24205
24206 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
24207 allowing the optimizer to choose whatever it deems best.
24208
24209 There are a fairly large number of constraints, but the ones that are
24210 most useful (for the Intel x86 processor) are the following:
24211
24212 @table @code
24213 @item =
24214 output constraint
24215 @item g
24216 global (i.e. can be stored anywhere)
24217 @item m
24218 in memory
24219 @item I
24220 a constant
24221 @item a
24222 use eax
24223 @item b
24224 use ebx
24225 @item c
24226 use ecx
24227 @item d
24228 use edx
24229 @item S
24230 use esi
24231 @item D
24232 use edi
24233 @item r
24234 use one of eax, ebx, ecx or edx
24235 @item q
24236 use one of eax, ebx, ecx, edx, esi or edi
24237 @end table
24238
24239 The full set of constraints is described in the gcc and @emph{as}
24240 documentation; note that it is possible to combine certain constraints
24241 in one constraint string.
24242
24243 You specify the association of an output variable with an assembler operand
24244 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
24245 integer.  Thus in
24246 @smallexample @c ada
24247 @group
24248 Asm ("pushfl"          & LF & HT & -- push flags on stack
24249      "popl %%eax"      & LF & HT & -- load eax with flags
24250      "movl %%eax, %0",             -- store flags in variable
24251      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24252 @end group
24253 @end smallexample
24254 @noindent
24255 @code{%0} will be replaced in the expanded code by the appropriate operand,
24256 whatever
24257 the compiler decided for the @code{Flags} variable.
24258
24259 In general, you may have any number of output variables:
24260 @itemize @bullet
24261 @item
24262 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
24263 @item
24264 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
24265 of @code{Asm_Output} attributes
24266 @end itemize
24267
24268 For example:
24269 @smallexample @c ada
24270 @group
24271 Asm ("movl %%eax, %0" & LF & HT &
24272      "movl %%ebx, %1" & LF & HT &
24273      "movl %%ecx, %2",
24274      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
24275                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
24276                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
24277 @end group
24278 @end smallexample
24279 @noindent
24280 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
24281 in the Ada program.
24282
24283 As a variation on the @code{Get_Flags} example, we can use the constraints
24284 string to direct the compiler to store the eax register into the @code{Flags}
24285 variable, instead of including the store instruction explicitly in the
24286 @code{Asm} template string:
24287
24288 @smallexample @c ada
24289 @group
24290 with Interfaces; use Interfaces;
24291 with Ada.Text_IO; use Ada.Text_IO;
24292 with System.Machine_Code; use System.Machine_Code;
24293 procedure Get_Flags_2 is
24294    Flags : Unsigned_32;
24295    use ASCII;
24296 begin
24297    Asm ("pushfl"      & LF & HT & -- push flags on stack
24298         "popl %%eax",             -- save flags in eax
24299         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
24300    Put_Line ("Flags register:" & Flags'Img);
24301 end Get_Flags_2;
24302 @end group
24303 @end smallexample
24304
24305 @noindent
24306 The @code{"a"} constraint tells the compiler that the @code{Flags}
24307 variable will come from the eax register. Here is the resulting code:
24308
24309 @smallexample
24310 @group
24311 #APP
24312    pushfl
24313    popl %eax
24314 #NO_APP
24315    movl %eax,-40(%ebp)
24316 @end group
24317 @end smallexample
24318
24319 @noindent
24320 The compiler generated the store of eax into Flags after
24321 expanding the assembler code.
24322
24323 Actually, there was no need to pop the flags into the eax register;
24324 more simply, we could just pop the flags directly into the program variable:
24325
24326 @smallexample @c ada
24327 @group
24328 with Interfaces; use Interfaces;
24329 with Ada.Text_IO; use Ada.Text_IO;
24330 with System.Machine_Code; use System.Machine_Code;
24331 procedure Get_Flags_3 is
24332    Flags : Unsigned_32;
24333    use ASCII;
24334 begin
24335    Asm ("pushfl"  & LF & HT & -- push flags on stack
24336         "pop %0",             -- save flags in Flags
24337         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24338    Put_Line ("Flags register:" & Flags'Img);
24339 end Get_Flags_3;
24340 @end group
24341 @end smallexample
24342
24343 @c ---------------------------------------------------------------------------
24344 @node Input Variables in Inline Assembler
24345 @section Input Variables in Inline Assembler
24346
24347 @noindent
24348 The example in this section illustrates how to specify the source operands
24349 for assembly language statements.
24350 The program simply increments its input value by 1:
24351
24352 @smallexample @c ada
24353 @group
24354 with Interfaces; use Interfaces;
24355 with Ada.Text_IO; use Ada.Text_IO;
24356 with System.Machine_Code; use System.Machine_Code;
24357 procedure Increment is
24358
24359    function Incr (Value : Unsigned_32) return Unsigned_32 is
24360       Result : Unsigned_32;
24361    begin
24362       Asm ("incl %0",
24363            Inputs  => Unsigned_32'Asm_Input ("a", Value),
24364            Outputs => Unsigned_32'Asm_Output ("=a", Result));
24365       return Result;
24366    end Incr;
24367
24368    Value : Unsigned_32;
24369
24370 begin
24371    Value := 5;
24372    Put_Line ("Value before is" & Value'Img);
24373    Value := Incr (Value);
24374    Put_Line ("Value after is" & Value'Img);
24375 end Increment;
24376 @end group
24377 @end smallexample
24378
24379 The @code{Outputs} parameter to @code{Asm} specifies
24380 that the result will be in the eax register and that it is to be stored
24381 in the @code{Result} variable.
24382
24383 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
24384 but with an @code{Asm_Input} attribute.
24385 The @code{"="} constraint, indicating an output value, is not present.
24386
24387 You can have multiple input variables, in the same way that you can have more
24388 than one output variable.
24389
24390 The parameter count (%0, %1) etc, now starts at the first input
24391 statement, and continues with the output statements.
24392 When both parameters use the same variable, the
24393 compiler will treat them as the same %n operand, which is the case here.
24394
24395 Just as the @code{Outputs} parameter causes the register to be stored into the
24396 target variable after execution of the assembler statements, so does the
24397 @code{Inputs} parameter cause its variable to be loaded into the register
24398 before execution of the assembler statements.
24399
24400 Thus the effect of the @code{Asm} invocation is:
24401 @enumerate
24402 @item load the 32-bit value of @code{Value} into eax
24403 @item execute the @code{incl %eax} instruction
24404 @item store the contents of eax into the @code{Result} variable
24405 @end enumerate
24406
24407 The resulting assembler file (with @option{-O2} optimization) contains:
24408 @smallexample
24409 @group
24410 _increment__incr.1:
24411    subl $4,%esp
24412    movl 8(%esp),%eax
24413 #APP
24414    incl %eax
24415 #NO_APP
24416    movl %eax,%edx
24417    movl %ecx,(%esp)
24418    addl $4,%esp
24419    ret
24420 @end group
24421 @end smallexample
24422
24423 @c ---------------------------------------------------------------------------
24424 @node Inlining Inline Assembler Code
24425 @section Inlining Inline Assembler Code
24426
24427 @noindent
24428 For a short subprogram such as the @code{Incr} function in the previous
24429 section, the overhead of the call and return (creating / deleting the stack
24430 frame) can be significant, compared to the amount of code in the subprogram
24431 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
24432 which directs the compiler to expand invocations of the subprogram at the
24433 point(s) of call, instead of setting up a stack frame for out-of-line calls.
24434 Here is the resulting program:
24435
24436 @smallexample @c ada
24437 @group
24438 with Interfaces; use Interfaces;
24439 with Ada.Text_IO; use Ada.Text_IO;
24440 with System.Machine_Code; use System.Machine_Code;
24441 procedure Increment_2 is
24442
24443    function Incr (Value : Unsigned_32) return Unsigned_32 is
24444       Result : Unsigned_32;
24445    begin
24446       Asm ("incl %0",
24447            Inputs  => Unsigned_32'Asm_Input ("a", Value),
24448            Outputs => Unsigned_32'Asm_Output ("=a", Result));
24449       return Result;
24450    end Incr;
24451    pragma Inline (Increment);
24452
24453    Value : Unsigned_32;
24454
24455 begin
24456    Value := 5;
24457    Put_Line ("Value before is" & Value'Img);
24458    Value := Increment (Value);
24459    Put_Line ("Value after is" & Value'Img);
24460 end Increment_2;
24461 @end group
24462 @end smallexample
24463
24464 Compile the program with both optimization (@option{-O2}) and inlining
24465 enabled (@option{-gnatpn} instead of @option{-gnatp}).
24466
24467 The @code{Incr} function is still compiled as usual, but at the
24468 point in @code{Increment} where our function used to be called:
24469
24470 @smallexample
24471 @group
24472 pushl %edi
24473 call _increment__incr.1
24474 @end group
24475 @end smallexample
24476
24477 @noindent
24478 the code for the function body directly appears:
24479
24480 @smallexample
24481 @group
24482 movl %esi,%eax
24483 #APP
24484    incl %eax
24485 #NO_APP
24486    movl %eax,%edx
24487 @end group
24488 @end smallexample
24489
24490 @noindent
24491 thus saving the overhead of stack frame setup and an out-of-line call.
24492
24493 @c ---------------------------------------------------------------------------
24494 @node Other Asm Functionality
24495 @section Other @code{Asm} Functionality
24496
24497 @noindent
24498 This section describes two important parameters to the @code{Asm}
24499 procedure: @code{Clobber}, which identifies register usage;
24500 and @code{Volatile}, which inhibits unwanted optimizations.
24501
24502 @menu
24503 * The Clobber Parameter::
24504 * The Volatile Parameter::
24505 @end menu
24506
24507 @c ---------------------------------------------------------------------------
24508 @node The Clobber Parameter
24509 @subsection The @code{Clobber} Parameter
24510
24511 @noindent
24512 One of the dangers of intermixing assembly language and a compiled language
24513 such as Ada is that the compiler needs to be aware of which registers are
24514 being used by the assembly code.  In some cases, such as the earlier examples,
24515 the constraint string is sufficient to indicate register usage (e.g.,
24516 @code{"a"} for
24517 the eax register).  But more generally, the compiler needs an explicit
24518 identification of the registers that are used by the Inline Assembly
24519 statements.
24520
24521 Using a register that the compiler doesn't know about
24522 could be a side effect of an instruction (like @code{mull}
24523 storing its result in both eax and edx).
24524 It can also arise from explicit register usage in your
24525 assembly code; for example:
24526 @smallexample
24527 @group
24528 Asm ("movl %0, %%ebx" & LF & HT &
24529      "movl %%ebx, %1",
24530      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
24531      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
24532 @end group
24533 @end smallexample
24534 @noindent
24535 where the compiler (since it does not analyze the @code{Asm} template string)
24536 does not know you are using the ebx register.
24537
24538 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
24539 to identify the registers that will be used by your assembly code:
24540
24541 @smallexample
24542 @group
24543 Asm ("movl %0, %%ebx" & LF & HT &
24544      "movl %%ebx, %1",
24545      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
24546      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
24547      Clobber => "ebx");
24548 @end group
24549 @end smallexample
24550
24551 The Clobber parameter is a static string expression specifying the
24552 register(s) you are using.  Note that register names are @emph{not} prefixed
24553 by a percent sign. Also, if more than one register is used then their names
24554 are separated by commas; e.g., @code{"eax, ebx"}
24555
24556 The @code{Clobber} parameter has several additional uses:
24557 @enumerate
24558 @item Use ``register'' name @code{cc} to indicate that flags might have changed
24559 @item Use ``register'' name @code{memory} if you changed a memory location
24560 @end enumerate
24561
24562 @c ---------------------------------------------------------------------------
24563 @node The Volatile Parameter
24564 @subsection The @code{Volatile} Parameter
24565 @cindex Volatile parameter
24566
24567 @noindent
24568 Compiler optimizations in the presence of Inline Assembler may sometimes have
24569 unwanted effects.  For example, when an @code{Asm} invocation with an input
24570 variable is inside a loop, the compiler might move the loading of the input
24571 variable outside the loop, regarding it as a one-time initialization.
24572
24573 If this effect is not desired, you can disable such optimizations by setting
24574 the @code{Volatile} parameter to @code{True}; for example:
24575
24576 @smallexample @c ada
24577 @group
24578 Asm ("movl %0, %%ebx" & LF & HT &
24579      "movl %%ebx, %1",
24580      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
24581      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
24582      Clobber  => "ebx",
24583      Volatile => True);
24584 @end group
24585 @end smallexample
24586
24587 By default, @code{Volatile} is set to @code{False} unless there is no
24588 @code{Outputs} parameter.
24589
24590 Although setting @code{Volatile} to @code{True} prevents unwanted
24591 optimizations, it will also disable other optimizations that might be
24592 important for efficiency. In general, you should set @code{Volatile}
24593 to @code{True} only if the compiler's optimizations have created
24594 problems.
24595
24596 @c ---------------------------------------------------------------------------
24597 @node A Complete Example
24598 @section A Complete Example
24599
24600 @noindent
24601 This section contains a complete program illustrating a realistic usage
24602 of GNAT's Inline Assembler capabilities.  It comprises a main procedure
24603 @code{Check_CPU} and a package @code{Intel_CPU}.
24604 The package declares a collection of functions that detect the properties
24605 of the 32-bit x86 processor that is running the program.
24606 The main procedure invokes these functions and displays the information.
24607
24608 The Intel_CPU package could be enhanced by adding functions to
24609 detect the type of x386 co-processor, the processor caching options and
24610 special operations such as the SIMD extensions.
24611
24612 Although the Intel_CPU package has been written for 32-bit Intel
24613 compatible CPUs, it is OS neutral. It has been tested on DOS,
24614 Windows/NT and GNU/Linux.
24615
24616 @menu
24617 * Check_CPU Procedure::
24618 * Intel_CPU Package Specification::
24619 * Intel_CPU Package Body::
24620 @end menu
24621
24622 @c ---------------------------------------------------------------------------
24623 @node Check_CPU Procedure
24624 @subsection @code{Check_CPU} Procedure
24625 @cindex Check_CPU procedure
24626
24627 @smallexample @c adanocomment
24628 ---------------------------------------------------------------------
24629 --                                                                 --
24630 --  Uses the Intel_CPU package to identify the CPU the program is  --
24631 --  running on, and some of the features it supports.              --
24632 --                                                                 --
24633 ---------------------------------------------------------------------
24634
24635 with Intel_CPU;                     --  Intel CPU detection functions
24636 with Ada.Text_IO;                   --  Standard text I/O
24637 with Ada.Command_Line;              --  To set the exit status
24638
24639 procedure Check_CPU is
24640
24641    Type_Found : Boolean := False;
24642    --  Flag to indicate that processor was identified
24643
24644    Features   : Intel_CPU.Processor_Features;
24645    --  The processor features
24646
24647    Signature  : Intel_CPU.Processor_Signature;
24648    --  The processor type signature
24649
24650 begin
24651
24652    -----------------------------------
24653    --  Display the program banner.  --
24654    -----------------------------------
24655
24656    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
24657                          ": check Intel CPU version and features, v1.0");
24658    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
24659    Ada.Text_IO.New_Line;
24660
24661    -----------------------------------------------------------------------
24662    --  We can safely start with the assumption that we are on at least  --
24663    --  a x386 processor. If the CPUID instruction is present, then we   --
24664    --  have a later processor type.                                     --
24665    -----------------------------------------------------------------------
24666
24667    if Intel_CPU.Has_CPUID = False then
24668
24669       --  No CPUID instruction, so we assume this is indeed a x386
24670       --  processor. We can still check if it has a FP co-processor.
24671       if Intel_CPU.Has_FPU then
24672          Ada.Text_IO.Put_Line
24673            ("x386-type processor with a FP co-processor");
24674       else
24675          Ada.Text_IO.Put_Line
24676            ("x386-type processor without a FP co-processor");
24677       end if;  --  check for FPU
24678
24679       --  Program done
24680       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24681       return;
24682
24683    end if;  --  check for CPUID
24684
24685    -----------------------------------------------------------------------
24686    --  If CPUID is supported, check if this is a true Intel processor,  --
24687    --  if it is not, display a warning.                                 --
24688    -----------------------------------------------------------------------
24689
24690    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
24691       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
24692       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
24693    end if;  --  check if Intel
24694
24695    ----------------------------------------------------------------------
24696    --  With the CPUID instruction present, we can assume at least a    --
24697    --  x486 processor. If the CPUID support level is < 1 then we have  --
24698    --  to leave it at that.                                            --
24699    ----------------------------------------------------------------------
24700
24701    if Intel_CPU.CPUID_Level < 1 then
24702
24703       --  Ok, this is a x486 processor. we still can get the Vendor ID
24704       Ada.Text_IO.Put_Line ("x486-type processor");
24705       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
24706
24707       --  We can also check if there is a FPU present
24708       if Intel_CPU.Has_FPU then
24709          Ada.Text_IO.Put_Line ("Floating-Point support");
24710       else
24711          Ada.Text_IO.Put_Line ("No Floating-Point support");
24712       end if;  --  check for FPU
24713
24714       --  Program done
24715       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24716       return;
24717
24718    end if;  --  check CPUID level
24719
24720    ---------------------------------------------------------------------
24721    --  With a CPUID level of 1 we can use the processor signature to  --
24722    --  determine it's exact type.                                     --
24723    ---------------------------------------------------------------------
24724
24725    Signature := Intel_CPU.Signature;
24726
24727    ----------------------------------------------------------------------
24728    --  Ok, now we go into a lot of messy comparisons to get the        --
24729    --  processor type. For clarity, no attememt to try to optimize the --
24730    --  comparisons has been made. Note that since Intel_CPU does not   --
24731    --  support getting cache info, we cannot distinguish between P5    --
24732    --  and Celeron types yet.                                          --
24733    ----------------------------------------------------------------------
24734
24735    --  x486SL
24736    if Signature.Processor_Type = 2#00#   and
24737      Signature.Family          = 2#0100# and
24738      Signature.Model           = 2#0100# then
24739       Type_Found := True;
24740       Ada.Text_IO.Put_Line ("x486SL processor");
24741    end if;
24742
24743    --  x486DX2 Write-Back
24744    if Signature.Processor_Type = 2#00#   and
24745      Signature.Family          = 2#0100# and
24746      Signature.Model           = 2#0111# then
24747       Type_Found := True;
24748       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
24749    end if;
24750
24751    --  x486DX4
24752    if Signature.Processor_Type = 2#00#   and
24753      Signature.Family          = 2#0100# and
24754      Signature.Model           = 2#1000# then
24755       Type_Found := True;
24756       Ada.Text_IO.Put_Line ("x486DX4 processor");
24757    end if;
24758
24759    --  x486DX4 Overdrive
24760    if Signature.Processor_Type = 2#01#   and
24761      Signature.Family          = 2#0100# and
24762      Signature.Model           = 2#1000# then
24763       Type_Found := True;
24764       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
24765    end if;
24766
24767    --  Pentium (60, 66)
24768    if Signature.Processor_Type = 2#00#   and
24769      Signature.Family          = 2#0101# and
24770      Signature.Model           = 2#0001# then
24771       Type_Found := True;
24772       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
24773    end if;
24774
24775    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
24776    if Signature.Processor_Type = 2#00#   and
24777      Signature.Family          = 2#0101# and
24778      Signature.Model           = 2#0010# then
24779       Type_Found := True;
24780       Ada.Text_IO.Put_Line
24781         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
24782    end if;
24783
24784    --  Pentium OverDrive (60, 66)
24785    if Signature.Processor_Type = 2#01#   and
24786      Signature.Family          = 2#0101# and
24787      Signature.Model           = 2#0001# then
24788       Type_Found := True;
24789       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
24790    end if;
24791
24792    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
24793    if Signature.Processor_Type = 2#01#   and
24794      Signature.Family          = 2#0101# and
24795      Signature.Model           = 2#0010# then
24796       Type_Found := True;
24797       Ada.Text_IO.Put_Line
24798         ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
24799    end if;
24800
24801    --  Pentium OverDrive processor for x486 processor-based systems
24802    if Signature.Processor_Type = 2#01#   and
24803      Signature.Family          = 2#0101# and
24804      Signature.Model           = 2#0011# then
24805       Type_Found := True;
24806       Ada.Text_IO.Put_Line
24807         ("Pentium OverDrive processor for x486 processor-based systems");
24808    end if;
24809
24810    --  Pentium processor with MMX technology (166, 200)
24811    if Signature.Processor_Type = 2#00#   and
24812      Signature.Family          = 2#0101# and
24813      Signature.Model           = 2#0100# then
24814       Type_Found := True;
24815       Ada.Text_IO.Put_Line
24816         ("Pentium processor with MMX technology (166, 200)");
24817    end if;
24818
24819    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
24820    if Signature.Processor_Type = 2#01#   and
24821      Signature.Family          = 2#0101# and
24822      Signature.Model           = 2#0100# then
24823       Type_Found := True;
24824       Ada.Text_IO.Put_Line
24825         ("Pentium OverDrive processor with MMX " &
24826          "technology for Pentium processor (75, 90, 100, 120, 133)");
24827    end if;
24828
24829    --  Pentium Pro processor
24830    if Signature.Processor_Type = 2#00#   and
24831      Signature.Family          = 2#0110# and
24832      Signature.Model           = 2#0001# then
24833       Type_Found := True;
24834       Ada.Text_IO.Put_Line ("Pentium Pro processor");
24835    end if;
24836
24837    --  Pentium II processor, model 3
24838    if Signature.Processor_Type = 2#00#   and
24839      Signature.Family          = 2#0110# and
24840      Signature.Model           = 2#0011# then
24841       Type_Found := True;
24842       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
24843    end if;
24844
24845    --  Pentium II processor, model 5 or Celeron processor
24846    if Signature.Processor_Type = 2#00#   and
24847      Signature.Family          = 2#0110# and
24848      Signature.Model           = 2#0101# then
24849       Type_Found := True;
24850       Ada.Text_IO.Put_Line
24851         ("Pentium II processor, model 5 or Celeron processor");
24852    end if;
24853
24854    --  Pentium Pro OverDrive processor
24855    if Signature.Processor_Type = 2#01#   and
24856      Signature.Family          = 2#0110# and
24857      Signature.Model           = 2#0011# then
24858       Type_Found := True;
24859       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
24860    end if;
24861
24862    --  If no type recognized, we have an unknown. Display what
24863    --  we _do_ know
24864    if Type_Found = False then
24865       Ada.Text_IO.Put_Line ("Unknown processor");
24866    end if;
24867
24868    -----------------------------------------
24869    --  Display processor stepping level.  --
24870    -----------------------------------------
24871
24872    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
24873
24874    ---------------------------------
24875    --  Display vendor ID string.  --
24876    ---------------------------------
24877
24878    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
24879
24880    ------------------------------------
24881    --  Get the processors features.  --
24882    ------------------------------------
24883
24884    Features := Intel_CPU.Features;
24885
24886    -----------------------------
24887    --  Check for a FPU unit.  --
24888    -----------------------------
24889
24890    if Features.FPU = True then
24891       Ada.Text_IO.Put_Line ("Floating-Point unit available");
24892    else
24893       Ada.Text_IO.Put_Line ("no Floating-Point unit");
24894    end if;  --  check for FPU
24895
24896    --------------------------------
24897    --  List processor features.  --
24898    --------------------------------
24899
24900    Ada.Text_IO.Put_Line ("Supported features: ");
24901
24902    --  Virtual Mode Extension
24903    if Features.VME = True then
24904       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
24905    end if;
24906
24907    --  Debugging Extension
24908    if Features.DE = True then
24909       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
24910    end if;
24911
24912    --  Page Size Extension
24913    if Features.PSE = True then
24914       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
24915    end if;
24916
24917    --  Time Stamp Counter
24918    if Features.TSC = True then
24919       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
24920    end if;
24921
24922    --  Model Specific Registers
24923    if Features.MSR = True then
24924       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
24925    end if;
24926
24927    --  Physical Address Extension
24928    if Features.PAE = True then
24929       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
24930    end if;
24931
24932    --  Machine Check Extension
24933    if Features.MCE = True then
24934       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
24935    end if;
24936
24937    --  CMPXCHG8 instruction supported
24938    if Features.CX8 = True then
24939       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
24940    end if;
24941
24942    --  on-chip APIC hardware support
24943    if Features.APIC = True then
24944       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
24945    end if;
24946
24947    --  Fast System Call
24948    if Features.SEP = True then
24949       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
24950    end if;
24951
24952    --  Memory Type Range Registers
24953    if Features.MTRR = True then
24954       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
24955    end if;
24956
24957    --  Page Global Enable
24958    if Features.PGE = True then
24959       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
24960    end if;
24961
24962    --  Machine Check Architecture
24963    if Features.MCA = True then
24964       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
24965    end if;
24966
24967    --  Conditional Move Instruction Supported
24968    if Features.CMOV = True then
24969       Ada.Text_IO.Put_Line
24970         ("    CMOV   - Conditional Move Instruction Supported");
24971    end if;
24972
24973    --  Page Attribute Table
24974    if Features.PAT = True then
24975       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
24976    end if;
24977
24978    --  36-bit Page Size Extension
24979    if Features.PSE_36 = True then
24980       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
24981    end if;
24982
24983    --  MMX technology supported
24984    if Features.MMX = True then
24985       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
24986    end if;
24987
24988    --  Fast FP Save and Restore
24989    if Features.FXSR = True then
24990       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
24991    end if;
24992
24993    ---------------------
24994    --  Program done.  --
24995    ---------------------
24996
24997    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24998
24999 exception
25000
25001    when others =>
25002       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
25003       raise;
25004
25005 end Check_CPU;
25006 @end smallexample
25007
25008 @c ---------------------------------------------------------------------------
25009 @node Intel_CPU Package Specification
25010 @subsection @code{Intel_CPU} Package Specification
25011 @cindex Intel_CPU package specification
25012
25013 @smallexample @c adanocomment
25014 -------------------------------------------------------------------------
25015 --                                                                     --
25016 --  file: intel_cpu.ads                                                --
25017 --                                                                     --
25018 --           *********************************************             --
25019 --           * WARNING: for 32-bit Intel processors only *             --
25020 --           *********************************************             --
25021 --                                                                     --
25022 --  This package contains a number of subprograms that are useful in   --
25023 --  determining the Intel x86 CPU (and the features it supports) on    --
25024 --  which the program is running.                                      --
25025 --                                                                     --
25026 --  The package is based upon the information given in the Intel       --
25027 --  Application Note AP-485: "Intel Processor Identification and the   --
25028 --  CPUID Instruction" as of April 1998. This application note can be  --
25029 --  found on www.intel.com.                                            --
25030 --                                                                     --
25031 --  It currently deals with 32-bit processors only, will not detect    --
25032 --  features added after april 1998, and does not guarantee proper     --
25033 --  results on Intel-compatible processors.                            --
25034 --                                                                     --
25035 --  Cache info and x386 fpu type detection are not supported.          --
25036 --                                                                     --
25037 --  This package does not use any privileged instructions, so should   --
25038 --  work on any OS running on a 32-bit Intel processor.                --
25039 --                                                                     --
25040 -------------------------------------------------------------------------
25041
25042 with Interfaces;             use Interfaces;
25043 --  for using unsigned types
25044
25045 with System.Machine_Code;    use System.Machine_Code;
25046 --  for using inline assembler code
25047
25048 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
25049 --  for inserting control characters
25050
25051 package Intel_CPU is
25052
25053    ----------------------
25054    --  Processor bits  --
25055    ----------------------
25056
25057    subtype Num_Bits is Natural range 0 .. 31;
25058    --  the number of processor bits (32)
25059
25060    --------------------------
25061    --  Processor register  --
25062    --------------------------
25063
25064    --  define a processor register type for easy access to
25065    --  the individual bits
25066
25067    type Processor_Register is array (Num_Bits) of Boolean;
25068    pragma Pack (Processor_Register);
25069    for Processor_Register'Size use 32;
25070
25071    -------------------------
25072    --  Unsigned register  --
25073    -------------------------
25074
25075    --  define a processor register type for easy access to
25076    --  the individual bytes
25077
25078    type Unsigned_Register is
25079       record
25080          L1 : Unsigned_8;
25081          H1 : Unsigned_8;
25082          L2 : Unsigned_8;
25083          H2 : Unsigned_8;
25084       end record;
25085
25086    for Unsigned_Register use
25087       record
25088          L1 at 0 range  0 ..  7;
25089          H1 at 0 range  8 .. 15;
25090          L2 at 0 range 16 .. 23;
25091          H2 at 0 range 24 .. 31;
25092       end record;
25093
25094    for Unsigned_Register'Size use 32;
25095
25096    ---------------------------------
25097    --  Intel processor vendor ID  --
25098    ---------------------------------
25099
25100    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
25101    --  indicates an Intel manufactured processor
25102
25103    ------------------------------------
25104    --  Processor signature register  --
25105    ------------------------------------
25106
25107    --  a register type to hold the processor signature
25108
25109    type Processor_Signature is
25110       record
25111          Stepping       : Natural range 0 .. 15;
25112          Model          : Natural range 0 .. 15;
25113          Family         : Natural range 0 .. 15;
25114          Processor_Type : Natural range 0 .. 3;
25115          Reserved       : Natural range 0 .. 262143;
25116       end record;
25117
25118    for Processor_Signature use
25119       record
25120          Stepping       at 0 range  0 ..  3;
25121          Model          at 0 range  4 ..  7;
25122          Family         at 0 range  8 .. 11;
25123          Processor_Type at 0 range 12 .. 13;
25124          Reserved       at 0 range 14 .. 31;
25125       end record;
25126
25127    for Processor_Signature'Size use 32;
25128
25129    -----------------------------------
25130    --  Processor features register  --
25131    -----------------------------------
25132
25133    --  a processor register to hold the processor feature flags
25134
25135    type Processor_Features is
25136       record
25137          FPU    : Boolean;                --  floating point unit on chip
25138          VME    : Boolean;                --  virtual mode extension
25139          DE     : Boolean;                --  debugging extension
25140          PSE    : Boolean;                --  page size extension
25141          TSC    : Boolean;                --  time stamp counter
25142          MSR    : Boolean;                --  model specific registers
25143          PAE    : Boolean;                --  physical address extension
25144          MCE    : Boolean;                --  machine check extension
25145          CX8    : Boolean;                --  cmpxchg8 instruction
25146          APIC   : Boolean;                --  on-chip apic hardware
25147          Res_1  : Boolean;                --  reserved for extensions
25148          SEP    : Boolean;                --  fast system call
25149          MTRR   : Boolean;                --  memory type range registers
25150          PGE    : Boolean;                --  page global enable
25151          MCA    : Boolean;                --  machine check architecture
25152          CMOV   : Boolean;                --  conditional move supported
25153          PAT    : Boolean;                --  page attribute table
25154          PSE_36 : Boolean;                --  36-bit page size extension
25155          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
25156          MMX    : Boolean;                --  MMX technology supported
25157          FXSR   : Boolean;                --  fast FP save and restore
25158          Res_3  : Natural range 0 .. 127; --  reserved for extensions
25159       end record;
25160
25161    for Processor_Features use
25162       record
25163          FPU    at 0 range  0 ..  0;
25164          VME    at 0 range  1 ..  1;
25165          DE     at 0 range  2 ..  2;
25166          PSE    at 0 range  3 ..  3;
25167          TSC    at 0 range  4 ..  4;
25168          MSR    at 0 range  5 ..  5;
25169          PAE    at 0 range  6 ..  6;
25170          MCE    at 0 range  7 ..  7;
25171          CX8    at 0 range  8 ..  8;
25172          APIC   at 0 range  9 ..  9;
25173          Res_1  at 0 range 10 .. 10;
25174          SEP    at 0 range 11 .. 11;
25175          MTRR   at 0 range 12 .. 12;
25176          PGE    at 0 range 13 .. 13;
25177          MCA    at 0 range 14 .. 14;
25178          CMOV   at 0 range 15 .. 15;
25179          PAT    at 0 range 16 .. 16;
25180          PSE_36 at 0 range 17 .. 17;
25181          Res_2  at 0 range 18 .. 22;
25182          MMX    at 0 range 23 .. 23;
25183          FXSR   at 0 range 24 .. 24;
25184          Res_3  at 0 range 25 .. 31;
25185       end record;
25186
25187    for Processor_Features'Size use 32;
25188
25189    -------------------
25190    --  Subprograms  --
25191    -------------------
25192
25193    function Has_FPU return Boolean;
25194    --  return True if a FPU is found
25195    --  use only if CPUID is not supported
25196
25197    function Has_CPUID return Boolean;
25198    --  return True if the processor supports the CPUID instruction
25199
25200    function CPUID_Level return Natural;
25201    --  return the CPUID support level (0, 1 or 2)
25202    --  can only be called if the CPUID instruction is supported
25203
25204    function Vendor_ID return String;
25205    --  return the processor vendor identification string
25206    --  can only be called if the CPUID instruction is supported
25207
25208    function Signature return Processor_Signature;
25209    --  return the processor signature
25210    --  can only be called if the CPUID instruction is supported
25211
25212    function Features return Processor_Features;
25213    --  return the processors features
25214    --  can only be called if the CPUID instruction is supported
25215
25216 private
25217
25218    ------------------------
25219    --  EFLAGS bit names  --
25220    ------------------------
25221
25222    ID_Flag : constant Num_Bits := 21;
25223    --  ID flag bit
25224
25225 end Intel_CPU;
25226 @end smallexample
25227
25228 @c ---------------------------------------------------------------------------
25229 @node Intel_CPU Package Body
25230 @subsection @code{Intel_CPU} Package Body
25231 @cindex Intel_CPU package body
25232
25233 @smallexample @c adanocomment
25234 package body Intel_CPU is
25235
25236    ---------------------------
25237    --  Detect FPU presence  --
25238    ---------------------------
25239
25240    --  There is a FPU present if we can set values to the FPU Status
25241    --  and Control Words.
25242
25243    function Has_FPU return Boolean is
25244
25245       Register : Unsigned_16;
25246       --  processor register to store a word
25247
25248    begin
25249
25250       --  check if we can change the status word
25251       Asm (
25252
25253            --  the assembler code
25254            "finit"              & LF & HT &    --  reset status word
25255            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
25256            "fnstsw %0"          & LF & HT &    --  save status word
25257            "movw %%ax, %0",                    --  store status word
25258
25259            --  output stored in Register
25260            --  register must be a memory location
25261            Outputs => Unsigned_16'Asm_output ("=m", Register),
25262
25263            --  tell compiler that we used eax
25264            Clobber => "eax");
25265
25266       --  if the status word is zero, there is no FPU
25267       if Register = 0 then
25268          return False;   --  no status word
25269       end if;  --  check status word value
25270
25271       --  check if we can get the control word
25272       Asm (
25273
25274            --  the assembler code
25275            "fnstcw %0",   --  save the control word
25276
25277            --  output into Register
25278            --  register must be a memory location
25279            Outputs => Unsigned_16'Asm_output ("=m", Register));
25280
25281       --  check the relevant bits
25282       if (Register and 16#103F#) /= 16#003F# then
25283          return False;   --  no control word
25284       end if;  --  check control word value
25285
25286       --  FPU found
25287       return True;
25288
25289    end Has_FPU;
25290
25291    --------------------------------
25292    --  Detect CPUID instruction  --
25293    --------------------------------
25294
25295    --  The processor supports the CPUID instruction if it is possible
25296    --  to change the value of ID flag bit in the EFLAGS register.
25297
25298    function Has_CPUID return Boolean is
25299
25300       Original_Flags, Modified_Flags : Processor_Register;
25301       --  EFLAG contents before and after changing the ID flag
25302
25303    begin
25304
25305       --  try flipping the ID flag in the EFLAGS register
25306       Asm (
25307
25308            --  the assembler code
25309            "pushfl"               & LF & HT &     --  push EFLAGS on stack
25310            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
25311            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
25312            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
25313            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
25314            "popfl"                & LF & HT &     --  load EFLAGS register
25315            "pushfl"               & LF & HT &     --  push EFLAGS on stack
25316            "pop %1",                              --  save EFLAGS content
25317
25318            --  output values, may be anything
25319            --  Original_Flags is %0
25320            --  Modified_Flags is %1
25321            Outputs =>
25322               (Processor_Register'Asm_output ("=g", Original_Flags),
25323                Processor_Register'Asm_output ("=g", Modified_Flags)),
25324
25325            --  tell compiler eax is destroyed
25326            Clobber => "eax");
25327
25328       --  check if CPUID is supported
25329       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
25330          return True;   --  ID flag was modified
25331       else
25332          return False;  --  ID flag unchanged
25333       end if;  --  check for CPUID
25334
25335    end Has_CPUID;
25336
25337    -------------------------------
25338    --  Get CPUID support level  --
25339    -------------------------------
25340
25341    function CPUID_Level return Natural is
25342
25343       Level : Unsigned_32;
25344       --  returned support level
25345
25346    begin
25347
25348       --  execute CPUID, storing the results in the Level register
25349       Asm (
25350
25351            --  the assembler code
25352            "cpuid",    --  execute CPUID
25353
25354            --  zero is stored in eax
25355            --  returning the support level in eax
25356            Inputs => Unsigned_32'Asm_input ("a", 0),
25357
25358            --  eax is stored in Level
25359            Outputs => Unsigned_32'Asm_output ("=a", Level),
25360
25361            --  tell compiler ebx, ecx and edx registers are destroyed
25362            Clobber => "ebx, ecx, edx");
25363
25364       --  return the support level
25365       return Natural (Level);
25366
25367    end CPUID_Level;
25368
25369    --------------------------------
25370    --  Get CPU Vendor ID String  --
25371    --------------------------------
25372
25373    --  The vendor ID string is returned in the ebx, ecx and edx register
25374    --  after executing the CPUID instruction with eax set to zero.
25375    --  In case of a true Intel processor the string returned is
25376    --  "GenuineIntel"
25377
25378    function Vendor_ID return String is
25379
25380       Ebx, Ecx, Edx : Unsigned_Register;
25381       --  registers containing the vendor ID string
25382
25383       Vendor_ID : String (1 .. 12);
25384       -- the vendor ID string
25385
25386    begin
25387
25388       --  execute CPUID, storing the results in the processor registers
25389       Asm (
25390
25391            --  the assembler code
25392            "cpuid",    --  execute CPUID
25393
25394            --  zero stored in eax
25395            --  vendor ID string returned in ebx, ecx and edx
25396            Inputs => Unsigned_32'Asm_input ("a", 0),
25397
25398            --  ebx is stored in Ebx
25399            --  ecx is stored in Ecx
25400            --  edx is stored in Edx
25401            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
25402                        Unsigned_Register'Asm_output ("=c", Ecx),
25403                        Unsigned_Register'Asm_output ("=d", Edx)));
25404
25405       --  now build the vendor ID string
25406       Vendor_ID( 1) := Character'Val (Ebx.L1);
25407       Vendor_ID( 2) := Character'Val (Ebx.H1);
25408       Vendor_ID( 3) := Character'Val (Ebx.L2);
25409       Vendor_ID( 4) := Character'Val (Ebx.H2);
25410       Vendor_ID( 5) := Character'Val (Edx.L1);
25411       Vendor_ID( 6) := Character'Val (Edx.H1);
25412       Vendor_ID( 7) := Character'Val (Edx.L2);
25413       Vendor_ID( 8) := Character'Val (Edx.H2);
25414       Vendor_ID( 9) := Character'Val (Ecx.L1);
25415       Vendor_ID(10) := Character'Val (Ecx.H1);
25416       Vendor_ID(11) := Character'Val (Ecx.L2);
25417       Vendor_ID(12) := Character'Val (Ecx.H2);
25418
25419       --  return string
25420       return Vendor_ID;
25421
25422    end Vendor_ID;
25423
25424    -------------------------------
25425    --  Get processor signature  --
25426    -------------------------------
25427
25428    function Signature return Processor_Signature is
25429
25430       Result : Processor_Signature;
25431       --  processor signature returned
25432
25433    begin
25434
25435       --  execute CPUID, storing the results in the Result variable
25436       Asm (
25437
25438            --  the assembler code
25439            "cpuid",    --  execute CPUID
25440
25441            --  one is stored in eax
25442            --  processor signature returned in eax
25443            Inputs => Unsigned_32'Asm_input ("a", 1),
25444
25445            --  eax is stored in Result
25446            Outputs => Processor_Signature'Asm_output ("=a", Result),
25447
25448            --  tell compiler that ebx, ecx and edx are also destroyed
25449            Clobber => "ebx, ecx, edx");
25450
25451       --  return processor signature
25452       return Result;
25453
25454    end Signature;
25455
25456    ------------------------------
25457    --  Get processor features  --
25458    ------------------------------
25459
25460    function Features return Processor_Features is
25461
25462       Result : Processor_Features;
25463       --  processor features returned
25464
25465    begin
25466
25467       --  execute CPUID, storing the results in the Result variable
25468       Asm (
25469
25470            --  the assembler code
25471            "cpuid",    --  execute CPUID
25472
25473            --  one stored in eax
25474            --  processor features returned in edx
25475            Inputs => Unsigned_32'Asm_input ("a", 1),
25476
25477            --  edx is stored in Result
25478            Outputs => Processor_Features'Asm_output ("=d", Result),
25479
25480            --  tell compiler that ebx and ecx are also destroyed
25481            Clobber => "ebx, ecx");
25482
25483       --  return processor signature
25484       return Result;
25485
25486    end Features;
25487
25488 end Intel_CPU;
25489 @end smallexample
25490 @c END OF INLINE ASSEMBLER CHAPTER
25491 @c ===============================
25492
25493
25494
25495 @c ***********************************
25496 @c * Compatibility and Porting Guide *
25497 @c ***********************************
25498 @node Compatibility and Porting Guide
25499 @appendix Compatibility and Porting Guide
25500
25501 @noindent
25502 This chapter describes the compatibility issues that may arise between
25503 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
25504 can expedite porting
25505 applications developed in other Ada environments.
25506
25507 @menu
25508 * Compatibility with Ada 83::
25509 * Implementation-dependent characteristics::
25510 * Compatibility with DEC Ada 83::
25511 * Compatibility with Other Ada 95 Systems::
25512 * Representation Clauses::
25513 @end menu
25514
25515 @node Compatibility with Ada 83
25516 @section Compatibility with Ada 83
25517 @cindex Compatibility (between Ada 83 and Ada 95)
25518
25519 @noindent
25520 Ada 95 is designed to be highly upwards compatible with Ada 83.  In
25521 particular, the design intention is that the difficulties associated
25522 with moving from Ada 83 to Ada 95 should be no greater than those
25523 that occur when moving from one Ada 83 system to another.
25524
25525 However, there are a number of points at which there are minor
25526 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25527 full details of these issues,
25528 and should be consulted for a complete treatment.
25529 In practice the
25530 following subsections treat the most likely issues to be encountered.
25531
25532 @menu
25533 * Legal Ada 83 programs that are illegal in Ada 95::
25534 * More deterministic semantics::
25535 * Changed semantics::
25536 * Other language compatibility issues::
25537 @end menu
25538
25539 @node Legal Ada 83 programs that are illegal in Ada 95
25540 @subsection Legal Ada 83 programs that are illegal in Ada 95
25541
25542 @table @asis
25543 @item Character literals
25544 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25545 @code{Wide_Character} as a new predefined character type, some uses of
25546 character literals that were legal in Ada 83 are illegal in Ada 95.
25547 For example:
25548 @smallexample @c ada
25549    for Char in 'A' .. 'Z' loop ... end loop;
25550 @end smallexample
25551 @noindent
25552 The problem is that @code{'A'} and @code{'Z'} could be from either
25553 @code{Character} or @code{Wide_Character}.  The simplest correction
25554 is to make the type explicit; e.g.:
25555 @smallexample @c ada
25556    for Char in Character range 'A' .. 'Z' loop ... end loop;
25557 @end smallexample
25558
25559 @item New reserved words
25560 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25561 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25562 Existing Ada 83 code using any of these identifiers must be edited to
25563 use some alternative name.
25564
25565 @item Freezing rules
25566 The rules in Ada 95 are slightly different with regard to the point at
25567 which entities are frozen, and representation pragmas and clauses are
25568 not permitted past the freeze point.  This shows up most typically in
25569 the form of an error message complaining that a representation item
25570 appears too late, and the appropriate corrective action is to move
25571 the item nearer to the declaration of the entity to which it refers.
25572
25573 A particular case is that representation pragmas
25574 @ifset vms
25575 (including the
25576 extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure})
25577 @end ifset
25578 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25579 declaration must be introduced to which the pragma can be applied.
25580
25581 @item Optional bodies for library packages
25582 In Ada 83, a package that did not require a package body was nevertheless
25583 allowed to have one.  This lead to certain surprises in compiling large
25584 systems (situations in which the body could be unexpectedly ignored by the
25585 binder).  In Ada 95, if a package does not require a body then it is not
25586 permitted to have a body.  To fix this problem, simply remove a redundant
25587 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25588 into the spec that makes the body required.  One approach is to add a private
25589 part to the package declaration (if necessary), and define a parameterless
25590 procedure called @code{Requires_Body}, which must then be given a dummy
25591 procedure body in the package body, which then becomes required.
25592 Another approach (assuming that this does not introduce elaboration
25593 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25594 since one effect of this pragma is to require the presence of a package body.
25595
25596 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25597 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25598 @code{Constraint_Error}.
25599 This means that it is illegal to have separate exception handlers for
25600 the two exceptions.  The fix is simply to remove the handler for the
25601 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25602 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25603
25604 @item Indefinite subtypes in generics
25605 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25606 as the actual for a generic formal private type, but then the instantiation
25607 would be illegal if there were any instances of declarations of variables
25608 of this type in the generic body.  In Ada 95, to avoid this clear violation
25609 of the methodological principle known as the ``contract model'',
25610 the generic declaration explicitly indicates whether
25611 or not such instantiations are permitted.  If a generic formal parameter
25612 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25613 type name, then it can be instantiated with indefinite types, but no
25614 stand-alone variables can be declared of this type.  Any attempt to declare
25615 such a variable will result in an illegality at the time the generic is
25616 declared.  If the @code{(<>)} notation is not used, then it is illegal
25617 to instantiate the generic with an indefinite type.
25618 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25619 It will show up as a compile time error, and
25620 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25621 @end table
25622
25623 @node More deterministic semantics
25624 @subsection More deterministic semantics
25625
25626 @table @asis
25627 @item Conversions
25628 Conversions from real types to integer types round away from 0.  In Ada 83
25629 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
25630 implementation freedom was intended to support unbiased rounding in
25631 statistical applications, but in practice it interfered with portability.
25632 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25633 is required.  Numeric code may be affected by this change in semantics.
25634 Note, though, that this issue is no worse than already existed in Ada 83
25635 when porting code from one vendor to another.
25636
25637 @item Tasking
25638 The Real-Time Annex introduces a set of policies that define the behavior of
25639 features that were implementation dependent in Ada 83, such as the order in
25640 which open select branches are executed.
25641 @end table
25642
25643 @node Changed semantics
25644 @subsection Changed semantics
25645
25646 @noindent
25647 The worst kind of incompatibility is one where a program that is legal in
25648 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25649 possible in Ada 83.  Fortunately this is extremely rare, but the one
25650 situation that you should be alert to is the change in the predefined type
25651 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25652
25653 @table @asis
25654 @item range of @code{Character}
25655 The range of @code{Standard.Character} is now the full 256 characters
25656 of Latin-1, whereas in most Ada 83 implementations it was restricted
25657 to 128 characters. Although some of the effects of
25658 this change will be manifest in compile-time rejection of legal
25659 Ada 83 programs it is possible for a working Ada 83 program to have
25660 a different effect in Ada 95, one that was not permitted in Ada 83.
25661 As an example, the expression
25662 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25663 delivers @code{255} as its value.
25664 In general, you should look at the logic of any
25665 character-processing Ada 83 program and see whether it needs to be adapted
25666 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
25667 character handling package that may be relevant if code needs to be adapted
25668 to account for the additional Latin-1 elements.
25669 The desirable fix is to
25670 modify the program to accommodate the full character set, but in some cases
25671 it may be convenient to define a subtype or derived type of Character that
25672 covers only the restricted range.
25673 @cindex Latin-1
25674 @end table
25675
25676 @node Other language compatibility issues
25677 @subsection Other language compatibility issues
25678 @table @asis
25679 @item @option{-gnat83 switch}
25680 All implementations of GNAT provide a switch that causes GNAT to operate
25681 in Ada 83 mode.  In this mode, some but not all compatibility problems
25682 of the type described above are handled automatically.  For example, the
25683 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
25684 However,
25685 in practice, it is usually advisable to make the necessary modifications
25686 to the program to remove the need for using this switch.
25687 See @ref{Compiling Ada 83 Programs}.
25688
25689 @item Support for removed Ada 83 pragmas and attributes
25690 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
25691 generally because they have been replaced by other mechanisms.  Ada 95
25692 compilers are allowed, but not required, to implement these missing
25693 elements.  In contrast with some other Ada 95 compilers, GNAT implements all
25694 such pragmas and attributes, eliminating this compatibility concern.  These
25695 include @code{pragma Interface} and the floating point type attributes
25696 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25697 @end table
25698
25699
25700 @node Implementation-dependent characteristics
25701 @section Implementation-dependent characteristics
25702 @noindent
25703 Although the Ada language defines the semantics of each construct as
25704 precisely as practical, in some situations (for example for reasons of
25705 efficiency, or where the effect is heavily dependent on the host or target
25706 platform) the implementation is allowed some freedom.  In porting Ada 83
25707 code to GNAT, you need to be aware of whether / how the existing code
25708 exercised such implementation dependencies.  Such characteristics fall into
25709 several categories, and GNAT offers specific support in assisting the
25710 transition from certain Ada 83 compilers.
25711
25712 @menu
25713 * Implementation-defined pragmas::
25714 * Implementation-defined attributes::
25715 * Libraries::
25716 * Elaboration order::
25717 * Target-specific aspects::
25718 @end menu
25719
25720
25721 @node Implementation-defined pragmas
25722 @subsection Implementation-defined pragmas
25723
25724 @noindent
25725 Ada compilers are allowed to supplement the language-defined pragmas, and
25726 these are a potential source of non-portability.  All GNAT-defined pragmas
25727 are described in the GNAT Reference Manual, and these include several that
25728 are specifically intended to correspond to other vendors' Ada 83 pragmas.
25729 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25730 For
25731 compatibility with DEC Ada 83, GNAT supplies the pragmas
25732 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25733 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25734 and @code{Volatile}.
25735 Other relevant pragmas include @code{External} and @code{Link_With}.
25736 Some vendor-specific
25737 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25738 recognized, thus
25739 avoiding compiler rejection of units that contain such pragmas; they are not
25740 relevant in a GNAT context and hence are not otherwise implemented.
25741
25742 @node Implementation-defined attributes
25743 @subsection Implementation-defined attributes
25744
25745 Analogous to pragmas, the set of attributes may be extended by an
25746 implementation.  All GNAT-defined attributes are described in the
25747 @cite{GNAT Reference Manual}, and these include several that are specifically
25748 intended
25749 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
25750 the attribute @code{VADS_Size} may be useful.  For compatibility with DEC
25751 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25752 @code{Type_Class}.
25753
25754 @node Libraries
25755 @subsection Libraries
25756 @noindent
25757 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
25758 code uses vendor-specific libraries then there are several ways to manage
25759 this in Ada 95:
25760 @enumerate
25761 @item
25762 If the source code for the libraries (specifications and bodies) are
25763 available, then the libraries can be migrated in the same way as the
25764 application.
25765 @item
25766 If the source code for the specifications but not the bodies are
25767 available, then you can reimplement the bodies.
25768 @item
25769 Some new Ada 95 features obviate the need for library support.  For
25770 example most Ada 83 vendors supplied a package for unsigned integers.  The
25771 Ada 95 modular type feature is the preferred way to handle this need, so
25772 instead of migrating or reimplementing the unsigned integer package it may
25773 be preferable to retrofit the application using modular types.
25774 @end enumerate
25775
25776 @node Elaboration order
25777 @subsection Elaboration order
25778 @noindent
25779 The implementation can choose any elaboration order consistent with the unit
25780 dependency relationship.  This freedom means that some orders can result in
25781 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25782 to invoke a subprogram its body has been elaborated, or to instantiate a
25783 generic before the generic body has been elaborated.  By default GNAT
25784 attempts to choose a safe order (one that will not encounter access before
25785 elaboration problems) by implicitly inserting Elaborate_All pragmas where
25786 needed.  However, this can lead to the creation of elaboration circularities
25787 and a resulting rejection of the program by gnatbind.  This issue is
25788 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25789 In brief, there are several
25790 ways to deal with this situation:
25791
25792 @itemize @bullet
25793 @item
25794 Modify the program to eliminate the circularities, e.g. by moving
25795 elaboration-time code into explicitly-invoked procedures
25796 @item
25797 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25798 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25799 @code{Elaborate_All}
25800 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25801 (by selectively suppressing elaboration checks via pragma
25802 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25803 @end itemize
25804
25805 @node Target-specific aspects
25806 @subsection Target-specific aspects
25807 @noindent
25808 Low-level applications need to deal with machine addresses, data
25809 representations, interfacing with assembler code, and similar issues.  If
25810 such an Ada 83 application is being ported to different target hardware (for
25811 example where the byte endianness has changed) then you will need to
25812 carefully examine the program logic; the porting effort will heavily depend
25813 on the robustness of the original design.  Moreover, Ada 95 is sometimes
25814 incompatible with typical Ada 83 compiler practices regarding implicit
25815 packing, the meaning of the Size attribute, and the size of access values.
25816 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25817
25818
25819 @node Compatibility with Other Ada 95 Systems
25820 @section Compatibility with Other Ada 95 Systems
25821
25822 @noindent
25823 Providing that programs avoid the use of implementation dependent and
25824 implementation defined features of Ada 95, as documented in the Ada 95
25825 reference manual, there should be a high degree of portability between
25826 GNAT and other Ada 95 systems.  The following are specific items which
25827 have proved troublesome in moving GNAT programs to other Ada 95
25828 compilers, but do not affect porting code to GNAT@.
25829
25830 @table @asis
25831 @item Ada 83 Pragmas and Attributes
25832 Ada 95 compilers are allowed, but not required, to implement the missing
25833 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25834 GNAT implements all such pragmas and attributes, eliminating this as
25835 a compatibility concern, but some other Ada 95 compilers reject these
25836 pragmas and attributes.
25837
25838 @item Special-needs Annexes
25839 GNAT implements the full set of special needs annexes.  At the
25840 current time, it is the only Ada 95 compiler to do so.  This means that
25841 programs making use of these features may not be portable to other Ada
25842 95 compilation systems.
25843
25844 @item Representation Clauses
25845 Some other Ada 95 compilers implement only the minimal set of
25846 representation clauses required by the Ada 95 reference manual.  GNAT goes
25847 far beyond this minimal set, as described in the next section.
25848 @end table
25849
25850 @node Representation Clauses
25851 @section Representation Clauses
25852
25853 @noindent
25854 The Ada 83 reference manual was quite vague in describing both the minimal
25855 required implementation of representation clauses, and also their precise
25856 effects.  The Ada 95 reference manual is much more explicit, but the minimal
25857 set of capabilities required in Ada 95 is quite limited.
25858
25859 GNAT implements the full required set of capabilities described in the
25860 Ada 95 reference manual, but also goes much beyond this, and in particular
25861 an effort has been made to be compatible with existing Ada 83 usage to the
25862 greatest extent possible.
25863
25864 A few cases exist in which Ada 83 compiler behavior is incompatible with
25865 requirements in the Ada 95 reference manual.  These are instances of
25866 intentional or accidental dependence on specific implementation dependent
25867 characteristics of these Ada 83 compilers.  The following is a list of
25868 the cases most likely to arise in existing legacy Ada 83 code.
25869
25870 @table @asis
25871 @item Implicit Packing
25872 Some Ada 83 compilers allowed a Size specification to cause implicit
25873 packing of an array or record.  This could cause expensive implicit
25874 conversions for change of representation in the presence of derived
25875 types, and the Ada design intends to avoid this possibility.
25876 Subsequent AI's were issued to make it clear that such implicit
25877 change of representation in response to a Size clause is inadvisable,
25878 and this recommendation is represented explicitly in the Ada 95 RM
25879 as implementation advice that is followed by GNAT@.
25880 The problem will show up as an error
25881 message rejecting the size clause.  The fix is simply to provide
25882 the explicit pragma @code{Pack}, or for more fine tuned control, provide
25883 a Component_Size clause.
25884
25885 @item Meaning of Size Attribute
25886 The Size attribute in Ada 95 for discrete types is defined as being the
25887 minimal number of bits required to hold values of the type.  For example,
25888 on a 32-bit machine, the size of Natural will typically be 31 and not
25889 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
25890 some 32 in this situation.  This problem will usually show up as a compile
25891 time error, but not always.  It is a good idea to check all uses of the
25892 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
25893 Object_Size can provide a useful way of duplicating the behavior of
25894 some Ada 83 compiler systems.
25895
25896 @item Size of Access Types
25897 A common assumption in Ada 83 code is that an access type is in fact a pointer,
25898 and that therefore it will be the same size as a System.Address value.  This
25899 assumption is true for GNAT in most cases with one exception.  For the case of
25900 a pointer to an unconstrained array type (where the bounds may vary from one
25901 value of the access type to another), the default is to use a ``fat pointer'',
25902 which is represented as two separate pointers, one to the bounds, and one to
25903 the array.  This representation has a number of advantages, including improved
25904 efficiency.  However, it may cause some difficulties in porting existing Ada 83
25905 code which makes the assumption that, for example, pointers fit in 32 bits on
25906 a machine with 32-bit addressing.
25907
25908 To get around this problem, GNAT also permits the use of ``thin pointers'' for
25909 access types in this case (where the designated type is an unconstrained array
25910 type).  These thin pointers are indeed the same size as a System.Address value.
25911 To specify a thin pointer, use a size clause for the type, for example:
25912
25913 @smallexample @c ada
25914 type X is access all String;
25915 for X'Size use Standard'Address_Size;
25916 @end smallexample
25917
25918 @noindent
25919 which will cause the type X to be represented using a single pointer.
25920 When using this representation, the bounds are right behind the array.
25921 This representation is slightly less efficient, and does not allow quite
25922 such flexibility in the use of foreign pointers or in using the
25923 Unrestricted_Access attribute to create pointers to non-aliased objects.
25924 But for any standard portable use of the access type it will work in
25925 a functionally correct manner and allow porting of existing code.
25926 Note that another way of forcing a thin pointer representation
25927 is to use a component size clause for the element size in an array,
25928 or a record representation clause for an access field in a record.
25929 @end table
25930
25931 @node Compatibility with DEC Ada 83
25932 @section Compatibility with DEC Ada 83
25933
25934 @noindent
25935 The VMS version of GNAT fully implements all the pragmas and attributes
25936 provided by DEC Ada 83, as well as providing the standard DEC Ada 83
25937 libraries, including Starlet.  In addition, data layouts and parameter
25938 passing conventions are highly compatible.  This means that porting
25939 existing DEC Ada 83 code to GNAT in VMS systems should be easier than
25940 most other porting efforts.  The following are some of the most
25941 significant differences between GNAT and DEC Ada 83.
25942
25943 @table @asis
25944 @item Default floating-point representation
25945 In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83,
25946 it is VMS format.  GNAT does implement the necessary pragmas
25947 (Long_Float, Float_Representation) for changing this default.
25948
25949 @item System
25950 The package System in GNAT exactly corresponds to the definition in the
25951 Ada 95 reference manual, which means that it excludes many of the
25952 DEC Ada 83 extensions.  However, a separate package Aux_DEC is provided
25953 that contains the additional definitions, and a special pragma,
25954 Extend_System allows this package to be treated transparently as an
25955 extension of package System.
25956
25957 @item To_Address
25958 The definitions provided by Aux_DEC are exactly compatible with those
25959 in the DEC Ada 83 version of System, with one exception.
25960 DEC Ada provides the following declarations:
25961
25962 @smallexample @c ada
25963 TO_ADDRESS (INTEGER)
25964 TO_ADDRESS (UNSIGNED_LONGWORD)
25965 TO_ADDRESS (universal_integer)
25966 @end smallexample
25967
25968 @noindent
25969 The version of TO_ADDRESS taking a universal integer argument is in fact
25970 an extension to Ada 83 not strictly compatible with the reference manual.
25971 In GNAT, we are constrained to be exactly compatible with the standard,
25972 and this means we cannot provide this capability.  In DEC Ada 83, the
25973 point of this definition is to deal with a call like:
25974
25975 @smallexample @c ada
25976 TO_ADDRESS (16#12777#);
25977 @end smallexample
25978
25979 @noindent
25980 Normally, according to the Ada 83 standard, one would expect this to be
25981 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
25982 of TO_ADDRESS@.  However, in DEC Ada 83, there is no ambiguity, since the
25983 definition using universal_integer takes precedence.
25984
25985 In GNAT, since the version with universal_integer cannot be supplied, it is
25986 not possible to be 100% compatible.  Since there are many programs using
25987 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
25988 to change the name of the function in the UNSIGNED_LONGWORD case, so the
25989 declarations provided in the GNAT version of AUX_Dec are:
25990
25991 @smallexample @c ada
25992 function To_Address (X : Integer) return Address;
25993 pragma Pure_Function (To_Address);
25994
25995 function To_Address_Long (X : Unsigned_Longword)
25996  return Address;
25997 pragma Pure_Function (To_Address_Long);
25998 @end smallexample
25999
26000 @noindent
26001 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26002 change the name to TO_ADDRESS_LONG@.
26003
26004 @item Task_Id values
26005 The Task_Id values assigned will be different in the two systems, and GNAT
26006 does not provide a specified value for the Task_Id of the environment task,
26007 which in GNAT is treated like any other declared task.
26008 @end table
26009
26010 For full details on these and other less significant compatibility issues,
26011 see appendix E of the Digital publication entitled @cite{DEC Ada, Technical
26012 Overview and Comparison on DIGITAL Platforms}.
26013
26014 For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and
26015 attributes are recognized, although only a subset of them can sensibly
26016 be implemented.  The description of pragmas in this reference manual
26017 indicates whether or not they are applicable to non-VMS systems.
26018
26019
26020
26021 @ifset unw
26022 @node Microsoft Windows Topics
26023 @appendix Microsoft Windows Topics
26024 @cindex Windows NT
26025 @cindex Windows 95
26026 @cindex Windows 98
26027
26028 @noindent
26029 This chapter describes topics that are specific to the Microsoft Windows
26030 platforms (NT, 2000, and XP Professional).
26031
26032 @menu
26033 * Using GNAT on Windows::
26034 * Using a network installation of GNAT::
26035 * CONSOLE and WINDOWS subsystems::
26036 * Temporary Files::
26037 * Mixed-Language Programming on Windows::
26038 * Windows Calling Conventions::
26039 * Introduction to Dynamic Link Libraries (DLLs)::
26040 * Using DLLs with GNAT::
26041 * Building DLLs with GNAT::
26042 * GNAT and Windows Resources::
26043 * Debugging a DLL::
26044 * GNAT and COM/DCOM Objects::
26045 @end menu
26046
26047 @node Using GNAT on Windows
26048 @section Using GNAT on Windows
26049
26050 @noindent
26051 One of the strengths of the GNAT technology is that its tool set
26052 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
26053 @code{gdb} debugger, etc.) is used in the same way regardless of the
26054 platform.
26055
26056 On Windows this tool set is complemented by a number of Microsoft-specific
26057 tools that have been provided to facilitate interoperability with Windows
26058 when this is required. With these tools:
26059
26060 @itemize @bullet
26061
26062 @item
26063 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26064 subsystems.
26065
26066 @item
26067 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26068 relocatable and non-relocatable DLLs are supported).
26069
26070 @item
26071 You can build Ada DLLs for use in other applications. These applications
26072 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26073 relocatable and non-relocatable Ada DLLs are supported.
26074
26075 @item
26076 You can include Windows resources in your Ada application.
26077
26078 @item
26079 You can use or create COM/DCOM objects.
26080 @end itemize
26081
26082 @noindent
26083 Immediately below are listed all known general GNAT-for-Windows restrictions.
26084 Other restrictions about specific features like Windows Resources and DLLs
26085 are listed in separate sections below.
26086
26087 @itemize @bullet
26088
26089 @item
26090 It is not possible to use @code{GetLastError} and @code{SetLastError}
26091 when tasking, protected records, or exceptions are used. In these
26092 cases, in order to implement Ada semantics, the GNAT run-time system
26093 calls certain Win32 routines that set the last error variable to 0 upon
26094 success. It should be possible to use @code{GetLastError} and
26095 @code{SetLastError} when tasking, protected record, and exception
26096 features are not used, but it is not guaranteed to work.
26097
26098 @item
26099 It is not possible to link against Microsoft libraries except for
26100 import libraries. The library must be built to be compatible with
26101 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
26102 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
26103 not be compatible with the GNAT runtime. Even if the library is
26104 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
26105
26106 @item
26107 When the compilation environment is located on FAT32 drives, users may
26108 experience recompilations of the source files that have not changed if
26109 Daylight Saving Time (DST) state has changed since the last time files
26110 were compiled. NTFS drives do not have this problem.
26111
26112 @item
26113 No components of the GNAT toolset use any entries in the Windows
26114 registry. The only entries that can be created are file associations and
26115 PATH settings, provided the user has chosen to create them at installation
26116 time, as well as some minimal book-keeping information needed to correctly
26117 uninstall or integrate different GNAT products.
26118 @end itemize
26119
26120 @node Using a network installation of GNAT
26121 @section Using a network installation of GNAT
26122
26123 @noindent
26124 Make sure the system on which GNAT is installed is accessible from the
26125 current machine, i.e. the install location is shared over the network.
26126 Shared resources are accessed on Windows by means of UNC paths, which
26127 have the format @code{\\server\sharename\path}
26128
26129 In order to use such a network installation, simply add the UNC path of the
26130 @file{bin} directory of your GNAT installation in front of your PATH. For
26131 example, if GNAT is installed in @file{\GNAT} directory of a share location
26132 called @file{c-drive} on a machine @file{LOKI}, the following command will
26133 make it available:
26134
26135 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26136
26137 Be aware that every compilation using the network installation results in the
26138 transfer of large amounts of data across the network and will likely cause
26139 serious performance penalty.
26140
26141 @node CONSOLE and WINDOWS subsystems
26142 @section CONSOLE and WINDOWS subsystems
26143 @cindex CONSOLE Subsystem
26144 @cindex WINDOWS Subsystem
26145 @cindex -mwindows
26146
26147 @noindent
26148 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26149 (which is the default subsystem) will always create a console when
26150 launching the application. This is not something desirable when the
26151 application has a Windows GUI. To get rid of this console the
26152 application must be using the @code{WINDOWS} subsystem. To do so
26153 the @option{-mwindows} linker option must be specified.
26154
26155 @smallexample
26156 $ gnatmake winprog -largs -mwindows
26157 @end smallexample
26158
26159 @node Temporary Files
26160 @section Temporary Files
26161 @cindex Temporary files
26162
26163 @noindent
26164 It is possible to control where temporary files gets created by setting
26165 the TMP environment variable. The file will be created:
26166
26167 @itemize
26168 @item Under the directory pointed to by the TMP environment variable if
26169 this directory exists.
26170
26171 @item Under c:\temp, if the TMP environment variable is not set (or not
26172 pointing to a directory) and if this directory exists.
26173
26174 @item Under the current working directory otherwise.
26175 @end itemize
26176
26177 @noindent
26178 This allows you to determine exactly where the temporary
26179 file will be created. This is particularly useful in networked
26180 environments where you may not have write access to some
26181 directories.
26182
26183 @node Mixed-Language Programming on Windows
26184 @section Mixed-Language Programming on Windows
26185
26186 @noindent
26187 Developing pure Ada applications on Windows is no different than on
26188 other GNAT-supported platforms. However, when developing or porting an
26189 application that contains a mix of Ada and C/C++, the choice of your
26190 Windows C/C++ development environment conditions your overall
26191 interoperability strategy.
26192
26193 If you use @code{gcc} to compile the non-Ada part of your application,
26194 there are no Windows-specific restrictions that affect the overall
26195 interoperability with your Ada code. If you plan to use
26196 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
26197 the following limitations:
26198
26199 @itemize @bullet
26200 @item
26201 You cannot link your Ada code with an object or library generated with
26202 Microsoft tools if these use the @code{.tls} section (Thread Local
26203 Storage section) since the GNAT linker does not yet support this section.
26204
26205 @item
26206 You cannot link your Ada code with an object or library generated with
26207 Microsoft tools if these use I/O routines other than those provided in
26208 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
26209 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
26210 libraries can cause a conflict with @code{msvcrt.dll} services. For
26211 instance Visual C++ I/O stream routines conflict with those in
26212 @code{msvcrt.dll}.
26213 @end itemize
26214
26215 @noindent
26216 If you do want to use the Microsoft tools for your non-Ada code and hit one
26217 of the above limitations, you have two choices:
26218
26219 @enumerate
26220 @item
26221 Encapsulate your non Ada code in a DLL to be linked with your Ada
26222 application. In this case, use the Microsoft or whatever environment to
26223 build the DLL and use GNAT to build your executable
26224 (@pxref{Using DLLs with GNAT}).
26225
26226 @item
26227 Or you can encapsulate your Ada code in a DLL to be linked with the
26228 other part of your application. In this case, use GNAT to build the DLL
26229 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
26230 environment to build your executable.
26231 @end enumerate
26232
26233 @node Windows Calling Conventions
26234 @section Windows Calling Conventions
26235 @findex Stdcall
26236 @findex APIENTRY
26237
26238 @menu
26239 * C Calling Convention::
26240 * Stdcall Calling Convention::
26241 * DLL Calling Convention::
26242 @end menu
26243
26244 @noindent
26245 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26246 (callee), there are several ways to push @code{G}'s parameters on the
26247 stack and there are several possible scenarios to clean up the stack
26248 upon @code{G}'s return. A calling convention is an agreed upon software
26249 protocol whereby the responsibilities between the caller (@code{F}) and
26250 the callee (@code{G}) are clearly defined. Several calling conventions
26251 are available for Windows:
26252
26253 @itemize @bullet
26254 @item
26255 @code{C} (Microsoft defined)
26256
26257 @item
26258 @code{Stdcall} (Microsoft defined)
26259
26260 @item
26261 @code{DLL} (GNAT specific)
26262 @end itemize
26263
26264 @node C Calling Convention
26265 @subsection @code{C} Calling Convention
26266
26267 @noindent
26268 This is the default calling convention used when interfacing to C/C++
26269 routines compiled with either @code{gcc} or Microsoft Visual C++.
26270
26271 In the @code{C} calling convention subprogram parameters are pushed on the
26272 stack by the caller from right to left. The caller itself is in charge of
26273 cleaning up the stack after the call. In addition, the name of a routine
26274 with @code{C} calling convention is mangled by adding a leading underscore.
26275
26276 The name to use on the Ada side when importing (or exporting) a routine
26277 with @code{C} calling convention is the name of the routine. For
26278 instance the C function:
26279
26280 @smallexample
26281 int get_val (long);
26282 @end smallexample
26283
26284 @noindent
26285 should be imported from Ada as follows:
26286
26287 @smallexample @c ada
26288 @group
26289 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26290 pragma Import (C, Get_Val, External_Name => "get_val");
26291 @end group
26292 @end smallexample
26293
26294 @noindent
26295 Note that in this particular case the @code{External_Name} parameter could
26296 have been omitted since, when missing, this parameter is taken to be the
26297 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26298 is missing, as in the above example, this parameter is set to be the
26299 @code{External_Name} with a leading underscore.
26300
26301 When importing a variable defined in C, you should always use the @code{C}
26302 calling convention unless the object containing the variable is part of a
26303 DLL (in which case you should use the @code{DLL} calling convention,
26304 @pxref{DLL Calling Convention}).
26305
26306 @node Stdcall Calling Convention
26307 @subsection @code{Stdcall} Calling Convention
26308
26309 @noindent
26310 This convention, which was the calling convention used for Pascal
26311 programs, is used by Microsoft for all the routines in the Win32 API for
26312 efficiency reasons. It must be used to import any routine for which this
26313 convention was specified.
26314
26315 In the @code{Stdcall} calling convention subprogram parameters are pushed
26316 on the stack by the caller from right to left. The callee (and not the
26317 caller) is in charge of cleaning the stack on routine exit. In addition,
26318 the name of a routine with @code{Stdcall} calling convention is mangled by
26319 adding a leading underscore (as for the @code{C} calling convention) and a
26320 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
26321 bytes) of the parameters passed to the routine.
26322
26323 The name to use on the Ada side when importing a C routine with a
26324 @code{Stdcall} calling convention is the name of the C routine. The leading
26325 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
26326 the compiler. For instance the Win32 function:
26327
26328 @smallexample
26329 @b{APIENTRY} int get_val (long);
26330 @end smallexample
26331
26332 @noindent
26333 should be imported from Ada as follows:
26334
26335 @smallexample @c ada
26336 @group
26337 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26338 pragma Import (Stdcall, Get_Val);
26339 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26340 @end group
26341 @end smallexample
26342
26343 @noindent
26344 As for the @code{C} calling convention, when the @code{External_Name}
26345 parameter is missing, it is taken to be the name of the Ada entity in lower
26346 case. If instead of writing the above import pragma you write:
26347
26348 @smallexample @c ada
26349 @group
26350 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26351 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26352 @end group
26353 @end smallexample
26354
26355 @noindent
26356 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26357 of specifying the @code{External_Name} parameter you specify the
26358 @code{Link_Name} as in the following example:
26359
26360 @smallexample @c ada
26361 @group
26362 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26363 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26364 @end group
26365 @end smallexample
26366
26367 @noindent
26368 then the imported routine is @code{retrieve_val@@4}, that is, there is no
26369 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
26370 added at the end of the @code{Link_Name} by the compiler.
26371
26372 @noindent
26373 Note, that in some special cases a DLL's entry point name lacks a trailing
26374 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
26375 The @code{gnatdll} tool, which creates the import library for the DLL, is able
26376 to handle those cases (see the description of the switches in
26377 @pxref{Using gnatdll} section).
26378
26379 @node DLL Calling Convention
26380 @subsection @code{DLL} Calling Convention
26381
26382 @noindent
26383 This convention, which is GNAT-specific, must be used when you want to
26384 import in Ada a variables defined in a DLL. For functions and procedures
26385 this convention is equivalent to the @code{Stdcall} convention. As an
26386 example, if a DLL contains a variable defined as:
26387
26388 @smallexample
26389 int my_var;
26390 @end smallexample
26391
26392 @noindent
26393 then, to access this variable from Ada you should write:
26394
26395 @smallexample @c ada
26396 @group
26397 My_Var : Interfaces.C.int;
26398 pragma Import (DLL, My_Var);
26399 @end group
26400 @end smallexample
26401
26402 The remarks concerning the @code{External_Name} and @code{Link_Name}
26403 parameters given in the previous sections equally apply to the @code{DLL}
26404 calling convention.
26405
26406 @node Introduction to Dynamic Link Libraries (DLLs)
26407 @section Introduction to Dynamic Link Libraries (DLLs)
26408 @findex DLL
26409
26410 @noindent
26411 A Dynamically Linked Library (DLL) is a library that can be shared by
26412 several applications running under Windows. A DLL can contain any number of
26413 routines and variables.
26414
26415 One advantage of DLLs is that you can change and enhance them without
26416 forcing all the applications that depend on them to be relinked or
26417 recompiled. However, you should be aware than all calls to DLL routines are
26418 slower since, as you will understand below, such calls are indirect.
26419
26420 To illustrate the remainder of this section, suppose that an application
26421 wants to use the services of a DLL @file{API.dll}. To use the services
26422 provided by @file{API.dll} you must statically link against an import
26423 library which contains a jump table with an entry for each routine and
26424 variable exported by the DLL. In the Microsoft world this import library is
26425 called @file{API.lib}. When using GNAT this import library is called either
26426 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
26427
26428 After you have statically linked your application with the import library
26429 and you run your application, here is what happens:
26430
26431 @enumerate
26432 @item
26433 Your application is loaded into memory.
26434
26435 @item
26436 The DLL @file{API.dll} is mapped into the address space of your
26437 application. This means that:
26438
26439 @itemize @bullet
26440 @item
26441 The DLL will use the stack of the calling thread.
26442
26443 @item
26444 The DLL will use the virtual address space of the calling process.
26445
26446 @item
26447 The DLL will allocate memory from the virtual address space of the calling
26448 process.
26449
26450 @item
26451 Handles (pointers) can be safely exchanged between routines in the DLL
26452 routines and routines in the application using the DLL.
26453 @end itemize
26454
26455 @item
26456 The entries in the @file{libAPI.a} or @file{API.lib} jump table which is
26457 part of your application are initialized with the addresses of the routines
26458 and variables in @file{API.dll}.
26459
26460 @item
26461 If present in @file{API.dll}, routines @code{DllMain} or
26462 @code{DllMainCRTStartup} are invoked. These routines typically contain
26463 the initialization code needed for the well-being of the routines and
26464 variables exported by the DLL.
26465 @end enumerate
26466
26467 @noindent
26468 There is an additional point which is worth mentioning. In the Windows
26469 world there are two kind of DLLs: relocatable and non-relocatable
26470 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
26471 in the target application address space. If the addresses of two
26472 non-relocatable DLLs overlap and these happen to be used by the same
26473 application, a conflict will occur and the application will run
26474 incorrectly. Hence, when possible, it is always preferable to use and
26475 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
26476 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
26477 User's Guide) removes the debugging symbols from the DLL but the DLL can
26478 still be relocated.
26479
26480 As a side note, an interesting difference between Microsoft DLLs and
26481 Unix shared libraries, is the fact that on most Unix systems all public
26482 routines are exported by default in a Unix shared library, while under
26483 Windows the exported routines must be listed explicitly in a definition
26484 file (@pxref{The Definition File}).
26485
26486 @node Using DLLs with GNAT
26487 @section Using DLLs with GNAT
26488
26489 @menu
26490 * Creating an Ada Spec for the DLL Services::
26491 * Creating an Import Library::
26492 @end menu
26493
26494 @noindent
26495 To use the services of a DLL, say @file{API.dll}, in your Ada application
26496 you must have:
26497
26498 @enumerate
26499 @item
26500 The Ada spec for the routines and/or variables you want to access in
26501 @file{API.dll}. If not available this Ada spec must be built from the C/C++
26502 header files provided with the DLL.
26503
26504 @item
26505 The import library (@file{libAPI.a} or @file{API.lib}). As previously
26506 mentioned an import library is a statically linked library containing the
26507 import table which will be filled at load time to point to the actual
26508 @file{API.dll} routines. Sometimes you don't have an import library for the
26509 DLL you want to use. The following sections will explain how to build one.
26510
26511 @item
26512 The actual DLL, @file{API.dll}.
26513 @end enumerate
26514
26515 @noindent
26516 Once you have all the above, to compile an Ada application that uses the
26517 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
26518 you simply issue the command
26519
26520 @smallexample
26521 $ gnatmake my_ada_app -largs -lAPI
26522 @end smallexample
26523
26524 @noindent
26525 The argument @option{-largs -lAPI} at the end of the @code{gnatmake} command
26526 tells the GNAT linker to look first for a library named @file{API.lib}
26527 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
26528 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
26529 contains the following pragma
26530
26531 @smallexample @c ada
26532 pragma Linker_Options ("-lAPI");
26533 @end smallexample
26534
26535 @noindent
26536 you do not have to add @option{-largs -lAPI} at the end of the @code{gnatmake}
26537 command.
26538
26539 If any one of the items above is missing you will have to create it
26540 yourself. The following sections explain how to do so using as an
26541 example a fictitious DLL called @file{API.dll}.
26542
26543 @node Creating an Ada Spec for the DLL Services
26544 @subsection Creating an Ada Spec for the DLL Services
26545
26546 @noindent
26547 A DLL typically comes with a C/C++ header file which provides the
26548 definitions of the routines and variables exported by the DLL. The Ada
26549 equivalent of this header file is a package spec that contains definitions
26550 for the imported entities. If the DLL you intend to use does not come with
26551 an Ada spec you have to generate one such spec yourself. For example if
26552 the header file of @file{API.dll} is a file @file{api.h} containing the
26553 following two definitions:
26554
26555 @smallexample
26556 @group
26557 @cartouche
26558 int some_var;
26559 int get (char *);
26560 @end cartouche
26561 @end group
26562 @end smallexample
26563
26564 @noindent
26565 then the equivalent Ada spec could be:
26566
26567 @smallexample @c ada
26568 @group
26569 @cartouche
26570 with Interfaces.C.Strings;
26571 package API is
26572    use Interfaces;
26573
26574    Some_Var : C.int;
26575    function Get (Str : C.Strings.Chars_Ptr) return C.int;
26576
26577 private
26578    pragma Import (C, Get);
26579    pragma Import (DLL, Some_Var);
26580 end API;
26581 @end cartouche
26582 @end group
26583 @end smallexample
26584
26585 @noindent
26586 Note that a variable is @strong{always imported with a DLL convention}. A
26587 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
26588 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
26589 (@pxref{Windows Calling Conventions}).
26590
26591 @node Creating an Import Library
26592 @subsection Creating an Import Library
26593 @cindex Import library
26594
26595 @menu
26596 * The Definition File::
26597 * GNAT-Style Import Library::
26598 * Microsoft-Style Import Library::
26599 @end menu
26600
26601 @noindent
26602 If a Microsoft-style import library @file{API.lib} or a GNAT-style
26603 import library @file{libAPI.a} is available with @file{API.dll} you
26604 can skip this section. Otherwise read on.
26605
26606 @node The Definition File
26607 @subsubsection The Definition File
26608 @cindex Definition file
26609 @findex .def
26610
26611 @noindent
26612 As previously mentioned, and unlike Unix systems, the list of symbols
26613 that are exported from a DLL must be provided explicitly in Windows.
26614 The main goal of a definition file is precisely that: list the symbols
26615 exported by a DLL. A definition file (usually a file with a @code{.def}
26616 suffix) has the following structure:
26617
26618 @smallexample
26619 @group
26620 @cartouche
26621 [LIBRARY @i{name}]
26622 [DESCRIPTION @i{string}]
26623 EXPORTS
26624    @i{symbol1}
26625    @i{symbol2}
26626    ...
26627 @end cartouche
26628 @end group
26629 @end smallexample
26630
26631 @table @code
26632 @item LIBRARY @i{name}
26633 This section, which is optional, gives the name of the DLL.
26634
26635 @item DESCRIPTION @i{string}
26636 This section, which is optional, gives a description string that will be
26637 embedded in the import library.
26638
26639 @item EXPORTS
26640 This section gives the list of exported symbols (procedures, functions or
26641 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
26642 section of @file{API.def} looks like:
26643
26644 @smallexample
26645 @group
26646 @cartouche
26647 EXPORTS
26648    some_var
26649    get
26650 @end cartouche
26651 @end group
26652 @end smallexample
26653 @end table
26654
26655 @noindent
26656 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
26657 (@pxref{Windows Calling Conventions}) for a Stdcall
26658 calling convention function in the exported symbols list.
26659
26660 @noindent
26661 There can actually be other sections in a definition file, but these
26662 sections are not relevant to the discussion at hand.
26663
26664 @node GNAT-Style Import Library
26665 @subsubsection GNAT-Style Import Library
26666
26667 @noindent
26668 To create a static import library from @file{API.dll} with the GNAT tools
26669 you should proceed as follows:
26670
26671 @enumerate
26672 @item
26673 Create the definition file @file{API.def} (@pxref{The Definition File}).
26674 For that use the @code{dll2def} tool as follows:
26675
26676 @smallexample
26677 $ dll2def API.dll > API.def
26678 @end smallexample
26679
26680 @noindent
26681 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
26682 to standard output the list of entry points in the DLL. Note that if
26683 some routines in the DLL have the @code{Stdcall} convention
26684 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
26685 suffix then you'll have to edit @file{api.def} to add it.
26686
26687 @noindent
26688 Here are some hints to find the right @code{@@}@i{nn} suffix.
26689
26690 @enumerate
26691 @item
26692 If you have the Microsoft import library (.lib), it is possible to get
26693 the right symbols by using Microsoft @code{dumpbin} tool (see the
26694 corresponding Microsoft documentation for further details).
26695
26696 @smallexample
26697 $ dumpbin /exports api.lib
26698 @end smallexample
26699
26700 @item
26701 If you have a message about a missing symbol at link time the compiler
26702 tells you what symbol is expected. You just have to go back to the
26703 definition file and add the right suffix.
26704 @end enumerate
26705
26706 @item
26707 Build the import library @code{libAPI.a}, using @code{gnatdll}
26708 (@pxref{Using gnatdll}) as follows:
26709
26710 @smallexample
26711 $ gnatdll -e API.def -d API.dll
26712 @end smallexample
26713
26714 @noindent
26715 @code{gnatdll} takes as input a definition file @file{API.def} and the
26716 name of the DLL containing the services listed in the definition file
26717 @file{API.dll}. The name of the static import library generated is
26718 computed from the name of the definition file as follows: if the
26719 definition file name is @i{xyz}@code{.def}, the import library name will
26720 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
26721 @option{-e} could have been removed because the name of the definition
26722 file (before the ``@code{.def}'' suffix) is the same as the name of the
26723 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
26724 @end enumerate
26725
26726 @node Microsoft-Style Import Library
26727 @subsubsection Microsoft-Style Import Library
26728
26729 @noindent
26730 With GNAT you can either use a GNAT-style or Microsoft-style import
26731 library. A Microsoft import library is needed only if you plan to make an
26732 Ada DLL available to applications developed with Microsoft
26733 tools (@pxref{Mixed-Language Programming on Windows}).
26734
26735 To create a Microsoft-style import library for @file{API.dll} you
26736 should proceed as follows:
26737
26738 @enumerate
26739 @item
26740 Create the definition file @file{API.def} from the DLL. For this use either
26741 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
26742 tool (see the corresponding Microsoft documentation for further details).
26743
26744 @item
26745 Build the actual import library using Microsoft's @code{lib} utility:
26746
26747 @smallexample
26748 $ lib -machine:IX86 -def:API.def -out:API.lib
26749 @end smallexample
26750
26751 @noindent
26752 If you use the above command the definition file @file{API.def} must
26753 contain a line giving the name of the DLL:
26754
26755 @smallexample
26756 LIBRARY      "API"
26757 @end smallexample
26758
26759 @noindent
26760 See the Microsoft documentation for further details about the usage of
26761 @code{lib}.
26762 @end enumerate
26763
26764 @node Building DLLs with GNAT
26765 @section Building DLLs with GNAT
26766 @cindex DLLs, building
26767
26768 @menu
26769 * Limitations When Using Ada DLLs from Ada::
26770 * Exporting Ada Entities::
26771 * Ada DLLs and Elaboration::
26772 * Ada DLLs and Finalization::
26773 * Creating a Spec for Ada DLLs::
26774 * Creating the Definition File::
26775 * Using gnatdll::
26776 @end menu
26777
26778 @noindent
26779 This section explains how to build DLLs containing Ada code. These DLLs
26780 will be referred to as Ada DLLs in the remainder of this section.
26781
26782 The steps required to build an Ada DLL that is to be used by Ada as well as
26783 non-Ada applications are as follows:
26784
26785 @enumerate
26786 @item
26787 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
26788 @code{Stdcall} calling convention to avoid any Ada name mangling for the
26789 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
26790 skip this step if you plan to use the Ada DLL only from Ada applications.
26791
26792 @item
26793 Your Ada code must export an initialization routine which calls the routine
26794 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
26795 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
26796 routine exported by the Ada DLL must be invoked by the clients of the DLL
26797 to initialize the DLL.
26798
26799 @item
26800 When useful, the DLL should also export a finalization routine which calls
26801 routine @code{adafinal} generated by @code{gnatbind} to perform the
26802 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
26803 The finalization routine exported by the Ada DLL must be invoked by the
26804 clients of the DLL when the DLL services are no further needed.
26805
26806 @item
26807 You must provide a spec for the services exported by the Ada DLL in each
26808 of the programming languages to which you plan to make the DLL available.
26809
26810 @item
26811 You must provide a definition file listing the exported entities
26812 (@pxref{The Definition File}).
26813
26814 @item
26815 Finally you must use @code{gnatdll} to produce the DLL and the import
26816 library (@pxref{Using gnatdll}).
26817 @end enumerate
26818
26819 @noindent
26820 Note that a relocatable DLL stripped using the @code{strip} binutils
26821 tool will not be relocatable anymore. To build a DLL without debug
26822 information pass @code{-largs -s} to @code{gnatdll}.
26823
26824 @node Limitations When Using Ada DLLs from Ada
26825 @subsection Limitations When Using Ada DLLs from Ada
26826
26827 @noindent
26828 When using Ada DLLs from Ada applications there is a limitation users
26829 should be aware of. Because on Windows the GNAT run time is not in a DLL of
26830 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
26831 each Ada DLL includes the services of the GNAT run time that are necessary
26832 to the Ada code inside the DLL. As a result, when an Ada program uses an
26833 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
26834 one in the main program.
26835
26836 It is therefore not possible to exchange GNAT run-time objects between the
26837 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
26838 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
26839 types, etc.
26840
26841 It is completely safe to exchange plain elementary, array or record types,
26842 Windows object handles, etc.
26843
26844 @node Exporting Ada Entities
26845 @subsection Exporting Ada Entities
26846 @cindex Export table
26847
26848 @noindent
26849 Building a DLL is a way to encapsulate a set of services usable from any
26850 application. As a result, the Ada entities exported by a DLL should be
26851 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
26852 any Ada name mangling. Please note that the @code{Stdcall} convention
26853 should only be used for subprograms, not for variables. As an example here
26854 is an Ada package @code{API}, spec and body, exporting two procedures, a
26855 function, and a variable:
26856
26857 @smallexample @c ada
26858 @group
26859 @cartouche
26860 with Interfaces.C; use Interfaces;
26861 package API is
26862    Count : C.int := 0;
26863    function Factorial (Val : C.int) return C.int;
26864
26865    procedure Initialize_API;
26866    procedure Finalize_API;
26867    --  Initialization & Finalization routines. More in the next section.
26868 private
26869    pragma Export (C, Initialize_API);
26870    pragma Export (C, Finalize_API);
26871    pragma Export (C, Count);
26872    pragma Export (C, Factorial);
26873 end API;
26874 @end cartouche
26875 @end group
26876 @end smallexample
26877
26878 @smallexample @c ada
26879 @group
26880 @cartouche
26881 package body API is
26882    function Factorial (Val : C.int) return C.int is
26883       Fact : C.int := 1;
26884    begin
26885       Count := Count + 1;
26886       for K in 1 .. Val loop
26887          Fact := Fact * K;
26888       end loop;
26889       return Fact;
26890    end Factorial;
26891
26892    procedure Initialize_API is
26893       procedure Adainit;
26894       pragma Import (C, Adainit);
26895    begin
26896       Adainit;
26897    end Initialize_API;
26898
26899    procedure Finalize_API is
26900       procedure Adafinal;
26901       pragma Import (C, Adafinal);
26902    begin
26903       Adafinal;
26904    end Finalize_API;
26905 end API;
26906 @end cartouche
26907 @end group
26908 @end smallexample
26909
26910 @noindent
26911 If the Ada DLL you are building will only be used by Ada applications
26912 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
26913 convention. As an example, the previous package could be written as
26914 follows:
26915
26916 @smallexample @c ada
26917 @group
26918 @cartouche
26919 package API is
26920    Count : Integer := 0;
26921    function Factorial (Val : Integer) return Integer;
26922
26923    procedure Initialize_API;
26924    procedure Finalize_API;
26925    --  Initialization and Finalization routines.
26926 end API;
26927 @end cartouche
26928 @end group
26929 @end smallexample
26930
26931 @smallexample @c ada
26932 @group
26933 @cartouche
26934 package body API is
26935    function Factorial (Val : Integer) return Integer is
26936       Fact : Integer := 1;
26937    begin
26938       Count := Count + 1;
26939       for K in 1 .. Val loop
26940          Fact := Fact * K;
26941       end loop;
26942       return Fact;
26943    end Factorial;
26944
26945    ...
26946    --  The remainder of this package body is unchanged.
26947 end API;
26948 @end cartouche
26949 @end group
26950 @end smallexample
26951
26952 @noindent
26953 Note that if you do not export the Ada entities with a @code{C} or
26954 @code{Stdcall} convention you will have to provide the mangled Ada names
26955 in the definition file of the Ada DLL
26956 (@pxref{Creating the Definition File}).
26957
26958 @node Ada DLLs and Elaboration
26959 @subsection Ada DLLs and Elaboration
26960 @cindex DLLs and elaboration
26961
26962 @noindent
26963 The DLL that you are building contains your Ada code as well as all the
26964 routines in the Ada library that are needed by it. The first thing a
26965 user of your DLL must do is elaborate the Ada code
26966 (@pxref{Elaboration Order Handling in GNAT}).
26967
26968 To achieve this you must export an initialization routine
26969 (@code{Initialize_API} in the previous example), which must be invoked
26970 before using any of the DLL services. This elaboration routine must call
26971 the Ada elaboration routine @code{adainit} generated by the GNAT binder
26972 (@pxref{Binding with Non-Ada Main Programs}). See the body of
26973 @code{Initialize_Api} for an example. Note that the GNAT binder is
26974 automatically invoked during the DLL build process by the @code{gnatdll}
26975 tool (@pxref{Using gnatdll}).
26976
26977 When a DLL is loaded, Windows systematically invokes a routine called
26978 @code{DllMain}. It would therefore be possible to call @code{adainit}
26979 directly from @code{DllMain} without having to provide an explicit
26980 initialization routine. Unfortunately, it is not possible to call
26981 @code{adainit} from the @code{DllMain} if your program has library level
26982 tasks because access to the @code{DllMain} entry point is serialized by
26983 the system (that is, only a single thread can execute ``through'' it at a
26984 time), which means that the GNAT run time will deadlock waiting for the
26985 newly created task to complete its initialization.
26986
26987 @node Ada DLLs and Finalization
26988 @subsection Ada DLLs and Finalization
26989 @cindex DLLs and finalization
26990
26991 @noindent
26992 When the services of an Ada DLL are no longer needed, the client code should
26993 invoke the DLL finalization routine, if available. The DLL finalization
26994 routine is in charge of releasing all resources acquired by the DLL. In the
26995 case of the Ada code contained in the DLL, this is achieved by calling
26996 routine @code{adafinal} generated by the GNAT binder
26997 (@pxref{Binding with Non-Ada Main Programs}).
26998 See the body of @code{Finalize_Api} for an
26999 example. As already pointed out the GNAT binder is automatically invoked
27000 during the DLL build process by the @code{gnatdll} tool
27001 (@pxref{Using gnatdll}).
27002
27003 @node Creating a Spec for Ada DLLs
27004 @subsection Creating a Spec for Ada DLLs
27005
27006 @noindent
27007 To use the services exported by the Ada DLL from another programming
27008 language (e.g. C), you have to translate the specs of the exported Ada
27009 entities in that language. For instance in the case of @code{API.dll},
27010 the corresponding C header file could look like:
27011
27012 @smallexample
27013 @group
27014 @cartouche
27015 extern int *_imp__count;
27016 #define count (*_imp__count)
27017 int factorial (int);
27018 @end cartouche
27019 @end group
27020 @end smallexample
27021
27022 @noindent
27023 It is important to understand that when building an Ada DLL to be used by
27024 other Ada applications, you need two different specs for the packages
27025 contained in the DLL: one for building the DLL and the other for using
27026 the DLL. This is because the @code{DLL} calling convention is needed to
27027 use a variable defined in a DLL, but when building the DLL, the variable
27028 must have either the @code{Ada} or @code{C} calling convention. As an
27029 example consider a DLL comprising the following package @code{API}:
27030
27031 @smallexample @c ada
27032 @group
27033 @cartouche
27034 package API is
27035    Count : Integer := 0;
27036    ...
27037    --  Remainder of the package omitted.
27038 end API;
27039 @end cartouche
27040 @end group
27041 @end smallexample
27042
27043 @noindent
27044 After producing a DLL containing package @code{API}, the spec that
27045 must be used to import @code{API.Count} from Ada code outside of the
27046 DLL is:
27047
27048 @smallexample @c ada
27049 @group
27050 @cartouche
27051 package API is
27052    Count : Integer;
27053    pragma Import (DLL, Count);
27054 end API;
27055 @end cartouche
27056 @end group
27057 @end smallexample
27058
27059 @node Creating the Definition File
27060 @subsection Creating the Definition File
27061
27062 @noindent
27063 The definition file is the last file needed to build the DLL. It lists
27064 the exported symbols. As an example, the definition file for a DLL
27065 containing only package @code{API} (where all the entities are exported
27066 with a @code{C} calling convention) is:
27067
27068 @smallexample
27069 @group
27070 @cartouche
27071 EXPORTS
27072     count
27073     factorial
27074     finalize_api
27075     initialize_api
27076 @end cartouche
27077 @end group
27078 @end smallexample
27079
27080 @noindent
27081 If the @code{C} calling convention is missing from package @code{API},
27082 then the definition file contains the mangled Ada names of the above
27083 entities, which in this case are:
27084
27085 @smallexample
27086 @group
27087 @cartouche
27088 EXPORTS
27089     api__count
27090     api__factorial
27091     api__finalize_api
27092     api__initialize_api
27093 @end cartouche
27094 @end group
27095 @end smallexample
27096
27097 @node Using gnatdll
27098 @subsection Using @code{gnatdll}
27099 @findex gnatdll
27100
27101 @menu
27102 * gnatdll Example::
27103 * gnatdll behind the Scenes::
27104 * Using dlltool::
27105 @end menu
27106
27107 @noindent
27108 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
27109 and non-Ada sources that make up your DLL have been compiled.
27110 @code{gnatdll} is actually in charge of two distinct tasks: build the
27111 static import library for the DLL and the actual DLL. The form of the
27112 @code{gnatdll} command is
27113
27114 @smallexample
27115 @cartouche
27116 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
27117 @end cartouche
27118 @end smallexample
27119
27120 @noindent
27121 where @i{list-of-files} is a list of ALI and object files. The object
27122 file list must be the exact list of objects corresponding to the non-Ada
27123 sources whose services are to be included in the DLL. The ALI file list
27124 must be the exact list of ALI files for the corresponding Ada sources
27125 whose services are to be included in the DLL. If @i{list-of-files} is
27126 missing, only the static import library is generated.
27127
27128 @noindent
27129 You may specify any of the following switches to @code{gnatdll}:
27130
27131 @table @code
27132 @item -a[@var{address}]
27133 @cindex @option{-a} (@code{gnatdll})
27134 Build a non-relocatable DLL at @var{address}. If @var{address} is not
27135 specified the default address @var{0x11000000} will be used. By default,
27136 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
27137 advise the reader to build relocatable DLL.
27138
27139 @item -b @var{address}
27140 @cindex @option{-b} (@code{gnatdll})
27141 Set the relocatable DLL base address. By default the address is
27142 @var{0x11000000}.
27143
27144 @item -bargs @var{opts}
27145 @cindex @option{-bargs} (@code{gnatdll})
27146 Binder options. Pass @var{opts} to the binder.
27147
27148 @item -d @var{dllfile}
27149 @cindex @option{-d} (@code{gnatdll})
27150 @var{dllfile} is the name of the DLL. This switch must be present for
27151 @code{gnatdll} to do anything. The name of the generated import library is
27152 obtained algorithmically from @var{dllfile} as shown in the following
27153 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
27154 @code{libxyz.a}. The name of the definition file to use (if not specified
27155 by option @option{-e}) is obtained algorithmically from @var{dllfile}
27156 as shown in the following example:
27157 if @var{dllfile} is @code{xyz.dll}, the definition
27158 file used is @code{xyz.def}.
27159
27160 @item -e @var{deffile}
27161 @cindex @option{-e} (@code{gnatdll})
27162 @var{deffile} is the name of the definition file.
27163
27164 @item -g
27165 @cindex @option{-g} (@code{gnatdll})
27166 Generate debugging information. This information is stored in the object
27167 file and copied from there to the final DLL file by the linker,
27168 where it can be read by the debugger. You must use the
27169 @option{-g} switch if you plan on using the debugger or the symbolic
27170 stack traceback.
27171
27172 @item -h
27173 @cindex @option{-h} (@code{gnatdll})
27174 Help mode. Displays @code{gnatdll} switch usage information.
27175
27176 @item -Idir
27177 @cindex @option{-I} (@code{gnatdll})
27178 Direct @code{gnatdll} to search the @var{dir} directory for source and
27179 object files needed to build the DLL.
27180 (@pxref{Search Paths and the Run-Time Library (RTL)}).
27181
27182 @item -k
27183 @cindex @option{-k} (@code{gnatdll})
27184 Removes the @code{@@}@i{nn} suffix from the import library's exported
27185 names. You must specified this option if you want to use a
27186 @code{Stdcall} function in a DLL for which the @code{@@}@i{nn} suffix
27187 has been removed. This is the case for most of the Windows NT DLL for
27188 example. This option has no effect when @option{-n} option is specified.
27189
27190 @item -l @var{file}
27191 @cindex @option{-l} (@code{gnatdll})
27192 The list of ALI and object files used to build the DLL are listed in
27193 @var{file}, instead of being given in the command line. Each line in
27194 @var{file} contains the name of an ALI or object file.
27195
27196 @item -n
27197 @cindex @option{-n} (@code{gnatdll})
27198 No Import. Do not create the import library.
27199
27200 @item -q
27201 @cindex @option{-q} (@code{gnatdll})
27202 Quiet mode. Do not display unnecessary messages.
27203
27204 @item -v
27205 @cindex @option{-v} (@code{gnatdll})
27206 Verbose mode. Display extra information.
27207
27208 @item -largs @var{opts}
27209 @cindex @option{-largs} (@code{gnatdll})
27210 Linker options. Pass @var{opts} to the linker.
27211 @end table
27212
27213 @node gnatdll Example
27214 @subsubsection @code{gnatdll} Example
27215
27216 @noindent
27217 As an example the command to build a relocatable DLL from @file{api.adb}
27218 once @file{api.adb} has been compiled and @file{api.def} created is
27219
27220 @smallexample
27221 $ gnatdll -d api.dll api.ali
27222 @end smallexample
27223
27224 @noindent
27225 The above command creates two files: @file{libapi.a} (the import
27226 library) and @file{api.dll} (the actual DLL). If you want to create
27227 only the DLL, just type:
27228
27229 @smallexample
27230 $ gnatdll -d api.dll -n api.ali
27231 @end smallexample
27232
27233 @noindent
27234 Alternatively if you want to create just the import library, type:
27235
27236 @smallexample
27237 $ gnatdll -d api.dll
27238 @end smallexample
27239
27240 @node gnatdll behind the Scenes
27241 @subsubsection @code{gnatdll} behind the Scenes
27242
27243 @noindent
27244 This section details the steps involved in creating a DLL. @code{gnatdll}
27245 does these steps for you. Unless you are interested in understanding what
27246 goes on behind the scenes, you should skip this section.
27247
27248 We use the previous example of a DLL containing the Ada package @code{API},
27249 to illustrate the steps necessary to build a DLL. The starting point is a
27250 set of objects that will make up the DLL and the corresponding ALI
27251 files. In the case of this example this means that @file{api.o} and
27252 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27253 the following:
27254
27255 @enumerate
27256 @item
27257 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27258 the information necessary to generate relocation information for the
27259 DLL.
27260
27261 @smallexample
27262 @group
27263 $ gnatbind -n api
27264 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27265 @end group
27266 @end smallexample
27267
27268 @noindent
27269 In addition to the base file, the @code{gnatlink} command generates an
27270 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27271 asks @code{gnatlink} to generate the routines @code{DllMain} and
27272 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27273 is loaded into memory.
27274
27275 @item
27276 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27277 export table (@file{api.exp}). The export table contains the relocation
27278 information in a form which can be used during the final link to ensure
27279 that the Windows loader is able to place the DLL anywhere in memory.
27280
27281 @smallexample
27282 @group
27283 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27284           --output-exp api.exp
27285 @end group
27286 @end smallexample
27287
27288 @item
27289 @code{gnatdll} builds the base file using the new export table. Note that
27290 @code{gnatbind} must be called once again since the binder generated file
27291 has been deleted during the previous call to @code{gnatlink}.
27292
27293 @smallexample
27294 @group
27295 $ gnatbind -n api
27296 $ gnatlink api -o api.jnk api.exp -mdll
27297       -Wl,--base-file,api.base
27298 @end group
27299 @end smallexample
27300
27301 @item
27302 @code{gnatdll} builds the new export table using the new base file and
27303 generates the DLL import library @file{libAPI.a}.
27304
27305 @smallexample
27306 @group
27307 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27308           --output-exp api.exp --output-lib libAPI.a
27309 @end group
27310 @end smallexample
27311
27312 @item
27313 Finally @code{gnatdll} builds the relocatable DLL using the final export
27314 table.
27315
27316 @smallexample
27317 @group
27318 $ gnatbind -n api
27319 $ gnatlink api api.exp -o api.dll -mdll
27320 @end group
27321 @end smallexample
27322 @end enumerate
27323
27324 @node Using dlltool
27325 @subsubsection Using @code{dlltool}
27326
27327 @noindent
27328 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27329 DLLs and static import libraries. This section summarizes the most
27330 common @code{dlltool} switches. The form of the @code{dlltool} command
27331 is
27332
27333 @smallexample
27334 $ dlltool [@var{switches}]
27335 @end smallexample
27336
27337 @noindent
27338 @code{dlltool} switches include:
27339
27340 @table @option
27341 @item --base-file @var{basefile}
27342 @cindex @option{--base-file} (@command{dlltool})
27343 Read the base file @var{basefile} generated by the linker. This switch
27344 is used to create a relocatable DLL.
27345
27346 @item --def @var{deffile}
27347 @cindex @option{--def} (@command{dlltool})
27348 Read the definition file.
27349
27350 @item --dllname @var{name}
27351 @cindex @option{--dllname} (@command{dlltool})
27352 Gives the name of the DLL. This switch is used to embed the name of the
27353 DLL in the static import library generated by @code{dlltool} with switch
27354 @option{--output-lib}.
27355
27356 @item -k
27357 @cindex @option{-k} (@command{dlltool})
27358 Kill @code{@@}@i{nn} from exported names
27359 (@pxref{Windows Calling Conventions}
27360 for a discussion about @code{Stdcall}-style symbols.
27361
27362 @item --help
27363 @cindex @option{--help} (@command{dlltool})
27364 Prints the @code{dlltool} switches with a concise description.
27365
27366 @item --output-exp @var{exportfile}
27367 @cindex @option{--output-exp} (@command{dlltool})
27368 Generate an export file @var{exportfile}. The export file contains the
27369 export table (list of symbols in the DLL) and is used to create the DLL.
27370
27371 @item --output-lib @i{libfile}
27372 @cindex @option{--output-lib} (@command{dlltool})
27373 Generate a static import library @var{libfile}.
27374
27375 @item -v
27376 @cindex @option{-v} (@command{dlltool})
27377 Verbose mode.
27378
27379 @item --as @i{assembler-name}
27380 @cindex @option{--as} (@command{dlltool})
27381 Use @i{assembler-name} as the assembler. The default is @code{as}.
27382 @end table
27383
27384 @node GNAT and Windows Resources
27385 @section GNAT and Windows Resources
27386 @cindex Resources, windows
27387
27388 @menu
27389 * Building Resources::
27390 * Compiling Resources::
27391 * Using Resources::
27392 @end menu
27393
27394 @noindent
27395 Resources are an easy way to add Windows specific objects to your
27396 application. The objects that can be added as resources include:
27397
27398 @itemize @bullet
27399 @item
27400 menus
27401
27402 @item
27403 accelerators
27404
27405 @item
27406 dialog boxes
27407
27408 @item
27409 string tables
27410
27411 @item
27412 bitmaps
27413
27414 @item
27415 cursors
27416
27417 @item
27418 icons
27419
27420 @item
27421 fonts
27422 @end itemize
27423
27424 @noindent
27425 This section explains how to build, compile and use resources.
27426
27427 @node Building Resources
27428 @subsection Building Resources
27429 @cindex Resources, building
27430
27431 @noindent
27432 A resource file is an ASCII file. By convention resource files have an
27433 @file{.rc} extension.
27434 The easiest way to build a resource file is to use Microsoft tools
27435 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
27436 @code{dlgedit.exe} to build dialogs.
27437 It is always possible to build an @file{.rc} file yourself by writing a
27438 resource script.
27439
27440 It is not our objective to explain how to write a resource file. A
27441 complete description of the resource script language can be found in the
27442 Microsoft documentation.
27443
27444 @node Compiling Resources
27445 @subsection Compiling Resources
27446 @findex rc
27447 @findex windres
27448 @cindex Resources, compiling
27449
27450 @noindent
27451 This section describes how to build a GNAT-compatible (COFF) object file
27452 containing the resources. This is done using the Resource Compiler
27453 @code{windres} as follows:
27454
27455 @smallexample
27456 $ windres -i myres.rc -o myres.o
27457 @end smallexample
27458
27459 @noindent
27460 By default @code{windres} will run @code{gcc} to preprocess the @file{.rc}
27461 file. You can specify an alternate preprocessor (usually named
27462 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
27463 parameter. A list of all possible options may be obtained by entering
27464 the command @code{windres} @option{--help}.
27465
27466 It is also possible to use the Microsoft resource compiler @code{rc.exe}
27467 to produce a @file{.res} file (binary resource file). See the
27468 corresponding Microsoft documentation for further details. In this case
27469 you need to use @code{windres} to translate the @file{.res} file to a
27470 GNAT-compatible object file as follows:
27471
27472 @smallexample
27473 $ windres -i myres.res -o myres.o
27474 @end smallexample
27475
27476 @node Using Resources
27477 @subsection Using Resources
27478 @cindex Resources, using
27479
27480 @noindent
27481 To include the resource file in your program just add the
27482 GNAT-compatible object file for the resource(s) to the linker
27483 arguments. With @code{gnatmake} this is done by using the @option{-largs}
27484 option:
27485
27486 @smallexample
27487 $ gnatmake myprog -largs myres.o
27488 @end smallexample
27489
27490 @node Debugging a DLL
27491 @section Debugging a DLL
27492 @cindex DLL debugging
27493
27494 @menu
27495 * Program and DLL Both Built with GCC/GNAT::
27496 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
27497 @end menu
27498
27499 @noindent
27500 Debugging a DLL is similar to debugging a standard program. But
27501 we have to deal with two different executable parts: the DLL and the
27502 program that uses it. We have the following four possibilities:
27503
27504 @enumerate 1
27505 @item
27506 The program and the DLL are built with @code{GCC/GNAT}.
27507 @item
27508 The program is built with foreign tools and the DLL is built with
27509 @code{GCC/GNAT}.
27510 @item
27511 The program is built with @code{GCC/GNAT} and the DLL is built with
27512 foreign tools.
27513 @item
27514 @end enumerate
27515
27516 @noindent
27517 In this section we address only cases one and two above.
27518 There is no point in trying to debug
27519 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
27520 information in it. To do so you must use a debugger compatible with the
27521 tools suite used to build the DLL.
27522
27523 @node Program and DLL Both Built with GCC/GNAT
27524 @subsection Program and DLL Both Built with GCC/GNAT
27525
27526 @noindent
27527 This is the simplest case. Both the DLL and the program have @code{GDB}
27528 compatible debugging information. It is then possible to break anywhere in
27529 the process. Let's suppose here that the main procedure is named
27530 @code{ada_main} and that in the DLL there is an entry point named
27531 @code{ada_dll}.
27532
27533 @noindent
27534 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
27535 program must have been built with the debugging information (see GNAT -g
27536 switch). Here are the step-by-step instructions for debugging it:
27537
27538 @enumerate 1
27539 @item Launch @code{GDB} on the main program.
27540
27541 @smallexample
27542 $ gdb -nw ada_main
27543 @end smallexample
27544
27545 @item Break on the main procedure and run the program.
27546
27547 @smallexample
27548 (gdb) break ada_main
27549 (gdb) run
27550 @end smallexample
27551
27552 @noindent
27553 This step is required to be able to set a breakpoint inside the DLL. As long
27554 as the program is not run, the DLL is not loaded. This has the
27555 consequence that the DLL debugging information is also not loaded, so it is not
27556 possible to set a breakpoint in the DLL.
27557
27558 @item Set a breakpoint inside the DLL
27559
27560 @smallexample
27561 (gdb) break ada_dll
27562 (gdb) run
27563 @end smallexample
27564
27565 @end enumerate
27566
27567 @noindent
27568 At this stage a breakpoint is set inside the DLL. From there on
27569 you can use the standard approach to debug the whole program
27570 (@pxref{Running and Debugging Ada Programs}).
27571
27572 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
27573 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
27574
27575 @menu
27576 * Debugging the DLL Directly::
27577 * Attaching to a Running Process::
27578 @end menu
27579
27580 @noindent
27581 In this case things are slightly more complex because it is not possible to
27582 start the main program and then break at the beginning to load the DLL and the
27583 associated DLL debugging information. It is not possible to break at the
27584 beginning of the program because there is no @code{GDB} debugging information,
27585 and therefore there is no direct way of getting initial control. This
27586 section addresses this issue by describing some methods that can be used
27587 to break somewhere in the DLL to debug it.
27588
27589 @noindent
27590 First suppose that the main procedure is named @code{main} (this is for
27591 example some C code built with Microsoft Visual C) and that there is a
27592 DLL named @code{test.dll} containing an Ada entry point named
27593 @code{ada_dll}.
27594
27595 @noindent
27596 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
27597 been built with debugging information (see GNAT -g option).
27598
27599 @node Debugging the DLL Directly
27600 @subsubsection Debugging the DLL Directly
27601
27602 @enumerate 1
27603 @item
27604 Launch the debugger on the DLL.
27605
27606 @smallexample
27607 $ gdb -nw test.dll
27608 @end smallexample
27609
27610 @item Set a breakpoint on a DLL subroutine.
27611
27612 @smallexample
27613 (gdb) break ada_dll
27614 @end smallexample
27615
27616 @item
27617 Specify the executable file to @code{GDB}.
27618
27619 @smallexample
27620 (gdb) exec-file main.exe
27621 @end smallexample
27622
27623 @item
27624 Run the program.
27625
27626 @smallexample
27627 (gdb) run
27628 @end smallexample
27629
27630 @noindent
27631 This will run the program until it reaches the breakpoint that has been
27632 set. From that point you can use the standard way to debug a program
27633 as described in (@pxref{Running and Debugging Ada Programs}).
27634
27635 @end enumerate
27636
27637 @noindent
27638 It is also possible to debug the DLL by attaching to a running process.
27639
27640 @node Attaching to a Running Process
27641 @subsubsection Attaching to a Running Process
27642 @cindex DLL debugging, attach to process
27643
27644 @noindent
27645 With @code{GDB} it is always possible to debug a running process by
27646 attaching to it. It is possible to debug a DLL this way. The limitation
27647 of this approach is that the DLL must run long enough to perform the
27648 attach operation. It may be useful for instance to insert a time wasting
27649 loop in the code of the DLL to meet this criterion.
27650
27651 @enumerate 1
27652
27653 @item Launch the main program @file{main.exe}.
27654
27655 @smallexample
27656 $ main
27657 @end smallexample
27658
27659 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
27660 that the process PID for @file{main.exe} is 208.
27661
27662 @item Launch gdb.
27663
27664 @smallexample
27665 $ gdb -nw
27666 @end smallexample
27667
27668 @item Attach to the running process to be debugged.
27669
27670 @smallexample
27671 (gdb) attach 208
27672 @end smallexample
27673
27674 @item Load the process debugging information.
27675
27676 @smallexample
27677 (gdb) symbol-file main.exe
27678 @end smallexample
27679
27680 @item Break somewhere in the DLL.
27681
27682 @smallexample
27683 (gdb) break ada_dll
27684 @end smallexample
27685
27686 @item Continue process execution.
27687
27688 @smallexample
27689 (gdb) continue
27690 @end smallexample
27691
27692 @end enumerate
27693
27694 @noindent
27695 This last step will resume the process execution, and stop at
27696 the breakpoint we have set. From there you can use the standard
27697 approach to debug a program as described in
27698 (@pxref{Running and Debugging Ada Programs}).
27699
27700 @node GNAT and COM/DCOM Objects
27701 @section GNAT and COM/DCOM Objects
27702 @findex COM
27703 @findex DCOM
27704
27705 @noindent
27706 This section is temporarily left blank.
27707
27708 @end ifset
27709
27710
27711 @c **********************************
27712 @c * GNU Free Documentation License *
27713 @c **********************************
27714 @include fdl.texi
27715 @c GNU Free Documentation License
27716
27717 @node Index,,GNU Free Documentation License, Top
27718 @unnumbered Index
27719
27720 @printindex cp
27721
27722 @contents
27723 @c Put table of contents at end, otherwise it precedes the "title page" in
27724 @c the .txt version
27725 @c Edit the pdf file to move the contents to the beginning, after the title
27726 @c page
27727
27728 @bye