OSDN Git Service

Daily bump.
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ug_wnt.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                                 o
9 @c                                                                            o
10 @c          Copyright (C) 1992-2002 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  GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com).    o
24 @c                                                                            o
25 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
26
27 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
28 @c
29 @c                           GNAT_UG Style Guide
30 @c
31 @c  1. Always put a @noindent on the line before the first paragraph
32 @c     after any of these commands:
33 @c
34 @c          @chapter
35 @c          @section
36 @c          @subsection
37 @c          @subsubsection
38 @c          @subsubsubsection
39 @c
40 @c          @end smallexample
41 @c          @end itemize
42 @c          @end enumerate
43 @c
44 @c  2. DO NOT use @example. Use @smallexample instead.
45 @c
46 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
47 @c     command must be preceded by two empty lines
48 @c
49 @c  4. The @item command must be on a line of its own if it is in an
50 @c     @itemize or @enumerate command.
51 @c
52 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
53 @c     or "ali".
54 @c
55 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
56
57
58 @setfilename gnat_ug_wnt.info
59 @settitle GNAT User's Guide for Windows NT
60
61
62
63 @include gcc-common.texi
64
65 @setchapternewpage odd
66 @syncodeindex fn cp
67 @c %**end of header
68
69 @titlepage
70
71
72 @title GNAT User's Guide
73 @center @titlefont{for Windows NT}
74
75
76
77 @subtitle GNAT, The GNU Ada 95 Compiler
78 @subtitle GNAT Version for GCC @value{version-GCC}
79
80 @author Ada Core Technologies, Inc.
81
82 @page
83 @vskip 0pt plus 1filll
84
85 Copyright @copyright{} 1995-2002, Free Software Foundation
86
87 Permission is granted to copy, distribute and/or modify this document
88 under the terms of the GNU Free Documentation License, Version 1.1
89 or any later version published by the Free Software Foundation;
90 with the Invariant Sections being ``GNU Free Documentation License'', with the
91 Front-Cover Texts being
92 ``GNAT User's Guide for Windows NT'',
93 and with no Back-Cover Texts.
94 A copy of the license is included in the section entitled ``GNU
95 Free Documentation License''.
96
97 @end titlepage
98
99 @ifnottex
100 @node Top, About This Guide, (dir), (dir)
101 @top GNAT User's Guide
102
103
104 GNAT User's Guide for Windows NT
105
106
107
108 GNAT, The GNU Ada 95 Compiler
109
110 GNAT Version for GCC @value{version-GCC}
111
112 Ada Core Technologies, Inc.
113
114 Copyright @copyright{} 1995-2002, Free Software Foundation
115
116 Permission is granted to copy, distribute and/or modify this document
117 under the terms of the GNU Free Documentation License, Version 1.1
118 or any later version published by the Free Software Foundation;
119 with the Invariant Sections being ``GNU Free Documentation License'', with the
120 Front-Cover Texts being
121 ``GNAT User's Guide for Windows NT'',
122 and with no Back-Cover Texts.
123 A copy of the license is included in the section entitled ``GNU
124 Free Documentation License''.
125
126 @menu
127 * About This Guide::
128 * Getting Started with GNAT::
129 * The GNAT Compilation Model::
130 * Compiling Using gcc::
131 * Binding Using gnatbind::
132 * Linking Using gnatlink::
133 * The GNAT Make Program gnatmake::
134 * Renaming Files Using gnatchop::
135 * Configuration Pragmas::
136 * Handling Arbitrary File Naming Conventions Using gnatname::
137 * GNAT Project Manager::
138 * Elaboration Order Handling in GNAT::
139 * The Cross-Referencing Tools gnatxref and gnatfind::
140 * File Name Krunching Using gnatkr::
141 * Preprocessing Using gnatprep::
142 * The GNAT Library Browser gnatls::
143 * GNAT and Libraries::
144 * Using the GNU make Utility::
145 * Finding Memory Problems with gnatmem::
146 * Finding Memory Problems with GNAT Debug Pool::
147 * Creating Sample Bodies Using gnatstub::
148 * Reducing the Size of Ada Executables with gnatelim::
149 * Other Utility Programs::
150 * Running and Debugging Ada Programs::
151 * Inline Assembler::
152 * Microsoft Windows Topics::
153 * Performance Considerations::
154 * GNU Free Documentation License::
155 * Index::
156
157  --- The Detailed Node Listing ---
158
159 About This Guide
160
161 * What This Guide Contains::
162 * What You Should Know before Reading This Guide::
163 * Related Information::
164 * Conventions::
165
166
167 Getting Started with GNAT
168
169 * Running GNAT::
170 * Running a Simple Ada Program::
171 * Running a Program with Multiple Units::
172 * Using the gnatmake Utility::
173
174 The GNAT Compilation Model
175
176 * Source Representation::
177 * Foreign Language Representation::
178 * File Naming Rules::
179 * Using Other File Names::
180 * Alternative File Naming Schemes::
181 * Generating Object Files::
182 * Source Dependencies::
183 * The Ada Library Information Files::
184 * Binding an Ada Program::
185 * Mixed Language Programming::
186 * Building Mixed Ada & C++ Programs::
187 * Comparison between GNAT and C/C++ Compilation Models::
188 * Comparison between GNAT and Conventional Ada Library Models::
189
190 Foreign Language Representation
191
192 * Latin-1::
193 * Other 8-Bit Codes::
194 * Wide Character Encodings::
195
196 Compiling Ada Programs With gcc
197
198 * Compiling Programs::
199 * Switches for gcc::
200 * Search Paths and the Run-Time Library (RTL)::
201 * Order of Compilation Issues::
202 * Examples::
203
204 Switches for gcc
205
206 * Output and Error Message Control::
207 * Debugging and Assertion Control::
208 * Run-Time Checks::
209 * Stack Overflow Checking::
210 * Run-Time Control::
211 * Validity Checking::
212 * Style Checking::
213 * Using gcc for Syntax Checking::
214 * Using gcc for Semantic Checking::
215 * Compiling Ada 83 Programs::
216 * Character Set Control::
217 * File Naming Control::
218 * Subprogram Inlining Control::
219 * Auxiliary Output Control::
220 * Debugging Control::
221 * Units to Sources Mapping Files::
222
223 Binding Ada Programs With gnatbind
224
225 * Running gnatbind::
226 * Generating the Binder Program in C::
227 * Consistency-Checking Modes::
228 * Binder Error Message Control::
229 * Elaboration Control::
230 * Output Control::
231 * Binding with Non-Ada Main Programs::
232 * Binding Programs with No Main Subprogram::
233 * Summary of Binder Switches::
234 * Command-Line Access::
235 * Search Paths for gnatbind::
236 * Examples of gnatbind Usage::
237
238 Linking Using gnatlink
239
240 * Running gnatlink::
241 * Switches for gnatlink::
242 * Setting Stack Size from gnatlink::
243 * Setting Heap Size from gnatlink::
244
245 The GNAT Make Program gnatmake
246
247 * Running gnatmake::
248 * Switches for gnatmake::
249 * Mode Switches for gnatmake::
250 * Notes on the Command Line::
251 * How gnatmake Works::
252 * Examples of gnatmake Usage::
253
254 Renaming Files Using gnatchop
255
256 * Handling Files with Multiple Units::
257 * Operating gnatchop in Compilation Mode::
258 * Command Line for gnatchop::
259 * Switches for gnatchop::
260 * Examples of gnatchop Usage::
261
262 Configuration Pragmas
263
264 * Handling of Configuration Pragmas::
265 * The Configuration Pragmas Files::
266
267 Handling Arbitrary File Naming Conventions Using gnatname
268
269 * Arbitrary File Naming Conventions::
270 * Running gnatname::
271 * Switches for gnatname::
272 * Examples of gnatname Usage::
273
274 GNAT Project Manager
275
276 * Introduction::
277 * Examples of Project Files::
278 * Project File Syntax::
279 * Objects and Sources in Project Files::
280 * Importing Projects::
281 * Project Extension::
282 * External References in Project Files::
283 * Packages in Project Files::
284 * Variables from Imported Projects::
285 * Naming Schemes::
286 * Library Projects::
287 * Switches Related to Project Files::
288 * Tools Supporting Project Files::
289 * An Extended Example::
290 * Project File Complete Syntax::
291
292 Elaboration Order Handling in GNAT
293
294 * Elaboration Code in Ada 95::
295 * Checking the Elaboration Order in Ada 95::
296 * Controlling the Elaboration Order in Ada 95::
297 * Controlling Elaboration in GNAT - Internal Calls::
298 * Controlling Elaboration in GNAT - External Calls::
299 * Default Behavior in GNAT - Ensuring Safety::
300 * Elaboration Issues for Library Tasks::
301 * Mixing Elaboration Models::
302 * What to Do If the Default Elaboration Behavior Fails::
303 * Elaboration for Access-to-Subprogram Values::
304 * Summary of Procedures for Elaboration Control::
305 * Other Elaboration Order Considerations::
306
307 The Cross-Referencing Tools gnatxref and gnatfind
308
309 * gnatxref Switches::
310 * gnatfind Switches::
311 * Project Files for gnatxref and gnatfind::
312 * Regular Expressions in gnatfind and gnatxref::
313 * Examples of gnatxref Usage::
314 * Examples of gnatfind Usage::
315
316 File Name Krunching Using gnatkr
317
318 * About gnatkr::
319 * Using gnatkr::
320 * Krunching Method::
321 * Examples of gnatkr Usage::
322
323 Preprocessing Using gnatprep
324
325 * Using gnatprep::
326 * Switches for gnatprep::
327 * Form of Definitions File::
328 * Form of Input Text for gnatprep::
329
330
331 The GNAT Library Browser gnatls
332
333 * Running gnatls::
334 * Switches for gnatls::
335 * Examples of gnatls Usage::
336
337
338 GNAT and Libraries
339
340 * Creating an Ada Library::
341 * Installing an Ada Library::
342 * Using an Ada Library::
343 * Creating an Ada Library to be Used in a Non-Ada Context::
344 * Rebuilding the GNAT Run-Time Library::
345
346 Using the GNU make Utility
347
348 * Using gnatmake in a Makefile::
349 * Automatically Creating a List of Directories::
350 * Generating the Command Line Switches::
351 * Overcoming Command Line Length Limits::
352
353 Finding Memory Problems with gnatmem
354
355 * Running gnatmem (GDB Mode)::
356 * Running gnatmem (GMEM Mode)::
357 * Switches for gnatmem::
358 * Examples of gnatmem Usage::
359 * GDB and GMEM Modes::
360 * Implementation Note::
361
362
363 Finding Memory Problems with GNAT Debug Pool
364
365 Creating Sample Bodies Using gnatstub
366
367 * Running gnatstub::
368 * Switches for gnatstub::
369
370 Reducing the Size of Ada Executables with gnatelim
371
372 * About gnatelim::
373 * Eliminate Pragma::
374 * Tree Files::
375 * Preparing Tree and Bind Files for gnatelim::
376 * Running gnatelim::
377 * Correcting the List of Eliminate Pragmas::
378 * Making Your Executables Smaller::
379 * Summary of the gnatelim Usage Cycle::
380
381 Other Utility Programs
382
383 * Using Other Utility Programs with GNAT::
384 * The gnatpsta Utility Program::
385 * The External Symbol Naming Scheme of GNAT::
386 * Ada Mode for Glide::
387 * Converting Ada Files to html with gnathtml::
388
389
390 Running and Debugging Ada Programs
391
392 * The GNAT Debugger GDB::
393 * Running GDB::
394 * Introduction to GDB Commands::
395 * Using Ada Expressions::
396 * Calling User-Defined Subprograms::
397 * Using the Next Command in a Function::
398 * Ada Exceptions::
399 * Ada Tasks::
400 * Debugging Generic Units::
401 * GNAT Abnormal Termination or Failure to Terminate::
402 * Naming Conventions for GNAT Source Files::
403 * Getting Internal Debugging Information::
404 * Stack Traceback::
405
406 Inline Assembler
407
408 * Basic Assembler Syntax::
409 * A Simple Example of Inline Assembler::
410 * Output Variables in Inline Assembler::
411 * Input Variables in Inline Assembler::
412 * Inlining Inline Assembler Code::
413 * Other Asm Functionality::
414 * A Complete Example::
415
416 Microsoft Windows Topics
417
418 * Using GNAT on Windows::
419 * GNAT Setup Tool::
420 * CONSOLE and WINDOWS subsystems::
421 * Temporary Files::
422 * Mixed-Language Programming on Windows::
423 * Windows Calling Conventions::
424 * Introduction to Dynamic Link Libraries (DLLs)::
425 * Using DLLs with GNAT::
426 * Building DLLs with GNAT::
427 * GNAT and Windows Resources::
428 * GNAT and COM/DCOM Objects::
429
430
431 Performance Considerations
432
433 * Controlling Run-Time Checks::
434 * Optimization Levels::
435 * Debugging Optimized Code::
436 * Inlining of Subprograms::
437
438 * Index::
439 @end menu
440 @end ifnottex
441
442 @node About This Guide
443 @unnumbered About This Guide
444
445 @noindent
446 This guide describes the use of GNAT, a compiler and software development
447 toolset for the full Ada 95 programming language.
448 It describes the features of the compiler and tools, and details
449 how to use them to build Ada 95 applications.
450
451 @menu
452 * What This Guide Contains::
453 * What You Should Know before Reading This Guide::
454 * Related Information::
455 * Conventions::
456 @end menu
457
458 @node What This Guide Contains
459 @unnumberedsec What This Guide Contains
460
461 @noindent
462 This guide contains the following chapters:
463 @itemize @bullet
464 @item
465 @ref{Getting Started with GNAT}, describes how to get started compiling
466 and running Ada programs with the GNAT Ada programming environment.
467 @item
468 @ref{The GNAT Compilation Model}, describes the compilation model used
469 by GNAT.
470 @item
471 @ref{Compiling Using gcc}, describes how to compile
472 Ada programs with @code{gcc}, the Ada compiler.
473 @item
474 @ref{Binding Using gnatbind}, describes how to
475 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
476 utility.
477 @item
478 @ref{Linking Using gnatlink},
479 describes @code{gnatlink}, a
480 program that provides for linking using the GNAT run-time library to
481 construct a program. @code{gnatlink} can also incorporate foreign language
482 object units into the executable.
483 @item
484 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
485 utility that automatically determines the set of sources
486 needed by an Ada compilation unit, and executes the necessary compilations
487 binding and link.
488 @item
489 @ref{Renaming Files Using gnatchop}, describes
490 @code{gnatchop}, a utility that allows you to preprocess a file that
491 contains Ada source code, and split it into one or more new files, one
492 for each compilation unit.
493 @item
494 @ref{Configuration Pragmas}, describes the configuration pragmas handled by GNAT.
495 @item
496 @ref{Handling Arbitrary File Naming Conventions Using gnatname}, shows how to override
497 the default GNAT file naming conventions, either for an individual unit or globally.
498 @item
499 @ref{GNAT Project Manager}, describes how to use project files to organize large projects.
500 @item
501 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps you deal with
502 elaboration order issues.
503 @item
504 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
505 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
506 way to navigate through sources.
507 @item
508 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
509 file name krunching utility, used to handle shortened
510 file names on operating systems with a limit on the length of names.
511 @item
512 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
513 preprocessor utility that allows a single source file to be used to
514 generate multiple or parameterized source files, by means of macro
515 substitution.
516 @item
517 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
518 utility that displays information about compiled units, including dependences
519 on the corresponding sources files, and consistency of compilations.
520 @item
521 @ref{GNAT and Libraries}, describes the process of creating and using
522 Libraries with GNAT. It also describes how to recompile the GNAT run-time
523 library.
524
525 @item
526 @ref{Using the GNU make Utility}, describes some techniques for using
527 the GNAT toolset in Makefiles.
528
529 @item
530 @ref{Finding Memory Problems with gnatmem}, describes @code{gnatmem}, a
531 utility that monitors dynamic allocation and deallocation activity in a
532 program, and displays information about incorrect deallocations and sources
533 of possible memory leaks.
534 @item
535 @ref{Finding Memory Problems with GNAT Debug Pool}, describes how to
536 use the GNAT-specific Debug Pool in order to detect as early as possible
537 the use of incorrect memory references.
538
539 @item
540 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
541 a utility that generates empty but compilable bodies for library units.
542
543 @item
544 @ref{Reducing the Size of Ada Executables with gnatelim}, describes
545 @code{gnatelim}, a tool which detects unused subprograms and helps
546 the compiler to create a smaller executable for the program.
547
548 @item
549 @ref{Other Utility Programs}, discusses several other GNAT utilities,
550 including @code{gnatpsta}.
551
552 @item
553 @ref{Running and Debugging Ada Programs}, describes how to run and debug
554 Ada programs.
555
556 @item
557 @ref{Inline Assembler}, shows how to use the inline assembly facility in an Ada program.
558
559
560 @item
561 @ref{Performance Considerations}, reviews the trade offs between using
562 defaults or options in program development.
563 @end itemize
564
565 @node What You Should Know before Reading This Guide
566 @unnumberedsec What You Should Know before Reading This Guide
567
568 @cindex Ada 95 Language Reference Manual
569 @noindent
570 This user's guide assumes that you are familiar with Ada 95 language, as
571 described in the International Standard ANSI/ISO/IEC-8652:1995, Jan
572 1995.
573
574 @node Related Information
575 @unnumberedsec Related Information
576
577 @noindent
578 For further information about related tools, refer to the following
579 documents:
580
581 @itemize @bullet
582 @item
583 @cite{GNAT Reference Manual}, which contains all reference
584 material for the GNAT implementation of Ada 95.
585
586 @item
587 @cite{Ada 95 Language Reference Manual}, which contains all reference
588 material for the Ada 95 programming language.
589
590 @item
591 @cite{Debugging with GDB}
592 contains all details on the use of the GNU source-level debugger.
593
594 @item
595 @cite{GNU Emacs Manual}
596 contains full information on the extensible editor and programming
597 environment Emacs.
598
599 @end itemize
600
601 @node Conventions
602 @unnumberedsec Conventions
603 @cindex Conventions
604 @cindex Typographical conventions
605
606 @noindent
607 Following are examples of the typographical and graphic conventions used
608 in this guide:
609
610 @itemize @bullet
611 @item
612 @code{Functions}, @code{utility program names}, @code{standard names},
613 and @code{classes}.
614
615 @item
616 @samp{Option flags}
617
618 @item
619 @file{File Names}, @file{button names}, and @file{field names}.
620
621 @item
622 @var{Variables}.
623
624 @item
625 @emph{Emphasis}.
626
627 @item
628 [optional information or parameters]
629
630 @item
631 Examples are described by text
632 @smallexample
633 and then shown this way.
634 @end smallexample
635 @end itemize
636
637 @noindent
638 Commands that are entered by the user are preceded in this manual by the
639 characters @w{"@code{$ }"} (dollar sign followed by space). If your system
640 uses this sequence as a prompt, then the commands will appear exactly as
641 you see them in the manual. If your system uses some other prompt, then
642 the command will appear with the @code{$} replaced by whatever prompt
643 character you are using.
644
645
646 @node Getting Started with GNAT
647 @chapter Getting Started with GNAT
648
649 @noindent
650 This chapter describes some simple ways of using GNAT to build
651 executable Ada programs.
652
653 @menu
654 * Running GNAT::
655 * Running a Simple Ada Program::
656
657 * Running a Program with Multiple Units::
658
659 * Using the gnatmake Utility::
660 * Introduction to Glide and GVD::
661 @end menu
662
663 @node Running GNAT
664 @section Running GNAT
665
666 @noindent
667 Three steps are needed to create an executable file from an Ada source
668 file:
669
670 @enumerate
671 @item
672 The source file(s) must be compiled.
673 @item
674 The file(s) must be bound using the GNAT binder.
675 @item
676 All appropriate object files must be linked to produce an executable.
677 @end enumerate
678
679 @noindent
680 All three steps are most commonly handled by using the @code{gnatmake}
681 utility program that, given the name of the main program, automatically
682 performs the necessary compilation, binding and linking steps.
683
684 @node Running a Simple Ada Program
685 @section Running a Simple Ada Program
686
687 @noindent
688 Any text editor may be used to prepare an Ada program. If @code{Glide} is
689 used, the optional Ada mode may be helpful in laying out the program. The
690 program text is a normal text file. We will suppose in our initial
691 example that you have used your editor to prepare the following
692 standard format text file:
693
694 @smallexample
695 @group
696 @cartouche
697 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
698 @b{procedure} Hello @b{is}
699 @b{begin}
700    Put_Line ("Hello WORLD!");
701 @b{end} Hello;
702 @end cartouche
703 @end group
704 @end smallexample
705
706 @noindent
707 This file should be named @file{hello.adb}.
708 With the normal default file naming conventions, GNAT requires
709 that each file
710 contain a single compilation unit whose file name is the
711 unit name,
712 with periods replaced by hyphens; the
713 extension is @file{ads} for a
714 spec and @file{adb} for a body.
715 You can override this default file naming convention by use of the
716 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
717 Alternatively, if you want to rename your files according to this default
718 convention, which is probably more convenient if you will be using GNAT
719 for all your compilations, then the @code{gnatchop} utility
720 can be used to generate correctly-named source files
721 (@pxref{Renaming Files Using gnatchop}).
722
723 You can compile the program using the following command (@code{$} is used
724 as the command prompt in the examples in this document):
725
726 @smallexample
727 $ gcc -c hello.adb
728 @end smallexample
729
730
731 @noindent
732 @code{gcc} is the command used to run the compiler. This compiler is
733 capable of compiling programs in several languages, including Ada 95 and
734 C. It assumes that you have given it an Ada program if the file extension is
735 either @file{.ads} or @file{.adb}, and it will then call the GNAT compiler to compile
736 the specified file.
737
738 The @option{-c} switch is required. It tells @command{gcc} to only do a
739 compilation. (For C programs, @command{gcc} can also do linking, but this
740 capability is not used directly for Ada programs, so the @option{-c}
741 switch must always be present.)
742
743 This compile command generates a file
744 @file{hello.o}, which is the object
745 file corresponding to your Ada program. It also generates an "Ada Library Information" file
746 @file{hello.ali},
747 which contains additional information used to check
748 that an Ada program is consistent.
749 To build an executable file,
750 use @code{gnatbind} to bind the program
751 and @code{gnatlink} to link it. The
752 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
753 @file{ali} file, but the default extension of @file{.ali} can
754 be omitted. This means that in the most common case, the argument
755 is simply the name of the main program:
756
757 @smallexample
758 $ gnatbind hello
759 $ gnatlink hello
760 @end smallexample
761
762
763 @noindent
764 A simpler method of carrying out these steps is to use
765 @command{gnatmake},
766 a master program that invokes all the required
767 compilation, binding and linking tools in the correct order. In particular,
768 @command{gnatmake} automatically recompiles any sources that have been modified
769 since they were last compiled, or sources that depend
770 on such modified sources, so that "version skew" is avoided.
771 @cindex Version skew (avoided by @command{gnatmake})
772
773 @smallexample
774 $ gnatmake hello.adb
775 @end smallexample
776
777
778 @noindent
779 The result is an executable program called @file{hello}, which can be
780 run by entering:
781
782 @c The following should be removed (BMB 2001-01-23)
783 @c @smallexample
784 @c $ ./hello
785 @c @end smallexample
786
787 @smallexample
788 $ hello
789 @end smallexample
790
791 @noindent
792 assuming that the current directory is on the search path for executable programs.
793
794 @noindent
795 and, if all has gone well, you will see
796
797 @smallexample
798 Hello WORLD!
799 @end smallexample
800
801 @noindent
802 appear in response to this command.
803
804
805
806
807 @node Running a Program with Multiple Units
808 @section Running a Program with Multiple Units
809
810 @noindent
811 Consider a slightly more complicated example that has three files: a
812 main program, and the spec and body of a package:
813
814 @smallexample
815 @cartouche
816 @group
817 @b{package} Greetings @b{is}
818    @b{procedure} Hello;
819    @b{procedure} Goodbye;
820 @b{end} Greetings;
821
822 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
823 @b{package} @b{body} Greetings @b{is}
824    @b{procedure} Hello @b{is}
825    @b{begin}
826       Put_Line ("Hello WORLD!");
827    @b{end} Hello;
828
829    @b{procedure} Goodbye @b{is}
830    @b{begin}
831       Put_Line ("Goodbye WORLD!");
832    @b{end} Goodbye;
833 @b{end} Greetings;
834 @end group
835
836 @group
837 @b{with} Greetings;
838 @b{procedure} Gmain @b{is}
839 @b{begin}
840    Greetings.Hello;
841    Greetings.Goodbye;
842 @b{end} Gmain;
843 @end group
844 @end cartouche
845 @end smallexample
846
847 @noindent
848 Following the one-unit-per-file rule, place this program in the
849 following three separate files:
850
851 @table @file
852 @item greetings.ads
853 spec of package @code{Greetings}
854
855 @item greetings.adb
856 body of package @code{Greetings}
857
858 @item gmain.adb
859 body of main program
860 @end table
861
862 @noindent
863 To build an executable version of
864 this program, we could use four separate steps to compile, bind, and link
865 the program, as follows:
866
867 @smallexample
868 $ gcc -c gmain.adb
869 $ gcc -c greetings.adb
870 $ gnatbind gmain
871 $ gnatlink gmain
872 @end smallexample
873
874
875 @noindent
876 Note that there is no required order of compilation when using GNAT.
877 In particular it is perfectly fine to compile the main program first.
878 Also, it is not necessary to compile package specs in the case where
879 there is an accompanying body; you only need to compile the body. If you want
880 to submit these files to the compiler for semantic checking and not code generation,
881 then use the
882 @option{-gnatc} switch:
883
884 @smallexample
885    $ gcc -c greetings.ads -gnatc
886 @end smallexample
887
888
889 @noindent
890 Although the compilation can be done in separate steps as in the
891 above example, in practice it is almost always more convenient
892 to use the @code{gnatmake} tool. All you need to know in this case
893 is the name of the main program's source file. The effect of the above four
894 commands can be achieved with a single one:
895
896 @smallexample
897 $ gnatmake gmain.adb
898 @end smallexample
899
900
901 @noindent
902 In the next section we discuss the advantages of using @code{gnatmake} in
903 more detail.
904
905 @node Using the gnatmake Utility
906 @section Using the @command{gnatmake} Utility
907
908 @noindent
909 If you work on a program by compiling single components at a time using
910 @code{gcc}, you typically keep track of the units you modify. In order to
911 build a consistent system, you compile not only these units, but also any
912 units that depend on the units you have modified.
913 For example, in the preceding case,
914 if you edit @file{gmain.adb}, you only need to recompile that file. But if
915 you edit @file{greetings.ads}, you must recompile both
916 @file{greetings.adb} and @file{gmain.adb}, because both files contain
917 units that depend on @file{greetings.ads}.
918
919 @code{gnatbind} will warn you if you forget one of these compilation
920 steps, so that it is impossible to generate an inconsistent program as a
921 result of forgetting to do a compilation. Nevertheless it is tedious and
922 error-prone to keep track of dependencies among units.
923 One approach to handle the dependency-bookkeeping is to use a
924 makefile. However, makefiles present maintenance problems of their own:
925 if the dependencies change as you change the program, you must make
926 sure that the makefile is kept up-to-date manually, which is also an
927 error-prone process.
928
929 The @code{gnatmake} utility takes care of these details automatically.
930 Invoke it using either one of the following forms:
931
932 @smallexample
933 $ gnatmake gmain.adb
934 $ gnatmake gmain
935 @end smallexample
936
937
938 @noindent
939 The argument is the name of the file containing the main program;
940 you may omit the extension. @code{gnatmake}
941 examines the environment, automatically recompiles any files that need
942 recompiling, and binds and links the resulting set of object files,
943 generating the executable file, @file{gmain}.
944 In a large program, it
945 can be extremely helpful to use @code{gnatmake}, because working out by hand
946 what needs to be recompiled can be difficult.
947
948 Note that @code{gnatmake}
949 takes into account all the Ada 95 rules that
950 establish dependencies among units. These include dependencies that result
951 from inlining subprogram bodies, and from
952 generic instantiation. Unlike some other
953 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
954 found by the compiler on a previous compilation, which may possibly
955 be wrong when sources change. @code{gnatmake} determines the exact set of
956 dependencies from scratch each time it is run.
957
958
959 @node Introduction to Glide and GVD
960 @section Introduction to Glide and GVD
961 @cindex Glide
962 @cindex GVD
963 @noindent
964 Although it is possible to develop programs using only the command line interface (@command{gnatmake}, etc.) a graphical Interactive Development Environment can make it easier for you to compose, navigate, and debug programs.  This section describes the main features of Glide, the GNAT graphical IDE, and also shows how to use the basic commands in GVD, the GNU Visual Debugger.  Additional information may be found in the on-line help for these tools.
965
966 @menu
967 * Building a New Program with Glide::
968 * Simple Debugging with GVD::
969 * Other Glide Features::
970 @end menu
971
972 @node Building a New Program with Glide
973 @subsection Building a New Program with Glide
974 @noindent
975 The simplest way to invoke Glide is to enter @command{glide} at the command prompt.  It will generally be useful to issue this as a background command, thus allowing you to continue using your command window for other purposes while Glide is running:
976
977 @smallexample
978 $ glide&
979 @end smallexample
980
981 @noindent
982 Glide will start up with an initial screen displaying the top-level menu items as well as some other information.  The menu selections are as follows
983 @itemize @bullet
984 @item @code{Buffers}
985 @item @code{Files}
986 @item @code{Tools}
987 @item @code{Edit}
988 @item @code{Search}
989 @item @code{Mule}
990 @item @code{Glide}
991 @item @code{Help}
992 @end itemize
993
994 @noindent
995 For this introductory example, you will need to create a new Ada source file.  First, select the @code{Files} menu.  This will pop open a menu with around a dozen or so items.  To create a file, select the @code{Open file...} choice.  Depending on the platform, you may see a pop-up window where you can browse to an appropriate directory and then enter the file name, or else simply see a line at the bottom of the Glide window where you can likewise enter the file name.  Note that in Glide, when you attempt to open a non-existent file, the effect is to create a file with that name.  For this example enter @file{hello.adb} as the name of the file.
996
997 A new buffer will now appear, occupying the entire Glide window, with the file name at the top.  The menu selections are slightly different from the ones you saw on the opening screen; there is an @code{Entities} item, and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses the file extension to identify the source language, so @file{adb} indicates an Ada source file.
998
999 You will enter some of the source program lines explicitly, and use the syntax-oriented template mechanism to enter other lines.  First, type the following text:
1000 @smallexample
1001 with Ada.Text_IO; use Ada.Text_IO;
1002 procedure Hello is
1003 begin
1004 @end smallexample
1005
1006 @noindent
1007 Observe that Glide uses different colors to distinguish reserved words from identifiers.  Also, after the @code{procedure Hello is} line, the cursor is automatically indented in anticipation of declarations.  When you enter @code{begin}, Glide recognizes that there are no declarations and thus places @code{begin} flush left.  But after the @code{begin} line the cursor is again indented, where the statement(s) will be placed.
1008
1009 The main part of the program will be a @code{for} loop.  Instead of entering the text explicitly, however, use a statement template.  Select the @code{Ada} item on the top menu bar, move the mouse to the @code{Statements} item, and you will see a large selection of alternatives.  Choose @code{for loop}.  You will be prompted (at the bottom of the buffer) for a loop name; simply press the @key{Enter} key since a loop name is not needed.  You should see the beginning of a @code{for} loop appear in the source program window.  You will now be prompted for the name of the loop variable; enter a line with the identifier @code{ind} (lower case).  Note that, by default, Glide capitalizes the name (you can override such behavior if you wish, although this is outside the scope of this introduction).  Next, Glide prompts you for the loop range; enter a line containing @code{1..5} and you will see this also appear in the source program, together with the remaining elements of the @code{for} loop syntax.
1010
1011 Next enter the statement (with an intentional error, a missing semicolon) that will form the body of the loop:
1012 @smallexample
1013 Put_Line("Hello, World" & Integer'Image(I))
1014 @end smallexample
1015
1016 @noindent
1017 Finally, type @code{end Hello;} as the last line in the program.  Now save the file: choose the @code{File} menu item, and then the @code{Save buffer} selection.  You will see a message at the bottom of the buffer confirming that the file has been saved.
1018
1019 You are now ready to attempt to build the program.  Select the @code{Ada} item from the top menu bar.  Although we could choose simply to compile the file, we will instead attempt to do a build (which invokes @command{gnatmake}) since, if the compile is successful, we want to build an executable.  Thus select @code{Ada build}.  This will fail because of the compilation error, and you will notice that the Glide window has been split: the top window contains the source file, and the bottom window contains the output from the GNAT tools.  Glide allows you to navigate from a compilation error to the source file position corresponding to the error: click the middle mouse button (or simultaneously press the left and right buttons, on a two-button mouse) on the diagnostic line in the tool window.  The focus will shift to the source window, and the cursor will be positioned on the character at which the error was detected.
1020
1021 Correct the error: type in a semicolon to terminate the statement.  Although you can again save the file explicitly, you can also simply invoke @code{Ada} @result{} @code{Build} and you will be prompted to save the file.  This time the build will succeed; the tool output window shows you the options that are supplied by default.  The GNAT tools' output (e.g., object and ALI files, executable) will go in the directory from which Glide was launched.
1022
1023 To execute the program, choose @code{Ada} and then @code{Run}.  You should see the program's output displayed in the bottom window:
1024
1025 @smallexample
1026 Hello, world 1
1027 Hello, world 2
1028 Hello, world 3
1029 Hello, world 4
1030 Hello, world 5
1031 @end smallexample
1032
1033 @node Simple Debugging with GVD
1034 @subsection Simple Debugging with GVD
1035
1036 @noindent
1037 This section describes how to set breakpoints, examine/modify variables, and step through execution.
1038
1039 In order to enable debugging, you need to pass the @option{-g} switch to both the compiler and to @command{gnatlink}.  If you are using the command line, passing @option{-g} to @command{gnatmake} will have this effect.  You can then launch GVD, e.g. on the @code{hello} program, by issuing the command:
1040
1041 @smallexample
1042 $ gvd hello
1043 @end smallexample
1044
1045 @noindent
1046 If you are using Glide, then @option{-g} is passed to the relevant tools by default when you do a build.  Start the debugger by selecting the @code{Ada} menu item, and then @code{Debug}.
1047
1048 GVD comes up in a multi-part window.  One pane shows the names of files comprising your executable; another pane shows the source code of the current unit (initially your main subprogram), another pane shows the debugger output and user interactions, and the fourth pane (the data canvas at the top of the window) displays data objects that you have selected.
1049
1050 To the left of the source file pane, you will notice green dots adjacent to some lines.  These are lines for which object code exists and where breakpoints can thus be set.  You set/reset a breakpoint by clicking the green dot.  When a breakpoint is set, the dot is replaced by an @code{X} in a red circle.  Clicking the circle toggles the breakpoint off, and the red circle is replaced by the green dot.
1051
1052 For this example, set a breakpoint at the statement where @code{Put_Line} is invoked.
1053
1054 Start program execution by selecting the @code{Run} button on the top menu bar.  (The @code{Start} button will also start your program, but it will cause program execution to break at the entry to your main subprogram.)  Evidence of reaching the breakpoint will appear: the source file line will be highlighted, and the debugger interactions pane will display a relevant message.
1055
1056 You can examine the values of variables in several ways.  Move the mouse over an occurrence of @code{Ind} in the @code{for} loop, and you will see the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind} and select @code{Display Ind}; a box showing the variable's name and value will appear in the data canvas.
1057
1058 Although a loop index is a constant with respect to Ada semantics, you can change its value in the debugger.  Right-click in the box for @code{Ind}, and select the @code{Set Value of Ind} item.  Enter @code{2} as the new value, and press @command{OK}.  The box for @code{Ind} shows the update.
1059
1060 Press the @code{Step} button on the top menu bar; this will step through one line of program text (the invocation of @code{Put_Line}), and you can observe the effect of having modified @code{Ind} since the value displayed is @code{2}.
1061
1062 Remove the breakpoint, and resume execution by selecting the @code{Cont} button.  You will see the remaining output lines displayed in the debugger interaction window, along with a message confirming normal program termination.
1063
1064
1065 @node Other Glide Features
1066 @subsection Other Glide Features
1067
1068 @noindent
1069 You may have observed that some of the menu selections contain abbreviations; e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.  These are @emph{shortcut keys} that you can use instead of selecting menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead of selecting @code{Files} and then @code{Open file...}.
1070
1071 To abort a Glide command, type @key{Ctrl-g}.
1072
1073 If you want Glide to start with an existing source file, you can either launch Glide as above and then open the file via @code{Files} @result{} @code{Open file...}, or else simply pass the name of the source file on the command line:
1074
1075 @smallexample
1076 $ glide hello.adb&
1077 @end smallexample
1078
1079 @noindent
1080 While you are using Glide, a number of @emph{buffers} exist.  You create some explicitly; e.g., when you open/create a file.  Others arise as an effect of the commands that you issue; e.g., the buffer containing the output of the tools invoked during a build.  If a buffer is hidden, you can bring it into a visible window by first opening the @code{Buffers} menu and then selecting the desired entry.
1081
1082 If a buffer occupies only part of the Glide screen and you want to expand it to fill the entire screen, then click in the buffer and then select @code{Files} @result{} @code{One Window}.
1083
1084 If a window is occupied by one buffer and you want to split the window to bring up a second buffer, perform the following steps:
1085 @itemize @bullet
1086 @item Select @code{Files} @result{} @code{Split Window}; this will produce two windows each of which holds the original buffer (these are not copies, but rather different views of the same buffer contents)
1087 @item With the focus in one of the windows, select the desired buffer from the @code{Buffers} menu
1088 @end itemize
1089
1090 @noindent
1091 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1092
1093 @node The GNAT Compilation Model
1094 @chapter The GNAT Compilation Model
1095 @cindex GNAT compilation model
1096 @cindex Compilation model
1097
1098 @menu
1099 * Source Representation::
1100 * Foreign Language Representation::
1101 * File Naming Rules::
1102 * Using Other File Names::
1103 * Alternative File Naming Schemes::
1104 * Generating Object Files::
1105 * Source Dependencies::
1106 * The Ada Library Information Files::
1107 * Binding an Ada Program::
1108 * Mixed Language Programming::
1109 * Building Mixed Ada & C++ Programs::
1110 * Comparison between GNAT and C/C++ Compilation Models::
1111 * Comparison between GNAT and Conventional Ada Library Models::
1112 @end menu
1113
1114 @noindent
1115 This chapter describes the compilation model used by GNAT. Although
1116 similar to that used by other languages, such as C and C++, this model
1117 is substantially different from the traditional Ada compilation models,
1118 which are based on a library. The model is initially described without
1119 reference to the library-based model. If you have not previously used an
1120 Ada compiler, you need only read the first part of this chapter. The
1121 last section describes and discusses the differences between the GNAT
1122 model and the traditional Ada compiler models. If you have used other
1123 Ada compilers, this section will help you to understand those
1124 differences, and the advantages of the GNAT model.
1125
1126 @node Source Representation
1127 @section Source Representation
1128 @cindex Latin-1
1129
1130 @noindent
1131 Ada source programs are represented in standard text files, using
1132 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1133 7-bit ASCII set, plus additional characters used for
1134 representing foreign languages (@pxref{Foreign Language Representation}
1135 for support of non-USA character sets). The format effector characters
1136 are represented using their standard ASCII encodings, as follows:
1137
1138 @table @code
1139 @item VT
1140 @findex VT
1141 Vertical tab, @code{16#0B#}
1142
1143 @item HT
1144 @findex HT
1145 Horizontal tab, @code{16#09#}
1146
1147 @item CR
1148 @findex CR
1149 Carriage return, @code{16#0D#}
1150
1151 @item LF
1152 @findex LF
1153 Line feed, @code{16#0A#}
1154
1155 @item FF
1156 @findex FF
1157 Form feed, @code{16#0C#}
1158 @end table
1159
1160 @noindent
1161 Source files are in standard text file format. In addition, GNAT will
1162 recognize a wide variety of stream formats, in which the end of physical
1163 physical lines is marked by any of the following sequences:
1164 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1165 in accommodating files that are imported from other operating systems.
1166
1167 @cindex End of source file
1168 @cindex Source file, end
1169 @findex SUB
1170 The end of a source file is normally represented by the physical end of
1171 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1172 recognized as signalling the end of the source file. Again, this is
1173 provided for compatibility with other operating systems where this
1174 code is used to represent the end of file.
1175
1176 Each file contains a single Ada compilation unit, including any pragmas
1177 associated with the unit. For example, this means you must place a
1178 package declaration (a package @dfn{spec}) and the corresponding body in
1179 separate files. An Ada @dfn{compilation} (which is a sequence of
1180 compilation units) is represented using a sequence of files. Similarly,
1181 you will place each subunit or child unit in a separate file.
1182
1183 @node Foreign Language Representation
1184 @section Foreign Language Representation
1185
1186 @noindent
1187 GNAT supports the standard character sets defined in Ada 95 as well as
1188 several other non-standard character sets for use in localized versions
1189 of the compiler (@pxref{Character Set Control}).
1190 @menu
1191 * Latin-1::
1192 * Other 8-Bit Codes::
1193 * Wide Character Encodings::
1194 @end menu
1195
1196 @node Latin-1
1197 @subsection Latin-1
1198 @cindex Latin-1
1199
1200 @noindent
1201 The basic character set is Latin-1. This character set is defined by ISO
1202 standard 8859, part 1. The lower half (character codes @code{16#00#}
1203 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half is
1204 used to represent additional characters. These include extended letters
1205 used by European languages, such as French accents, the vowels with umlauts
1206 used in German, and the extra letter A-ring used in Swedish.
1207
1208 @findex Ada.Characters.Latin_1
1209 For a complete list of Latin-1 codes and their encodings, see the source
1210 file of library unit @code{Ada.Characters.Latin_1} in file
1211 @file{a-chlat1.ads}.
1212 You may use any of these extended characters freely in character or
1213 string literals. In addition, the extended characters that represent
1214 letters can be used in identifiers.
1215
1216 @node Other 8-Bit Codes
1217 @subsection Other 8-Bit Codes
1218
1219 @noindent
1220 GNAT also supports several other 8-bit coding schemes:
1221
1222 @table @asis
1223 @cindex Latin-2
1224 @item Latin-2
1225 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1226 equivalence.
1227
1228 @item Latin-3
1229 @cindex Latin-3
1230 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1231 equivalence.
1232
1233 @item Latin-4
1234 @cindex Latin-4
1235 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1236 equivalence.
1237
1238 @item Latin-5
1239 @cindex Latin-5
1240 @cindex Cyrillic
1241 Latin-4 letters (Cyrillic) allowed in identifiers, with uppercase and lowercase
1242 equivalence.
1243
1244 @item IBM PC (code page 437)
1245 @cindex code page 437
1246 This code page is the normal default for PCs in the U.S. It corresponds
1247 to the original IBM PC character set. This set has some, but not all, of
1248 the extended Latin-1 letters, but these letters do not have the same
1249 encoding as Latin-1. In this mode, these letters are allowed in
1250 identifiers with uppercase and lowercase equivalence.
1251
1252 @item IBM PC (code page 850)
1253 @cindex code page 850
1254 This code page is a modification of 437 extended to include all the
1255 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1256 mode, all these letters are allowed in identifiers with uppercase and
1257 lowercase equivalence.
1258
1259 @item Full Upper 8-bit
1260 Any character in the range 80-FF allowed in identifiers, and all are
1261 considered distinct. In other words, there are no uppercase and lowercase
1262 equivalences in this range. This is useful in conjunction with
1263 certain encoding schemes used for some foreign character sets (e.g.
1264 the typical method of representing Chinese characters on the PC).
1265
1266 @item No Upper-Half
1267 No upper-half characters in the range 80-FF are allowed in identifiers.
1268 This gives Ada 83 compatibility for identifier names.
1269 @end table
1270
1271 @noindent
1272 For precise data on the encodings permitted, and the uppercase and lowercase
1273 equivalences that are recognized, see the file @file{csets.adb} in
1274 the GNAT compiler sources. You will need to obtain a full source release
1275 of GNAT to obtain this file.
1276
1277 @node Wide Character Encodings
1278 @subsection Wide Character Encodings
1279
1280 @noindent
1281 GNAT allows wide character codes to appear in character and string
1282 literals, and also optionally in identifiers, by means of the following
1283 possible encoding schemes:
1284
1285 @table @asis
1286
1287 @item Hex Coding
1288 In this encoding, a wide character is represented by the following five
1289 character sequence:
1290
1291 @smallexample
1292 ESC a b c d
1293 @end smallexample
1294
1295 @noindent
1296 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1297 characters (using uppercase letters) of the wide character code. For
1298 example, ESC A345 is used to represent the wide character with code
1299 @code{16#A345#}.
1300 This scheme is compatible with use of the full Wide_Character set.
1301
1302 @item Upper-Half Coding
1303 @cindex Upper-Half Coding
1304 The wide character with encoding @code{16#abcd#} where the upper bit is on (in
1305 other words, "a" is in the range 8-F) is represented as two bytes,
1306 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1307 character, but is not required to be in the upper half. This method can
1308 be also used for shift-JIS or EUC, where the internal coding matches the
1309 external coding.
1310
1311 @item Shift JIS Coding
1312 @cindex Shift JIS Coding
1313 A wide character is represented by a two-character sequence,
1314 @code{16#ab#} and
1315 @code{16#cd#}, with the restrictions described for upper-half encoding as
1316 described above. The internal character code is the corresponding JIS
1317 character according to the standard algorithm for Shift-JIS
1318 conversion. Only characters defined in the JIS code set table can be
1319 used with this encoding method.
1320
1321 @item EUC Coding
1322 @cindex EUC Coding
1323 A wide character is represented by a two-character sequence
1324 @code{16#ab#} and
1325 @code{16#cd#}, with both characters being in the upper half. The internal
1326 character code is the corresponding JIS character according to the EUC
1327 encoding algorithm. Only characters defined in the JIS code set table
1328 can be used with this encoding method.
1329
1330 @item UTF-8 Coding
1331 A wide character is represented using
1332 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1333 10646-1/Am.2. Depending on the character value, the representation
1334 is a one, two, or three byte sequence:
1335 @smallexample
1336 @iftex
1337 @leftskip=.7cm
1338 @end iftex
1339 16#0000#-16#007f#: 2#0xxxxxxx#
1340 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1341 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1342
1343 @end smallexample
1344
1345 @noindent
1346 where the xxx bits correspond to the left-padded bits of the
1347 16-bit character value. Note that all lower half ASCII characters
1348 are represented as ASCII bytes and all upper half characters and
1349 other wide characters are represented as sequences of upper-half
1350 (The full UTF-8 scheme allows for encoding 31-bit characters as
1351 6-byte sequences, but in this implementation, all UTF-8 sequences
1352 of four or more bytes length will be treated as illegal).
1353 @item Brackets Coding
1354 In this encoding, a wide character is represented by the following eight
1355 character sequence:
1356
1357 @smallexample
1358 [ " a b c d " ]
1359 @end smallexample
1360
1361 @noindent
1362 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1363 characters (using uppercase letters) of the wide character code. For
1364 example, ["A345"] is used to represent the wide character with code
1365 @code{16#A345#}. It is also possible (though not required) to use the
1366 Brackets coding for upper half characters. For example, the code
1367 @code{16#A3#} can be represented as @code{["A3"]}.
1368
1369 This scheme is compatible with use of the full Wide_Character set,
1370 and is also the method used for wide character encoding in the standard
1371 ACVC (Ada Compiler Validation Capability) test suite distributions.
1372
1373 @end table
1374
1375 @noindent
1376 Note: Some of these coding schemes do not permit the full use of the
1377 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
1378 use of the upper half of the Latin-1 set.
1379
1380 @node File Naming Rules
1381 @section File Naming Rules
1382
1383 @noindent
1384 The default file name is determined by the name of the unit that the
1385 file contains. The name is formed by taking the full expanded name of
1386 the unit and replacing the separating dots with hyphens and using
1387 lowercase for all letters.
1388
1389 An exception arises if the file name generated by the above rules starts
1390 with one of the characters
1391 a,g,i, or s,
1392 and the second character is a
1393 minus. In this case, the character tilde is used in place
1394 of the minus. The reason for this special rule is to avoid clashes with
1395 the standard names for child units of the packages System, Ada,
1396 Interfaces, and GNAT, which use the prefixes
1397 s- a- i- and g-
1398 respectively.
1399
1400 The file extension is @file{.ads} for a spec and
1401 @file{.adb} for a body. The following list shows some
1402 examples of these rules.
1403
1404 @table @file
1405 @item main.ads
1406 Main (spec)
1407 @item main.adb
1408 Main (body)
1409 @item arith_functions.ads
1410 Arith_Functions (package spec)
1411 @item arith_functions.adb
1412 Arith_Functions (package body)
1413 @item func-spec.ads
1414 Func.Spec (child package spec)
1415 @item func-spec.adb
1416 Func.Spec (child package body)
1417 @item main-sub.adb
1418 Sub (subunit of Main)
1419 @item a~bad.adb
1420 A.Bad (child package body)
1421 @end table
1422
1423 @noindent
1424 Following these rules can result in excessively long
1425 file names if corresponding
1426 unit names are long (for example, if child units or subunits are
1427 heavily nested). An option is available to shorten such long file names
1428 (called file name "krunching"). This may be particularly useful when
1429 programs being developed with GNAT are to be used on operating systems
1430 with limited file name lengths. @xref{Using gnatkr}.
1431
1432 Of course, no file shortening algorithm can guarantee uniqueness over
1433 all possible unit names; if file name krunching is used, it is your
1434 responsibility to ensure no name clashes occur. Alternatively you
1435 can specify the exact file names that you want used, as described
1436 in the next section. Finally, if your Ada programs are migrating from a
1437 compiler with a different naming convention, you can use the gnatchop
1438 utility to produce source files that follow the GNAT naming conventions.
1439 (For details @pxref{Renaming Files Using gnatchop}.)
1440
1441 @node Using Other File Names
1442 @section Using Other File Names
1443 @cindex File names
1444
1445 @noindent
1446 In the previous section, we have described the default rules used by
1447 GNAT to determine the file name in which a given unit resides. It is
1448 often convenient to follow these default rules, and if you follow them,
1449 the compiler knows without being explicitly told where to find all
1450 the files it needs.
1451
1452 However, in some cases, particularly when a program is imported from
1453 another Ada compiler environment, it may be more convenient for the
1454 programmer to specify which file names contain which units. GNAT allows
1455 arbitrary file names to be used by means of the Source_File_Name pragma.
1456 The form of this pragma is as shown in the following examples:
1457 @cindex Source_File_Name pragma
1458
1459 @smallexample
1460 @group
1461 @cartouche
1462 @b{pragma} Source_File_Name (My_Utilities.Stacks,
1463   Spec_File_Name => "myutilst_a.ada");
1464 @b{pragma} Source_File_name (My_Utilities.Stacks,
1465   Body_File_Name => "myutilst.ada");
1466 @end cartouche
1467 @end group
1468 @end smallexample
1469
1470 @noindent
1471 As shown in this example, the first argument for the pragma is the unit
1472 name (in this example a child unit). The second argument has the form
1473 of a named association. The identifier
1474 indicates whether the file name is for a spec or a body;
1475 the file name itself is given by a string literal.
1476
1477 The source file name pragma is a configuration pragma, which means that
1478 normally it will be placed in the @file{gnat.adc}
1479 file used to hold configuration
1480 pragmas that apply to a complete compilation environment.
1481 For more details on how the @file{gnat.adc} file is created and used
1482 @pxref{Handling of Configuration Pragmas}
1483 @cindex @file{gnat.adc}
1484
1485 GNAT allows completely arbitrary file names to be specified using the
1486 source file name pragma. However, if the file name specified has an
1487 extension other than @file{.ads} or @file{.adb} it is necessary to use a special
1488 syntax when compiling the file. The name in this case must be preceded
1489 by the special sequence @code{-x} followed by a space and the name of the
1490 language, here @code{ada}, as in:
1491
1492 @smallexample
1493 $ gcc -c -x ada peculiar_file_name.sim
1494 @end smallexample
1495
1496 @noindent
1497 @code{gnatmake} handles non-standard file names in the usual manner (the
1498 non-standard file name for the main program is simply used as the
1499 argument to gnatmake). Note that if the extension is also non-standard,
1500 then it must be included in the gnatmake command, it may not be omitted.
1501
1502 @node Alternative File Naming Schemes
1503 @section Alternative File Naming Schemes
1504 @cindex File naming schemes, alternative
1505 @cindex File names
1506
1507 In the previous section, we described the use of the @code{Source_File_Name}
1508 pragma to allow arbitrary names to be assigned to individual source files.
1509 However, this approach requires one pragma for each file, and especially in
1510 large systems can result in very long @file{gnat.adc} files, and also create
1511 a maintenance problem.
1512
1513 GNAT also provides a facility for specifying systematic file naming schemes
1514 other than the standard default naming scheme previously described. An
1515 alternative scheme for naming is specified by the use of
1516 @code{Source_File_Name} pragmas having the following format:
1517 @cindex Source_File_Name pragma
1518
1519 @smallexample
1520 pragma Source_File_Name (
1521    Spec_File_Name  => FILE_NAME_PATTERN
1522  [,Casing          => CASING_SPEC]
1523  [,Dot_Replacement => STRING_LITERAL]);
1524
1525 pragma Source_File_Name (
1526    Body_File_Name  => FILE_NAME_PATTERN
1527  [,Casing          => CASING_SPEC]
1528  [,Dot_Replacement => STRING_LITERAL]);
1529
1530 pragma Source_File_Name (
1531    Subunit_File_Name  => FILE_NAME_PATTERN
1532  [,Casing             => CASING_SPEC]
1533  [,Dot_Replacement    => STRING_LITERAL]);
1534
1535 FILE_NAME_PATTERN ::= STRING_LITERAL
1536 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1537
1538 @end smallexample
1539
1540 @noindent
1541 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1542 It contains a single asterisk character, and the unit name is substituted
1543 systematically for this asterisk. The optional parameter
1544 @code{Casing} indicates
1545 whether the unit name is to be all upper-case letters, all lower-case letters,
1546 or mixed-case. If no
1547 @code{Casing} parameter is used, then the default is all
1548 lower-case.
1549
1550 The optional @code{Dot_Replacement} string is used to replace any periods
1551 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1552 argument is used then separating dots appear unchanged in the resulting
1553 file name.
1554 Although the above syntax indicates that the
1555 @code{Casing} argument must appear
1556 before the @code{Dot_Replacement} argument, but it
1557 is also permissible to write these arguments in the opposite order.
1558
1559 As indicated, it is possible to specify different naming schemes for
1560 bodies, specs, and subunits. Quite often the rule for subunits is the
1561 same as the rule for bodies, in which case, there is no need to give
1562 a separate @code{Subunit_File_Name} rule, and in this case the
1563 @code{Body_File_name} rule is used for subunits as well.
1564
1565 The separate rule for subunits can also be used to implement the rather
1566 unusual case of a compilation environment (e.g. a single directory) which
1567 contains a subunit and a child unit with the same unit name. Although
1568 both units cannot appear in the same partition, the Ada Reference Manual
1569 allows (but does not require) the possibility of the two units coexisting
1570 in the same environment.
1571
1572 The file name translation works in the following steps:
1573
1574 @itemize @bullet
1575
1576 @item
1577 If there is a specific @code{Source_File_Name} pragma for the given unit,
1578 then this is always used, and any general pattern rules are ignored.
1579
1580 @item
1581 If there is a pattern type @code{Source_File_Name} pragma that applies to
1582 the unit, then the resulting file name will be used if the file exists. If
1583 more than one pattern matches, the latest one will be tried first, and the
1584 first attempt resulting in a reference to a file that exists will be used.
1585
1586 @item
1587 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1588 for which the corresponding file exists, then the standard GNAT default
1589 naming rules are used.
1590
1591 @end itemize
1592
1593 @noindent
1594 As an example of the use of this mechanism, consider a commonly used scheme
1595 in which file names are all lower case, with separating periods copied
1596 unchanged to the resulting file name, and specs end with ".1.ada", and
1597 bodies end with ".2.ada". GNAT will follow this scheme if the following
1598 two pragmas appear:
1599
1600 @smallexample
1601 pragma Source_File_Name
1602   (Spec_File_Name => "*.1.ada");
1603 pragma Source_File_Name
1604   (Body_File_Name => "*.2.ada");
1605 @end smallexample
1606
1607 @noindent
1608 The default GNAT scheme is actually implemented by providing the following
1609 default pragmas internally:
1610
1611 @smallexample
1612 pragma Source_File_Name
1613   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1614 pragma Source_File_Name
1615   (Body_File_Name => "*.adb", Dot_Replacement => "-");
1616 @end smallexample
1617
1618 @noindent
1619 Our final example implements a scheme typically used with one of the
1620 Ada 83 compilers, where the separator character for subunits was "__"
1621 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1622 by adding @file{.ADA}, and subunits by
1623 adding @file{.SEP}. All file names were
1624 upper case. Child units were not present of course since this was an
1625 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1626 the same double underscore separator for child units.
1627
1628 @smallexample
1629 pragma Source_File_Name
1630   (Spec_File_Name => "*_.ADA",
1631    Dot_Replacement => "__",
1632    Casing = Uppercase);
1633 pragma Source_File_Name
1634   (Body_File_Name => "*.ADA",
1635    Dot_Replacement => "__",
1636    Casing = Uppercase);
1637 pragma Source_File_Name
1638   (Subunit_File_Name => "*.SEP",
1639    Dot_Replacement => "__",
1640    Casing = Uppercase);
1641 @end smallexample
1642
1643 @node Generating Object Files
1644 @section Generating Object Files
1645
1646 @noindent
1647 An Ada program consists of a set of source files, and the first step in
1648 compiling the program is to generate the corresponding object files.
1649 These are generated by compiling a subset of these source files.
1650 The files you need to compile are the following:
1651
1652 @itemize @bullet
1653 @item
1654 If a package spec has no body, compile the package spec to produce the
1655 object file for the package.
1656
1657 @item
1658 If a package has both a spec and a body, compile the body to produce the
1659 object file for the package. The source file for the package spec need
1660 not be compiled in this case because there is only one object file, which
1661 contains the code for both the spec and body of the package.
1662
1663 @item
1664 For a subprogram, compile the subprogram body to produce the object file
1665 for the subprogram. The spec, if one is present, is as usual in a
1666 separate file, and need not be compiled.
1667
1668 @item
1669 @cindex Subunits
1670 In the case of subunits, only compile the parent unit. A single object
1671 file is generated for the entire subunit tree, which includes all the
1672 subunits.
1673
1674 @item
1675 Compile child units independently of their parent units
1676 (though, of course, the spec of all the ancestor unit must be present in order
1677 to compile a child unit).
1678
1679 @item
1680 @cindex Generics
1681 Compile generic units in the same manner as any other units. The object
1682 files in this case are small dummy files that contain at most the
1683 flag used for elaboration checking. This is because GNAT always handles generic
1684 instantiation by means of macro expansion. However, it is still necessary to
1685 compile generic units, for dependency checking and elaboration purposes.
1686 @end itemize
1687
1688 @noindent
1689 The preceding rules describe the set of files that must be compiled to
1690 generate the object files for a program. Each object file has the same
1691 name as the corresponding source file, except that the extension is
1692 @file{.o} as usual.
1693
1694 You may wish to compile other files for the purpose of checking their
1695 syntactic and semantic correctness. For example, in the case where a
1696 package has a separate spec and body, you would not normally compile the
1697 spec. However, it is convenient in practice to compile the spec to make
1698 sure it is error-free before compiling clients of this spec, because such
1699 compilations will fail if there is an error in the spec.
1700
1701 GNAT provides an option for compiling such files purely for the
1702 purposes of checking correctness; such compilations are not required as
1703 part of the process of building a program. To compile a file in this
1704 checking mode, use the @option{-gnatc} switch.
1705
1706 @node Source Dependencies
1707 @section Source Dependencies
1708
1709 @noindent
1710 A given object file clearly depends on the source file which is compiled
1711 to produce it. Here we are using @dfn{depends} in the sense of a typical
1712 @code{make} utility; in other words, an object file depends on a source
1713 file if changes to the source file require the object file to be
1714 recompiled.
1715 In addition to this basic dependency, a given object may depend on
1716 additional source files as follows:
1717
1718 @itemize @bullet
1719 @item
1720 If a file being compiled @code{with}'s a unit @var{X}, the object file
1721 depends on the file containing the spec of unit @var{X}. This includes
1722 files that are @code{with}'ed implicitly either because they are parents
1723 of @code{with}'ed child units or they are run-time units required by the
1724 language constructs used in a particular unit.
1725
1726 @item
1727 If a file being compiled instantiates a library level generic unit, the
1728 object file depends on both the spec and body files for this generic
1729 unit.
1730
1731 @item
1732 If a file being compiled instantiates a generic unit defined within a
1733 package, the object file depends on the body file for the package as
1734 well as the spec file.
1735
1736 @item
1737 @findex Inline
1738 @cindex @option{-gnatn} switch
1739 If a file being compiled contains a call to a subprogram for which
1740 pragma @code{Inline} applies and inlining is activated with the
1741 @option{-gnatn} switch, the object file depends on the file containing the
1742 body of this subprogram as well as on the file containing the spec. Note
1743 that for inlining to actually occur as a result of the use of this switch,
1744 it is necessary to compile in optimizing mode.
1745
1746 @cindex @option{-gnatN} switch
1747 The use of @option{-gnatN} activates a more extensive inlining optimization
1748 that is performed by the front end of the compiler. This inlining does
1749 not require that the code generation be optimized. Like @option{-gnatn},
1750 the use of this switch generates additional dependencies.
1751
1752 @item
1753 If an object file O  depends on the proper body of a subunit through inlining
1754 or instantiation, it depends on the parent unit of the subunit. This means that
1755 any modification of the parent unit or one of its subunits affects the
1756 compilation of O.
1757
1758 @item
1759 The object file for a parent unit depends on all its subunit body files.
1760
1761 @item
1762 The previous two rules meant that for purposes of computing dependencies and
1763 recompilation, a body and all its subunits are treated as an indivisible whole.
1764
1765 @noindent
1766 These rules are applied transitively: if unit @code{A} @code{with}'s
1767 unit @code{B}, whose elaboration calls an inlined procedure in package
1768 @code{C}, the object file for unit @code{A} will depend on the body of
1769 @code{C}, in file @file{c.adb}.
1770
1771 The set of dependent files described by these rules includes all the
1772 files on which the unit is semantically dependent, as described in the
1773 Ada 95 Language Reference Manual. However, it is a superset of what the
1774 ARM describes, because it includes generic, inline, and subunit dependencies.
1775
1776 An object file must be recreated by recompiling the corresponding source
1777 file if any of the source files on which it depends are modified. For
1778 example, if the @code{make} utility is used to control compilation,
1779 the rule for an Ada object file must mention all the source files on
1780 which the object file depends, according to the above definition.
1781 The determination of the necessary
1782 recompilations is done automatically when one uses @code{gnatmake}.
1783 @end itemize
1784
1785 @node The Ada Library Information Files
1786 @section The Ada Library Information Files
1787 @cindex Ada Library Information files
1788 @cindex @file{ali} files
1789
1790 @noindent
1791 Each compilation actually generates two output files. The first of these
1792 is the normal object file that has a @file{.o} extension. The second is a
1793 text file containing full dependency information. It has the same
1794 name as the source file, but an @file{.ali} extension.
1795 This file is known as the Ada Library Information (@file{ali}) file.
1796 The following information is contained in the @file{ali} file.
1797
1798 @itemize @bullet
1799 @item
1800 Version information (indicates which version of GNAT was used to compile
1801 the unit(s) in question)
1802
1803 @item
1804 Main program information (including priority and time slice settings,
1805 as well as the wide character encoding used during compilation).
1806
1807 @item
1808 List of arguments used in the @code{gcc} command for the compilation
1809
1810 @item
1811 Attributes of the unit, including configuration pragmas used, an indication
1812 of whether the compilation was successful, exception model used etc.
1813
1814 @item
1815 A list of relevant restrictions applying to the unit (used for consistency)
1816 checking.
1817
1818 @item
1819 Categorization information (e.g. use of pragma @code{Pure}).
1820
1821 @item
1822 Information on all @code{with}'ed units, including presence of
1823 @code{Elaborate} or @code{Elaborate_All} pragmas.
1824
1825 @item
1826 Information from any @code{Linker_Options} pragmas used in the unit
1827
1828 @item
1829 Information on the use of @code{Body_Version} or @code{Version}
1830 attributes in the unit.
1831
1832 @item
1833 Dependency information. This is a list of files, together with
1834 time stamp and checksum information. These are files on which
1835 the unit depends in the sense that recompilation is required
1836 if any of these units are modified.
1837
1838 @item
1839 Cross-reference data. Contains information on all entities referenced
1840 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
1841 provide cross-reference information.
1842
1843 @end itemize
1844
1845 @noindent
1846 For a full detailed description of the format of the @file{ali} file,
1847 see the source of the body of unit @code{Lib.Writ}, contained in file
1848 @file{lib-writ.adb} in the GNAT compiler sources.
1849
1850 @node Binding an Ada Program
1851 @section Binding an Ada Program
1852
1853 @noindent
1854 When using languages such as C and C++, once the source files have been
1855 compiled the only remaining step in building an executable program
1856 is linking the object modules together. This means that it is possible to
1857 link an inconsistent version of a program, in which two units have
1858 included different versions of the same header.
1859
1860 The rules of Ada do not permit such an inconsistent program to be built.
1861 For example, if two clients have different versions of the same package,
1862 it is illegal to build a program containing these two clients.
1863 These rules are enforced by the GNAT binder, which also determines an
1864 elaboration order consistent with the Ada rules.
1865
1866 The GNAT binder is run after all the object files for a program have
1867 been created. It is given the name of the main program unit, and from
1868 this it determines the set of units required by the program, by reading the
1869 corresponding ALI files. It generates error messages if the program is
1870 inconsistent or if no valid order of elaboration exists.
1871
1872 If no errors are detected, the binder produces a main program, in Ada by
1873 default, that contains calls to the elaboration procedures of those
1874 compilation unit that require them, followed by
1875 a call to the main program. This Ada program is compiled to generate the
1876 object file for the main program. The name of
1877 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
1878 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
1879 main program unit.
1880
1881 Finally, the linker is used to build the resulting executable program,
1882 using the object from the main program from the bind step as well as the
1883 object files for the Ada units of the program.
1884
1885 @node Mixed Language Programming
1886 @section Mixed Language Programming
1887 @cindex Mixed Language Programming
1888
1889 @menu
1890 * Interfacing to C::
1891 * Calling Conventions::
1892 @end menu
1893
1894 @node Interfacing to C
1895 @subsection Interfacing to C
1896 @noindent
1897 There are two ways to
1898 build a program that contains some Ada files and some other language
1899 files depending on whether the main program is in Ada or not.
1900 If the main program is in Ada, you should proceed as follows:
1901
1902 @enumerate
1903 @item
1904 Compile the other language files to generate object files. For instance:
1905 @smallexample
1906 gcc -c file1.c
1907 gcc -c file2.c
1908 @end smallexample
1909
1910 @item
1911 Compile the Ada units to produce a set of object files and ALI
1912 files. For instance:
1913 @smallexample
1914 gnatmake -c my_main.adb
1915 @end smallexample
1916
1917 @item
1918 Run the Ada binder on the Ada main program. For instance:
1919 @smallexample
1920 gnatbind my_main.ali
1921 @end smallexample
1922
1923 @item
1924 Link the Ada main program, the Ada objects and the other language
1925 objects. For instance:
1926 @smallexample
1927 gnatlink my_main.ali file1.o file2.o
1928 @end smallexample
1929 @end enumerate
1930
1931 The three last steps can be grouped in a single command:
1932 @smallexample
1933 gnatmake my_main.adb -largs file1.o file2.o
1934 @end smallexample
1935
1936 @cindex Binder output file
1937 @noindent
1938 If the main program is in some language other than Ada, Then you may
1939 have more than one entry point in the Ada subsystem. You must use a
1940 special option of the binder to generate callable routines to initialize
1941 and finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
1942 Calls to the initialization and finalization routines must be inserted in
1943 the main program, or some other appropriate point in the code. The call to
1944 initialize the Ada units must occur before the first Ada subprogram is
1945 called, and the call to finalize the Ada units must occur after the last
1946 Ada subprogram returns. You use the same procedure for building the
1947 program as described previously. In this case, however, the binder
1948 only places the initialization and finalization subprograms into file
1949 @file{b~@var{xxx}.adb} instead of the main program.
1950 So, if the main program is not in Ada, you should proceed as follows:
1951
1952 @enumerate
1953 @item
1954 Compile the other language files to generate object files. For instance:
1955 @smallexample
1956 gcc -c file1.c
1957 gcc -c file2.c
1958 @end smallexample
1959
1960 @item
1961 Compile the Ada units to produce a set of object files and ALI
1962 files. For instance:
1963 @smallexample
1964 gnatmake -c entry_point1.adb
1965 gnatmake -c entry_point2.adb
1966 @end smallexample
1967
1968 @item
1969 Run the Ada binder on the Ada main program. For instance:
1970 @smallexample
1971 gnatbind -n entry_point1.ali entry_point2.ali
1972 @end smallexample
1973
1974 @item
1975 Link the Ada main program, the Ada objects and the other language
1976 objects. You only need to give the last entry point here. For instance:
1977 @smallexample
1978 gnatlink entry_point2.ali file1.o file2.o
1979 @end smallexample
1980 @end enumerate
1981
1982 @node Calling Conventions
1983 @subsection Calling Conventions
1984 @cindex Foreign Languages
1985 @cindex Calling Conventions
1986 GNAT follows standard calling sequence conventions and will thus interface
1987 to any other language that also follows these conventions. The following
1988 Convention identifiers are recognized by GNAT:
1989
1990 @itemize @bullet
1991 @cindex Interfacing to Ada
1992 @cindex Other Ada compilers
1993 @cindex Convention Ada
1994 @item
1995 Ada. This indicates that the standard Ada calling sequence will be
1996 used and all Ada data items may be passed without any limitations in the
1997 case where GNAT is used to generate both the caller and callee. It is also
1998 possible to mix GNAT generated code and code generated by another Ada
1999 compiler. In this case, the data types should be restricted to simple
2000 cases, including primitive types. Whether complex data types can be passed
2001 depends on the situation. Probably it is safe to pass simple arrays, such
2002 as arrays of integers or floats. Records may or may not work, depending
2003 on whether both compilers lay them out identically. Complex structures
2004 involving variant records, access parameters, tasks, or protected types,
2005 are unlikely to be able to be passed.
2006
2007 Note that in the case of GNAT running
2008 on a platform that supports DEC Ada 83, a higher degree of compatibility
2009 can be guaranteed, and in particular records are layed out in an identical
2010 manner in the two compilers. Note also that if output from two different
2011 compilers is mixed, the program is responsible for dealing with elaboration
2012 issues. Probably the safest approach is to write the main program in the
2013 version of Ada other than GNAT, so that it takes care of its own elaboration
2014 requirements, and then call the GNAT-generated adainit procedure to ensure
2015 elaboration of the GNAT components. Consult the documentation of the other
2016 Ada compiler for further details on elaboration.
2017
2018 However, it is not possible to mix the tasking run time of GNAT and
2019 DEC Ada 83, All the tasking operations must either be entirely within
2020 GNAT compiled sections of the program, or entirely within DEC Ada 83
2021 compiled sections of the program.
2022
2023 @cindex Interfacing to Assembly
2024 @cindex Convention Assembler
2025 @item
2026 Assembler. Specifies assembler as the convention. In practice this has the
2027 same effect as convention Ada (but is not equivalent in the sense of being
2028 considered the same convention).
2029
2030 @cindex Convention Asm
2031 @findex Asm
2032 @item
2033 Asm. Equivalent to Assembler.
2034
2035 @cindex Convention Asm
2036 @findex Asm
2037 @item
2038 Asm. Equivalent to Assembly.
2039
2040 @cindex Interfacing to COBOL
2041 @cindex Convention COBOL
2042 @findex COBOL
2043 @item
2044 COBOL. Data will be passed according to the conventions described
2045 in section B.4 of the Ada 95 Reference Manual.
2046
2047 @findex C
2048 @cindex Interfacing to C
2049 @cindex Convention C
2050 @item
2051 C. Data will be passed according to the conventions described
2052 in section B.3 of the Ada 95 Reference Manual.
2053
2054 @cindex Convention Default
2055 @findex Default
2056 @item
2057 Default. Equivalent to C.
2058
2059 @cindex Convention External
2060 @findex External
2061 @item
2062 External. Equivalent to C.
2063
2064 @findex C++
2065 @cindex Interfacing to C++
2066 @cindex Convention C++
2067 @item
2068 CPP. This stands for C++. For most purposes this is identical to C.
2069 See the separate description of the specialized GNAT pragmas relating to
2070 C++ interfacing for further details.
2071
2072 @findex Fortran
2073 @cindex Interfacing to Fortran
2074 @cindex Convention Fortran
2075 @item
2076 Fortran. Data will be passed according to the conventions described
2077 in section B.5 of the Ada 95 Reference Manual.
2078
2079 @item
2080 Intrinsic. This applies to an intrinsic operation, as defined in the Ada 95
2081 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
2082 this means that the body of the subprogram is provided by the compiler itself,
2083 usually by means of an efficient code sequence, and that the user does not
2084 supply an explicit body for it. In an application program, the pragma can only
2085 be applied to the following two sets of names, which the GNAT compiler
2086 recognizes.
2087 @itemize @bullet
2088 @item
2089 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
2090 Arithmetic.  The corresponding subprogram declaration must have
2091 two formal parameters. The
2092 first one must be a signed integer type or a modular type with a binary
2093 modulus, and the second parameter must be of type Natural.
2094 The return type must be the same as the type of the first argument. The size
2095 of this type can only be 8, 16, 32, or 64.
2096 @item binary arithmetic operators: "+", "-", "*", "/"
2097 The corresponding operator declaration must have parameters and result type
2098 that have the same root numeric type (for example, all three are long_float
2099 types). This simplifies the definition of operations that use type checking
2100 to perform dimensional checks:
2101 @smallexample
2102 type Distance is new Long_Float;
2103 type Time     is new Long_Float;
2104 type Velocity is new Long_Float;
2105 function "/" (D : Distance; T : Time)
2106   return Velocity;
2107 pragma Import (Intrinsic, "/");
2108 @end smallexample
2109 @noindent
2110 This common idiom is often programmed with a generic definition and an explicit
2111 body. The pragma makes it simpler to introduce such declarations. It incurs
2112 no overhead in compilation time or code size, because it is implemented as a
2113 single machine instruction.
2114 @end itemize
2115 @noindent
2116
2117 @findex Stdcall
2118 @cindex Convention Stdcall
2119 @item
2120 Stdcall. This is relevant only to NT/Win95 implementations of GNAT,
2121 and specifies that the Stdcall calling sequence will be used, as defined
2122 by the NT API.
2123
2124 @findex DLL
2125 @cindex Convention DLL
2126 @item
2127 DLL. This is equivalent to Stdcall.
2128
2129 @findex Win32
2130 @cindex Convention Win32
2131 @item
2132 Win32. This is equivalent to Stdcall.
2133
2134 @findex Stubbed
2135 @cindex Convention Stubbed
2136 @item
2137 Stubbed. This is a special convention that indicates that the compiler
2138 should provide a stub body that raises @code{Program_Error}.
2139 @end itemize
2140
2141 @noindent
2142 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2143 that can be used to parametrize conventions and allow additional synonyms
2144 to be specified. For example if you have legacy code in which the convention
2145 identifier Fortran77 was used for Fortran, you can use the configuration
2146 pragma:
2147
2148 @smallexample
2149    pragma Convention_Identifier (Fortran77, Fortran);
2150 @end smallexample
2151
2152 @noindent
2153 And from now on the identifier Fortran77 may be used as a convention
2154 identifier (for example in an @code{Import} pragma) with the same
2155 meaning as Fortran.
2156
2157 @node Building Mixed Ada & C++ Programs
2158 @section Building Mixed Ada & C++ Programs
2159
2160 @noindent
2161 Building a mixed application containing both Ada and C++ code may be a
2162 challenge for the unaware programmer. As a matter of fact, this
2163 interfacing has not been standardized in the Ada 95 reference manual due
2164 to the immaturity and lack of standard of C++ at the time. This
2165 section gives a few hints that should make this task easier. In
2166 particular the first section addresses the differences with
2167 interfacing with C. The second section looks into the delicate problem
2168 of linking the complete application from its Ada and C++ parts. The last
2169 section give some hints on how the GNAT run time can be adapted in order
2170 to allow inter-language dispatching with a new C++ compiler.
2171
2172 @menu
2173 * Interfacing to C++::
2174 * Linking a Mixed C++ & Ada Program::
2175 * A Simple Example::
2176 * Adapting the Run Time to a New C++ Compiler::
2177 @end menu
2178
2179 @node Interfacing to C++
2180 @subsection Interfacing to C++
2181
2182 @noindent
2183 GNAT supports interfacing with C++ compilers generating code that is
2184 compatible with the standard Application Binary Interface of the given
2185 platform.
2186
2187 @noindent
2188 Interfacing can be done at 3 levels: simple data, subprograms and
2189 classes. In the first 2 cases, GNAT offer a specific @var{Convention
2190 CPP} that behaves exactly like @var{Convention C}. Usually C++ mangle
2191 names of subprograms and currently GNAT does not provide any help to
2192 solve the demangling problem. This problem can be addressed in 2 ways:
2193 @itemize @bullet
2194 @item
2195 by modifying the C++ code in order to force a C convention using
2196 the @var{extern "C"} syntax.
2197
2198 @item
2199 by figuring out the mangled name and use it as the Link_Name argument of
2200 the pragma import.
2201 @end itemize
2202
2203 @noindent
2204 Interfacing at the class level can be achieved by using the GNAT specific
2205 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
2206 Reference Manual for additional information.
2207
2208 @node Linking a Mixed C++ & Ada Program
2209 @subsection Linking a Mixed C++ & Ada Program
2210
2211 @noindent
2212 Usually the linker of the C++ development system must be used to link
2213 mixed applications because most C++ systems will resolve elaboration
2214 issues (such as calling constructors on global class instances)
2215 transparently during the link phase. GNAT has been adapted to ease the
2216 use of a foreign linker for the last phase. Three cases can be
2217 considered:
2218 @enumerate
2219
2220 @item
2221 Using GNAT and G++ (GNU C++ compiler) from the same GCC
2222 installation. The c++ linker can simply be called by using the c++
2223 specific driver called @code{c++}. Note that this setup is not
2224 very common because it may request recompiling the whole GCC
2225 tree from sources and it does not allow to upgrade easily to a new
2226 version of one compiler for one of the two languages without taking the
2227 risk of destabilizing the other.
2228
2229 @smallexample
2230 $ c++ -c file1.C
2231 $ c++ -c file2.C
2232 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
2233 @end smallexample
2234
2235 @item
2236 Using GNAT and G++ from 2 different GCC installations. If both compilers
2237 are on the PATH, the same method can be used. It is important to be
2238 aware that environment variables such as C_INCLUDE_PATH,
2239 GCC_EXEC_PREFIX, BINUTILS_ROOT or GCC_ROOT will affect both compilers at
2240 the same time and thus may make one of the 2 compilers operate
2241 improperly if they are set for the other. In particular it is important
2242 that the link command has access to the proper gcc library @file{libgcc.a},
2243 that is to say the one that is part of the C++ compiler
2244 installation. The implicit link command as suggested in the gnatmake
2245 command from the former example can be replaced by an explicit link
2246 command with full verbosity in order to verify which library is used:
2247 @smallexample
2248 $ gnatbind ada_unit
2249 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2250 @end smallexample
2251 If there is a problem due to interfering environment variables, it can
2252 be workaround by using an intermediate script. The following example
2253 shows the proper script to use when GNAT has not been installed at its
2254 default location and g++ has been installed at its default location:
2255
2256 @smallexample
2257 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2258 $ cat ./my_script
2259 #!/bin/sh
2260 unset BINUTILS_ROOT
2261 unset GCC_ROOT
2262 c++ $*
2263 @end smallexample
2264
2265 @item
2266 Using a non GNU C++ compiler. The same set of command as previously
2267 described can be used to insure that the c++ linker is
2268 used. Nonetheless, you need to add the path to libgcc explicitely, since some
2269 libraries needed by GNAT are located in this directory:
2270
2271 @smallexample
2272
2273 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2274 $ cat ./my_script
2275 #!/bin/sh
2276 CC $* `gcc -print-libgcc-file-name`
2277
2278 @end smallexample
2279
2280 Where CC is the name of the non GNU C++ compiler.
2281
2282 @end enumerate
2283
2284 @node A Simple Example
2285 @subsection  A Simple Example
2286 @noindent
2287 The following example, provided as part of the GNAT examples, show how
2288 to achieve procedural interfacing between Ada and C++ in both
2289 directions. The C++ class A has 2 methods. The first method is exported
2290 to Ada by the means of an extern C wrapper function. The second method
2291 calls an Ada subprogram. On the Ada side, The C++ calls is modelized by
2292 a limited record with a layout comparable to the C++ class. The Ada
2293 subprogram, in turn, calls the c++ method. So from the C++ main program
2294 the code goes back and forth between the 2 languages.
2295
2296 @noindent
2297 Here are the compilation commands
2298 for native configurations:
2299 @smallexample
2300 $ gnatmake -c simple_cpp_interface
2301 $ c++ -c cpp_main.C
2302 $ c++ -c ex7.C
2303 $ gnatbind -n simple_cpp_interface
2304 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
2305       -lstdc++ ex7.o cpp_main.o
2306 @end smallexample
2307 @noindent
2308 Here are the corresponding sources:
2309 @smallexample
2310
2311 //cpp_main.C
2312
2313 #include "ex7.h"
2314
2315 extern "C" @{
2316   void adainit (void);
2317   void adafinal (void);
2318   void method1 (A *t);
2319 @}
2320
2321 void method1 (A *t)
2322 @{
2323   t->method1 ();
2324 @}
2325
2326 int main ()
2327 @{
2328   A obj;
2329   adainit ();
2330   obj.method2 (3030);
2331   adafinal ();
2332 @}
2333
2334 //ex7.h
2335
2336 class Origin @{
2337  public:
2338   int o_value;
2339 @};
2340 class A : public Origin @{
2341  public:
2342   void method1 (void);
2343   virtual void method2 (int v);
2344   A();
2345   int   a_value;
2346 @};
2347
2348 //ex7.C
2349
2350 #include "ex7.h"
2351 #include <stdio.h>
2352
2353 extern "C" @{ void ada_method2 (A *t, int v);@}
2354
2355 void A::method1 (void)
2356 @{
2357   a_value = 2020;
2358   printf ("in A::method1, a_value = %d \n",a_value);
2359
2360 @}
2361
2362 void A::method2 (int v)
2363 @{
2364    ada_method2 (this, v);
2365    printf ("in A::method2, a_value = %d \n",a_value);
2366
2367 @}
2368
2369 A::A(void)
2370 @{
2371    a_value = 1010;
2372   printf ("in A::A, a_value = %d \n",a_value);
2373 @}
2374
2375 -- Ada sources
2376 @b{package} @b{body} Simple_Cpp_Interface @b{is}
2377
2378    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
2379    @b{begin}
2380       Method1 (This);
2381       This.A_Value := V;
2382    @b{end} Ada_Method2;
2383
2384 @b{end} Simple_Cpp_Interface;
2385
2386 @b{package} Simple_Cpp_Interface @b{is}
2387    @b{type} A @b{is} @b{limited}
2388       @b{record}
2389          O_Value : Integer;
2390          A_Value : Integer;
2391       @b{end} @b{record};
2392    @b{pragma} Convention (C, A);
2393
2394    @b{procedure} Method1 (This : @b{in} @b{out} A);
2395    @b{pragma} Import (C, Method1);
2396
2397    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
2398    @b{pragma} Export (C, Ada_Method2);
2399
2400 @b{end} Simple_Cpp_Interface;
2401 @end smallexample
2402
2403 @node Adapting the Run Time to a New C++ Compiler
2404 @subsection Adapting the Run Time to a New C++ Compiler
2405 @noindent
2406 GNAT offers the capability to derive Ada 95 tagged types directly from
2407 preexisting C++ classes and . See "Interfacing with C++" in the GNAT
2408 reference manual. The mechanism used by GNAT for achieving such a goal
2409 has been made user configurable through a GNAT library unit
2410 @code{Interfaces.CPP}. The default version of this file is adapted to
2411 the GNU c++ compiler. Internal knowledge of the virtual
2412 table layout used by the new C++ compiler is needed to configure
2413 properly this unit. The Interface of this unit is known by the compiler
2414 and cannot be changed except for the value of the constants defining the
2415 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
2416 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
2417 of this unit for more details.
2418
2419 @node Comparison between GNAT and C/C++ Compilation Models
2420 @section Comparison between GNAT and C/C++ Compilation Models
2421
2422 @noindent
2423 The GNAT model of compilation is close to the C and C++ models. You can
2424 think of Ada specs as corresponding to header files in C. As in C, you
2425 don't need to compile specs; they are compiled when they are used. The
2426 Ada @code{with} is similar in effect to the @code{#include} of a C
2427 header.
2428
2429 One notable difference is that, in Ada, you may compile specs separately
2430 to check them for semantic and syntactic accuracy. This is not always
2431 possible with C headers because they are fragments of programs that have
2432 less specific syntactic or semantic rules.
2433
2434 The other major difference is the requirement for running the binder,
2435 which performs two important functions. First, it checks for
2436 consistency. In C or C++, the only defense against assembling
2437 inconsistent programs lies outside the compiler, in a makefile, for
2438 example. The binder satisfies the Ada requirement that it be impossible
2439 to construct an inconsistent program when the compiler is used in normal
2440 mode.
2441
2442 @cindex Elaboration order control
2443 The other important function of the binder is to deal with elaboration
2444 issues. There are also elaboration issues in C++ that are handled
2445 automatically. This automatic handling has the advantage of being
2446 simpler to use, but the C++ programmer has no control over elaboration.
2447 Where @code{gnatbind} might complain there was no valid order of
2448 elaboration, a C++ compiler would simply construct a program that
2449 malfunctioned at run time.
2450
2451 @node Comparison between GNAT and Conventional Ada Library Models
2452 @section Comparison between GNAT and Conventional Ada Library Models
2453
2454 @noindent
2455 This section is intended to be useful to Ada programmers who have
2456 previously used an Ada compiler implementing the traditional Ada library
2457 model, as described in the Ada 95 Language Reference Manual. If you
2458 have not used such a system, please go on to the next section.
2459
2460 @cindex GNAT library
2461 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
2462 source files themselves acts as the library. Compiling Ada programs does
2463 not generate any centralized information, but rather an object file and
2464 a ALI file, which are of interest only to the binder and linker.
2465 In a traditional system, the compiler reads information not only from
2466 the source file being compiled, but also from the centralized library.
2467 This means that the effect of a compilation depends on what has been
2468 previously compiled. In particular:
2469
2470 @itemize @bullet
2471 @item
2472 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2473 to the version of the unit most recently compiled into the library.
2474
2475 @item
2476 Inlining is effective only if the necessary body has already been
2477 compiled into the library.
2478
2479 @item
2480 Compiling a unit may obsolete other units in the library.
2481 @end itemize
2482
2483 @noindent
2484 In GNAT, compiling one unit never affects the compilation of any other
2485 units because the compiler reads only source files. Only changes to source
2486 files can affect the results of a compilation. In particular:
2487
2488 @itemize @bullet
2489 @item
2490 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2491 to the source version of the unit that is currently accessible to the
2492 compiler.
2493
2494 @item
2495 @cindex Inlining
2496 Inlining requires the appropriate source files for the package or
2497 subprogram bodies to be available to the compiler. Inlining is always
2498 effective, independent of the order in which units are complied.
2499
2500 @item
2501 Compiling a unit never affects any other compilations. The editing of
2502 sources may cause previous compilations to be out of date if they
2503 depended on the source file being modified.
2504 @end itemize
2505
2506 @noindent
2507 The most important result of these differences is that order of compilation
2508 is never significant in GNAT. There is no situation in which one is
2509 required to do one compilation before another. What shows up as order of
2510 compilation requirements in the traditional Ada library becomes, in
2511 GNAT, simple source dependencies; in other words, there is only a set
2512 of rules saying what source files must be present when a file is
2513 compiled.
2514
2515 @node Compiling Using gcc
2516 @chapter Compiling Using @code{gcc}
2517
2518 @noindent
2519 This chapter discusses how to compile Ada programs using the @code{gcc}
2520 command. It also describes the set of switches
2521 that can be used to control the behavior of the compiler.
2522 @menu
2523 * Compiling Programs::
2524 * Switches for gcc::
2525 * Search Paths and the Run-Time Library (RTL)::
2526 * Order of Compilation Issues::
2527 * Examples::
2528 @end menu
2529
2530 @node Compiling Programs
2531 @section Compiling Programs
2532
2533 @noindent
2534 The first step in creating an executable program is to compile the units
2535 of the program using the @code{gcc} command. You must compile the
2536 following files:
2537
2538 @itemize @bullet
2539 @item
2540 the body file (@file{.adb}) for a library level subprogram or generic
2541 subprogram
2542
2543 @item
2544 the spec file (@file{.ads}) for a library level package or generic
2545 package that has no body
2546
2547 @item
2548 the body file (@file{.adb}) for a library level package
2549 or generic package that has a body
2550
2551 @end itemize
2552
2553 @noindent
2554 You need @emph{not} compile the following files
2555
2556 @itemize @bullet
2557
2558 @item
2559 the spec of a library unit which has a body
2560
2561 @item
2562 subunits
2563 @end itemize
2564
2565 @noindent
2566 because they are compiled as part of compiling related units. GNAT
2567 package specs
2568 when the corresponding body is compiled, and subunits when the parent is
2569 compiled.
2570 @cindex No code generated
2571 If you attempt to compile any of these files, you will get one of the
2572 following error messages (where fff is the name of the file you compiled):
2573
2574 @smallexample
2575 No code generated for file @var{fff} (@var{package spec})
2576 No code generated for file @var{fff} (@var{subunit})
2577 @end smallexample
2578
2579 @noindent
2580 The basic command for compiling a file containing an Ada unit is
2581
2582 @smallexample
2583 $ gcc -c [@var{switches}] @file{file name}
2584 @end smallexample
2585
2586 @noindent
2587 where @var{file name} is the name of the Ada file (usually
2588 having an extension
2589 @file{.ads} for a spec or @file{.adb} for a body).
2590 You specify the
2591 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
2592 The result of a successful compilation is an object file, which has the
2593 same name as the source file but an extension of @file{.o} and an Ada
2594 Library Information (ALI) file, which also has the same name as the
2595 source file, but with @file{.ali} as the extension. GNAT creates these
2596 two output files in the current directory, but you may specify a source
2597 file in any directory using an absolute or relative path specification
2598 containing the directory information.
2599
2600 @findex gnat1
2601 @code{gcc} is actually a driver program that looks at the extensions of
2602 the file arguments and loads the appropriate compiler. For example, the
2603 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
2604 These programs are in directories known to the driver program (in some
2605 configurations via environment variables you set), but need not be in
2606 your path. The @code{gcc} driver also calls the assembler and any other
2607 utilities needed to complete the generation of the required object
2608 files.
2609
2610 It is possible to supply several file names on the same @code{gcc}
2611 command. This causes @code{gcc} to call the appropriate compiler for
2612 each file. For example, the following command lists three separate
2613 files to be compiled:
2614
2615 @smallexample
2616 $ gcc -c x.adb y.adb z.c
2617 @end smallexample
2618
2619 @noindent
2620 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
2621 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
2622 The compiler generates three object files @file{x.o}, @file{y.o} and
2623 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
2624 Ada compilations. Any switches apply to all the files listed,
2625 except for
2626 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
2627
2628 @node Switches for gcc
2629 @section Switches for @code{gcc}
2630
2631 @noindent
2632 The @code{gcc} command accepts switches that control the
2633 compilation process. These switches are fully described in this section.
2634 First we briefly list all the switches, in alphabetical order, then we
2635 describe the switches in more detail in functionally grouped sections.
2636
2637 @menu
2638 * Output and Error Message Control::
2639 * Debugging and Assertion Control::
2640 * Run-Time Checks::
2641 * Stack Overflow Checking::
2642 * Run-Time Control::
2643 * Validity Checking::
2644 * Style Checking::
2645 * Using gcc for Syntax Checking::
2646 * Using gcc for Semantic Checking::
2647 * Compiling Ada 83 Programs::
2648 * Character Set Control::
2649 * File Naming Control::
2650 * Subprogram Inlining Control::
2651 * Auxiliary Output Control::
2652 * Debugging Control::
2653 * Units to Sources Mapping Files::
2654 @end menu
2655
2656 @table @code
2657 @cindex @code{-b} (@code{gcc})
2658 @item -b @var{target}
2659 Compile your program to run on @var{target}, which is the name of a
2660 system configuration. You must have a GNAT cross-compiler built if
2661 @var{target} is not the same as your host system.
2662
2663 @item -B@var{dir}
2664 @cindex @code{-B} (@code{gcc})
2665 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
2666 from @var{dir} instead of the default location. Only use this switch
2667 when multiple versions of the GNAT compiler are available. See the
2668 @code{gcc} manual page for further details. You would normally use the
2669 @code{-b} or @code{-V} switch instead.
2670
2671 @item -c
2672 @cindex @code{-c} (@code{gcc})
2673 Compile. Always use this switch when compiling Ada programs.
2674
2675 Note: for some other languages when using @code{gcc}, notably in
2676 the case of C and C++, it is possible to use
2677 use @code{gcc} without a @code{-c} switch to
2678 compile and link in one step. In the case of GNAT, you
2679 cannot use this approach, because the binder must be run
2680 and @code{gcc} cannot be used to run the GNAT binder.
2681
2682 @item -g
2683 @cindex @code{-g} (@code{gcc})
2684 Generate debugging information. This information is stored in the object
2685 file and copied from there to the final executable file by the linker,
2686 where it can be read by the debugger. You must use the
2687 @code{-g} switch if you plan on using the debugger.
2688
2689 @item -I@var{dir}
2690 @cindex @code{-I} (@code{gcc})
2691 @cindex RTL
2692 Direct GNAT to search the @var{dir} directory for source files needed by
2693 the current compilation
2694 (@pxref{Search Paths and the Run-Time Library (RTL)}).
2695
2696 @item -I-
2697 @cindex @code{-I-} (@code{gcc})
2698 @cindex RTL
2699 Except for the source file named in the command line, do not look for source files
2700 in the directory containing the source file named in the command line
2701 (@pxref{Search Paths and the Run-Time Library (RTL)}).
2702
2703 @item -o @var{file}
2704 @cindex @code{-o} (@code{gcc})
2705 This switch is used in @code{gcc} to redirect the generated object file
2706 and its associated ALI file. Beware of this switch with GNAT, because it may
2707 cause the object file and ALI file to have different names which in turn
2708 may confuse the binder and the linker.
2709
2710 @item -O[@var{n}]
2711 @cindex @code{-O} (@code{gcc})
2712 @var{n} controls the optimization level.
2713
2714 @table @asis
2715 @item n = 0
2716 No optimization, the default setting if no @code{-O} appears
2717
2718 @item n = 1
2719 Normal optimization, the default if you specify @code{-O} without
2720 an operand.
2721
2722 @item n = 2
2723 Extensive optimization
2724
2725 @item n = 3
2726 Extensive optimization with automatic inlining. This applies only to
2727 inlining within a unit. For details on control of inter-unit inlining
2728 see @xref{Subprogram Inlining Control}.
2729 @end table
2730
2731
2732 @item --RTS=@var{rts-path}
2733 @cindex @code{--RTS} (@code{gcc})
2734 Specifies the default location of the runtime library. Same meaning as the
2735 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
2736
2737 @item -S
2738 @cindex @code{-S} (@code{gcc})
2739 Used in place of @code{-c} to
2740 cause the assembler source file to be
2741 generated, using @file{.s} as the extension,
2742 instead of the object file.
2743 This may be useful if you need to examine the generated assembly code.
2744
2745 @item -v
2746 @cindex @code{-v} (@code{gcc})
2747 Show commands generated by the @code{gcc} driver. Normally used only for
2748 debugging purposes or if you need to be sure what version of the
2749 compiler you are executing.
2750
2751 @item -V @var{ver}
2752 @cindex @code{-V} (@code{gcc})
2753 Execute @var{ver} version of the compiler. This is the @code{gcc}
2754 version, not the GNAT version.
2755
2756 @item -gnata
2757 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
2758 activated.
2759
2760 @item -gnatA
2761 Avoid processing @file{gnat.adc}. If a gnat.adc file is present, it will be ignored.
2762
2763 @item -gnatb
2764 Generate brief messages to @file{stderr} even if verbose mode set.
2765
2766 @item -gnatc
2767 Check syntax and semantics only (no code generation attempted).
2768
2769 @item -gnatC
2770 Compress debug information and external symbol name table entries.
2771
2772 @item -gnatD
2773 Output expanded source files for source level debugging. This switch
2774 also suppress generation of cross-reference information (see -gnatx).
2775
2776 @item -gnatec@var{path}
2777 Specify a configuration pragma file. (see @ref{The Configuration Pragmas Files})
2778
2779 @item -gnatem@var{path}
2780 Specify a mapping file. (see @ref{Units to Sources Mapping Files})
2781
2782 @item -gnatE
2783 Full dynamic elaboration checks.
2784
2785 @item -gnatf
2786 Full errors. Multiple errors per line, all undefined references.
2787
2788 @item -gnatF
2789 Externals names are folded to all uppercase.
2790
2791 @item -gnatg
2792 Internal GNAT implementation mode. This should not be used for
2793 applications programs, it is intended only for use by the compiler
2794 and its run-time library. For documentation, see the GNAT sources.
2795
2796 @item -gnatG
2797 List generated expanded code in source form.
2798
2799 @item -gnati@var{c}
2800 Identifier character set
2801 (@var{c}=1/2/3/4/8/9/p/f/n/w).
2802
2803 @item -gnath
2804 Output usage information. The output is written to @file{stdout}.
2805
2806 @item -gnatk@var{n}
2807 Limit file names to @var{n} (1-999) characters (@code{k} = krunch).
2808
2809 @item -gnatl
2810 Output full source listing with embedded error messages.
2811
2812 @item -gnatm@var{n}
2813 Limit number of detected errors to @var{n} (1-999).
2814
2815 @item -gnatn
2816 Activate inlining across unit boundaries for subprograms for which
2817 pragma @code{inline} is specified.
2818
2819 @item -gnatN
2820 Activate front end inlining.
2821
2822 @item -fno-inline
2823 Suppresses all inlining, even if other optimization or inlining switches
2824 are set.
2825
2826 @item -fstack-check
2827 Activates stack checking. See separate section on stack checking for
2828 details of the use of this option.
2829
2830 @item -gnato
2831 Enable numeric overflow checking (which is not normally enabled by
2832 default). Not that division by zero is a separate check that is not
2833 controlled by this switch (division by zero checking is on by default).
2834
2835 @item -gnatp
2836 Suppress all checks.
2837
2838 @item -gnatq
2839 Don't quit; try semantics, even if parse errors.
2840
2841 @item -gnatQ
2842 Don't quit; generate @file{ali} and tree files even if illegalities.
2843
2844 @item -gnatP
2845 Enable polling. This is required on some systems (notably Windows NT) to
2846 obtain asynchronous abort and asynchronous transfer of control capability.
2847 See the description of pragma Polling in the GNAT Reference Manual for
2848 full details.
2849
2850 @item -gnatR[0/1/2/3][s]
2851 Output representation information for declared types and objects.
2852
2853 @item -gnats
2854 Syntax check only.
2855
2856 @item -gnatt
2857 Tree output file to be generated.
2858
2859 @item -gnatT nnn
2860 Set time slice to specified number of microseconds
2861
2862 @item -gnatu
2863 List units for this compilation.
2864
2865 @item -gnatU
2866 Tag all error messages with the unique string "error:"
2867
2868 @item -gnatv
2869 Verbose mode. Full error output with source lines to @file{stdout}.
2870
2871 @item -gnatV
2872 Control level of validity checking. See separate section describing
2873 this feature.
2874
2875 @item -gnatwxxx@var{xxx}
2876 Warning mode where
2877 @var{xxx} is a string of options describing the exact warnings that
2878 are enabled or disabled. See separate section on warning control.
2879
2880 @item -gnatW@var{e}
2881 Wide character encoding method
2882 (@var{e}=n/h/u/s/e/8).
2883
2884 @item -gnatx
2885 Suppress generation of cross-reference information.
2886
2887 @item -gnaty
2888 Enable built-in style checks. See separate section describing this feature.
2889
2890 @item -gnatz@var{m}
2891 Distribution stub generation and compilation
2892 (@var{m}=r/c for receiver/caller stubs).
2893
2894 @item -gnat83
2895 Enforce Ada 83 restrictions.
2896
2897 @item -pass-exit-codes
2898 Catch exit codes from the compiler and use the most meaningful as
2899 exit status.
2900 @end table
2901
2902 You may combine a sequence of GNAT switches into a single switch. For
2903 example, the combined switch
2904
2905 @cindex Combining GNAT switches
2906 @smallexample
2907 -gnatofi3
2908 @end smallexample
2909
2910 @noindent
2911 is equivalent to specifying the following sequence of switches:
2912
2913 @smallexample
2914 -gnato -gnatf -gnati3
2915 @end smallexample
2916
2917 @noindent
2918 The following restrictions apply to the combination of switches
2919 in this manner:
2920
2921 @itemize @bullet
2922 @item
2923 The switch @option{-gnatc} if combined with other switches must come
2924 first in the string.
2925
2926 @item
2927 The switch @option{-gnats} if combined with other switches must come
2928 first in the string.
2929
2930 @item
2931 Once a "y" appears in the string (that is a use of the @option{-gnaty}
2932 switch), then all further characters in the switch are interpreted
2933 as style modifiers (see description of @option{-gnaty}).
2934
2935 @item
2936 Once a "d" appears in the string (that is a use of the @option{-gnatd}
2937 switch), then all further characters in the switch are interpreted
2938 as debug flags (see description of @option{-gnatd}).
2939
2940 @item
2941 Once a "w" appears in the string (that is a use of the @option{-gnatw}
2942 switch), then all further characters in the switch are interpreted
2943 as warning mode modifiers (see description of @option{-gnatw}).
2944
2945 @item
2946 Once a "V" appears in the string (that is a use of the @option{-gnatV}
2947 switch), then all further characters in the switch are interpreted
2948 as validity checking options (see description of @option{-gnatV}).
2949
2950 @end itemize
2951
2952 @node Output and Error Message Control
2953 @subsection Output and Error Message Control
2954 @findex stderr
2955
2956 @noindent
2957 The standard default format for error messages is called "brief format."
2958 Brief format messages are written to @file{stderr} (the standard error
2959 file) and have the following form:
2960
2961 @smallexample
2962 @iftex
2963 @leftskip=.7cm
2964 @end iftex
2965 e.adb:3:04: Incorrect spelling of keyword "function"
2966 e.adb:4:20: ";" should be "is"
2967 @end smallexample
2968
2969 @noindent
2970 The first integer after the file name is the line number in the file,
2971 and the second integer is the column number within the line.
2972 @code{glide} can parse the error messages
2973 and point to the referenced character.
2974 The following switches provide control over the error message
2975 format:
2976
2977 @table @code
2978 @item -gnatv
2979 @cindex @option{-gnatv} (@code{gcc})
2980 @findex stdout
2981 The v stands for verbose.
2982 The effect of this setting is to write long-format error
2983 messages to @file{stdout} (the standard output file.
2984 The same program compiled with the
2985 @option{-gnatv} switch would generate:
2986
2987 @smallexample
2988 @group
2989 @cartouche
2990 3. funcion X (Q : Integer)
2991    |
2992 >>> Incorrect spelling of keyword "function"
2993 4. return Integer;
2994                  |
2995 >>> ";" should be "is"
2996 @end cartouche
2997 @end group
2998 @end smallexample
2999
3000 @noindent
3001 The vertical bar indicates the location of the error, and the @samp{>>>}
3002 prefix can be used to search for error messages. When this switch is
3003 used the only source lines output are those with errors.
3004
3005 @item -gnatl
3006 @cindex @option{-gnatl} (@code{gcc})
3007 The @code{l} stands for list.
3008 This switch causes a full listing of
3009 the file to be generated. The output might look as follows:
3010
3011 @smallexample
3012 @group
3013 @cartouche
3014  1. procedure E is
3015  2.    V : Integer;
3016  3.    funcion X (Q : Integer)
3017        |
3018     >>> Incorrect spelling of keyword "function"
3019  4.     return Integer;
3020                       |
3021     >>> ";" should be "is"
3022  5.    begin
3023  6.       return Q + Q;
3024  7.    end;
3025  8. begin
3026  9.    V := X + X;
3027 10.end E;
3028 @end cartouche
3029 @end group
3030 @end smallexample
3031
3032 @noindent
3033 @findex stderr
3034 When you specify the @option{-gnatv} or @option{-gnatl} switches and
3035 standard output is redirected, a brief summary is written to
3036 @file{stderr} (standard error) giving the number of error messages and
3037 warning messages generated.
3038
3039 @item -gnatU
3040 @cindex @option{-gnatU} (@code{gcc})
3041 This switch forces all error messages to be preceded by the unique
3042 string "error:". This means that error messages take a few more
3043 characters in space, but allows easy searching for and identification
3044 of error messages.
3045
3046 @item -gnatb
3047 @cindex @option{-gnatb} (@code{gcc})
3048 The @code{b} stands for brief.
3049 This switch causes GNAT to generate the
3050 brief format error messages to @file{stderr} (the standard error
3051 file) as well as the verbose
3052 format message or full listing (which as usual is written to
3053 @file{stdout} (the standard output file).
3054
3055 @item -gnatm@var{n}
3056 @cindex @option{-gnatm} (@code{gcc})
3057 The @code{m} stands for maximum.
3058 @var{n} is a decimal integer in the
3059 range of 1 to 999 and limits the number of error messages to be
3060 generated. For example, using @option{-gnatm2} might yield
3061
3062 @smallexample
3063 @iftex
3064 @leftskip=.7cm
3065 @end iftex
3066 e.adb:3:04: Incorrect spelling of keyword "function"
3067 e.adb:5:35: missing ".."
3068 fatal error: maximum errors reached
3069 compilation abandoned
3070 @end smallexample
3071
3072 @item -gnatf
3073 @cindex @option{-gnatf} (@code{gcc})
3074 @cindex Error messages, suppressing
3075 The @code{f} stands for full.
3076 Normally, the compiler suppresses error messages that are likely to be
3077 redundant. This switch causes all error
3078 messages to be generated. In particular, in the case of
3079 references to undefined variables. If a given variable is referenced
3080 several times, the normal format of messages is
3081 @smallexample
3082 @iftex
3083 @leftskip=.7cm
3084 @end iftex
3085 e.adb:7:07: "V" is undefined (more references follow)
3086 @end smallexample
3087
3088 @noindent
3089 where the parenthetical comment warns that there are additional
3090 references to the variable @code{V}. Compiling the same program with the
3091 @option{-gnatf} switch yields
3092
3093 @smallexample
3094 e.adb:7:07: "V" is undefined
3095 e.adb:8:07: "V" is undefined
3096 e.adb:8:12: "V" is undefined
3097 e.adb:8:16: "V" is undefined
3098 e.adb:9:07: "V" is undefined
3099 e.adb:9:12: "V" is undefined
3100 @end smallexample
3101
3102 @item -gnatq
3103 @cindex @option{-gnatq} (@code{gcc})
3104 The @code{q} stands for quit (really "don't quit").
3105 In normal operation mode, the compiler first parses the program and
3106 determines if there are any syntax errors. If there are, appropriate
3107 error messages are generated and compilation is immediately terminated.
3108 This switch tells
3109 GNAT to continue with semantic analysis even if syntax errors have been
3110 found. This may enable the detection of more errors in a single run. On
3111 the other hand, the semantic analyzer is more likely to encounter some
3112 internal fatal error when given a syntactically invalid tree.
3113
3114 @item -gnatQ
3115 In normal operation mode, the @file{ali} file is not generated if any
3116 illegalities are detected in the program. The use of @option{-gnatQ} forces
3117 generation of the @file{ali} file. This file is marked as being in
3118 error, so it cannot be used for binding purposes, but it does contain
3119 reasonably complete cross-reference information, and thus may be useful
3120 for use by tools (e.g. semantic browsing tools or integrated development
3121 environments) that are driven from the @file{ali} file.
3122
3123 In addition, if @option{-gnatt} is also specified, then the tree file is
3124 generated even if there are illegalities. It may be useful in this case
3125 to also specify @option{-gnatq} to ensure that full semantic processing
3126 occurs. The resulting tree file can be processed by ASIS, for the purpose
3127 of providing partial information about illegal units, but if the error
3128 causes the tree to be badly malformed, then ASIS may crash during the
3129 analysis.
3130
3131 @end table
3132
3133 @noindent
3134 In addition to error messages, which correspond to illegalities as defined
3135 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
3136 situations.
3137
3138 @cindex Warning messages
3139 First, the compiler considers some constructs suspicious and generates a
3140 warning message to alert you to a possible error. Second, if the
3141 compiler detects a situation that is sure to raise an exception at
3142 run time, it generates a warning message. The following shows an example
3143 of warning messages:
3144 @smallexample
3145 @iftex
3146 @leftskip=.2cm
3147 @end iftex
3148 e.adb:4:24: warning: creation of object may raise Storage_Error
3149 e.adb:10:17: warning: static value out of range
3150 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
3151
3152 @end smallexample
3153
3154 @noindent
3155 GNAT considers a large number of situations as appropriate
3156 for the generation of warning messages. As always, warnings are not
3157 definite indications of errors. For example, if you do an out-of-range
3158 assignment with the deliberate intention of raising a
3159 @code{Constraint_Error} exception, then the warning that may be
3160 issued does not indicate an error. Some of the situations for which GNAT
3161 issues warnings (at least some of the time) are given in the following
3162 list, which is not necessarily complete.
3163
3164 @itemize @bullet
3165 @item
3166 Possible infinitely recursive calls
3167
3168 @item
3169 Out-of-range values being assigned
3170
3171 @item
3172 Possible order of elaboration problems
3173
3174 @item
3175 Unreachable code
3176
3177 @item
3178 Fixed-point type declarations with a null range
3179
3180 @item
3181 Variables that are never assigned a value
3182
3183 @item
3184 Variables that are referenced before being initialized
3185
3186 @item
3187 Task entries with no corresponding accept statement
3188
3189 @item
3190 Duplicate accepts for the same task entry in a select
3191
3192 @item
3193 Objects that take too much storage
3194
3195 @item
3196 Unchecked conversion between types of differing sizes
3197
3198 @item
3199 Missing return statements along some execution paths in a function
3200
3201 @item
3202 Incorrect (unrecognized) pragmas
3203
3204 @item
3205 Incorrect external names
3206
3207 @item
3208 Allocation from empty storage pool
3209
3210 @item
3211 Potentially blocking operations in protected types
3212
3213 @item
3214 Suspicious parenthesization of expressions
3215
3216 @item
3217 Mismatching bounds in an aggregate
3218
3219 @item
3220 Attempt to return local value by reference
3221
3222 @item
3223 Unrecognized pragmas
3224
3225 @item
3226 Premature instantiation of a generic body
3227
3228 @item
3229 Attempt to pack aliased components
3230
3231 @item
3232 Out of bounds array subscripts
3233
3234 @item
3235 Wrong length on string assignment
3236
3237 @item
3238 Violations of style rules if style checking is enabled
3239
3240 @item
3241 Unused with clauses
3242
3243 @item
3244 Bit_Order usage that does not have any effect
3245
3246 @item
3247 Compile time biased rounding of floating-point constant
3248
3249 @item
3250 Standard.Duration used to resolve universal fixed expression
3251
3252 @item
3253 Dereference of possibly null value
3254
3255 @item
3256 Declaration that is likely to cause storage error
3257
3258 @item
3259 Internal GNAT unit with'ed by application unit
3260
3261 @item
3262 Values known to be out of range at compile time
3263
3264 @item
3265 Unreferenced labels and variables
3266
3267 @item
3268 Address overlays that could clobber memory
3269
3270 @item
3271 Unexpected initialization when address clause present
3272
3273 @item
3274 Bad alignment for address clause
3275
3276 @item
3277 Useless type conversions
3278
3279 @item
3280 Redundant assignment statements
3281
3282 @item
3283 Accidental hiding of name by child unit
3284
3285 @item
3286 Unreachable code
3287
3288 @item
3289 Access before elaboration detected at compile time
3290
3291 @item
3292 A range in a @code{for} loop that is known to be null or might be null
3293
3294 @end itemize
3295
3296 @noindent
3297 The following switches are available to control the handling of
3298 warning messages:
3299
3300 @table @code
3301 @item -gnatwa (activate all optional errors)
3302 @cindex @option{-gnatwa} (@code{gcc})
3303 This switch activates most optional warning messages, see remaining list
3304 in this section for details on optional warning messages that can be
3305 individually controlled. The warnings that are not turned on by this
3306 switch are @option{-gnatwb} (biased rounding),
3307 @option{-gnatwd} (implicit dereferencing),
3308 and @option{-gnatwh} (hiding). All other optional warnings are
3309 turned on.
3310
3311 @item -gnatwA (suppress all optional errors)
3312 @cindex @option{-gnatwA} (@code{gcc})
3313 This switch suppresses all optional warning messages, see remaining list
3314 in this section for details on optional warning messages that can be
3315 individually controlled.
3316
3317 @item -gnatwb (activate warnings on biased rounding)
3318 @cindex @option{-gnatwb} (@code{gcc})
3319 @cindex Rounding, biased
3320 @cindex Biased rounding
3321 If a static floating-point expression has a value that is exactly half
3322 way between two adjacent machine numbers, then the rules of Ada
3323 (Ada Reference Manual, section 4.9(38)) require that this rounding
3324 be done away from zero, even if the normal unbiased rounding rules
3325 at run time would require rounding towards zero. This warning message
3326 alerts you to such instances where compile-time rounding and run-time
3327 rounding are not equivalent. If it is important to get proper run-time
3328 rounding, then you can force this by making one of the operands into
3329 a variable. The default is that such warnings are not generated.
3330 Note that @option{-gnatwa} does not affect the setting of
3331 this warning option.
3332
3333 @item -gnatwB (suppress warnings on biased rounding)
3334 @cindex @option{-gnatwB} (@code{gcc})
3335 This switch disables warnings on biased rounding.
3336
3337 @item -gnatwc (activate warnings on conditionals)
3338 @cindex @option{-gnatwc} (@code{gcc})
3339 @cindex Conditionals, constant
3340 This switch activates warnings for conditional expressions used in
3341 tests that are known to be True or False at compile time. The default
3342 is that such warnings are not generated.
3343 This warning can also be turned on using @option{-gnatwa}.
3344
3345 @item -gnatwC (suppress warnings on conditionals)
3346 @cindex @option{-gnatwC} (@code{gcc})
3347 This switch suppresses warnings for conditional expressions used in
3348 tests that are known to be True or False at compile time.
3349
3350 @item -gnatwd (activate warnings on implicit dereferencing)
3351 @cindex @option{-gnatwd} (@code{gcc})
3352 If this switch is set, then the use of a prefix of an access type
3353 in an indexed component, slice, or selected component without an
3354 explicit @code{.all} will generate a warning. With this warning
3355 enabled, access checks occur only at points where an explicit
3356 @code{.all} appears in the source code (assuming no warnings are
3357 generated as a result of this switch). The default is that such
3358 warnings are not generated.
3359 Note that @option{-gnatwa} does not affect the setting of
3360 this warning option.
3361
3362 @item -gnatwD (suppress warnings on implicit dereferencing)
3363 @cindex @option{-gnatwD} (@code{gcc})
3364 @cindex Implicit dereferencing
3365 @cindex Dereferencing, implicit
3366 This switch suppresses warnings for implicit deferences in
3367 indexed components, slices, and selected components.
3368
3369 @item -gnatwe (treat warnings as errors)
3370 @cindex @option{-gnatwe} (@code{gcc})
3371 @cindex Warnings, treat as error
3372 This switch causes warning messages to be treated as errors.
3373 The warning string still appears, but the warning messages are counted
3374 as errors, and prevent the generation of an object file.
3375
3376 @item -gnatwf (activate warnings on unreferenced formals)
3377 @cindex @option{-gnatwf} (@code{gcc})
3378 @cindex Formals, unreferenced
3379 This switch causes a warning to be generated if a formal parameter
3380 is not referenced in the body of the subprogram. This warning can
3381 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
3382
3383 @item -gnatwF (suppress warnings on unreferenced formals)
3384 @cindex @option{-gnatwF} (@code{gcc})
3385 This switch suppresses warnings for unreferenced formal
3386 parameters. Note that the
3387 combination @option{-gnatwu} followed by @option{-gnatwF} has the
3388 effect of warning on unreferenced entities other than subprogram
3389 formals.
3390
3391 @item -gnatwh (activate warnings on hiding)
3392 @cindex @option{-gnatwh} (@code{gcc})
3393 @cindex Hiding of Declarations
3394 This switch activates warnings on hiding declarations.
3395 A declaration is considered hiding
3396 if it is for a non-overloadable entity, and it declares an entity with the
3397 same name as some other entity that is directly or use-visible. The default
3398 is that such warnings are not generated.
3399 Note that @option{-gnatwa} does not affect the setting of this warning option.
3400
3401 @item -gnatwH (suppress warnings on hiding)
3402 @cindex @option{-gnatwH} (@code{gcc})
3403 This switch suppresses warnings on hiding declarations.
3404
3405 @item -gnatwi (activate warnings on implementation units).
3406 @cindex @option{-gnatwi} (@code{gcc})
3407 This switch activates warnings for a @code{with} of an internal GNAT
3408 implementation unit, defined as any unit from the @code{Ada},
3409 @code{Interfaces}, @code{GNAT},
3410  or @code{System}
3411 hierarchies that is not
3412 documented in either the Ada Reference Manual or the GNAT
3413 Programmer's Reference Manual. Such units are intended only
3414 for internal implementation purposes and should not be @code{with}'ed
3415 by user programs. The default is that such warnings are generated
3416 This warning can also be turned on using @option{-gnatwa}.
3417
3418 @item -gnatwI (disable warnings on implementation units).
3419 @cindex @option{-gnatwI} (@code{gcc})
3420 This switch disables warnings for a @code{with} of an internal GNAT
3421 implementation unit.
3422
3423 @item -gnatwl (activate warnings on elaboration pragmas)
3424 @cindex @option{-gnatwl} (@code{gcc})
3425 @cindex Elaboration, warnings
3426 This switch activates warnings on missing pragma Elaborate_All statements.
3427 See the section in this guide on elaboration checking for details on
3428 when such pragma should be used. The default is that such warnings
3429 are not generated.
3430 This warning can also be turned on using @option{-gnatwa}.
3431
3432 @item -gnatwL (suppress warnings on elaboration pragmas)
3433 @cindex @option{-gnatwL} (@code{gcc})
3434 This switch suppresses warnings on missing pragma Elaborate_All statements.
3435 See the section in this guide on elaboration checking for details on
3436 when such pragma should be used.
3437
3438 @item -gnatwo (activate warnings on address clause overlays)
3439 @cindex @option{-gnatwo} (@code{gcc})
3440 @cindex Address Clauses, warnings
3441 This switch activates warnings for possibly unintended initialization
3442 effects of defining address clauses that cause one variable to overlap
3443 another. The default is that such warnings are generated.
3444 This warning can also be turned on using @option{-gnatwa}.
3445
3446 @item -gnatwO (suppress warnings on address clause overlays)
3447 @cindex @option{-gnatwO} (@code{gcc})
3448 This switch suppresses warnings on possibly unintended initialization
3449 effects of defining address clauses that cause one variable to overlap
3450 another.
3451
3452 @item -gnatwp (activate warnings on ineffective pragma Inlines)
3453 @cindex @option{-gnatwp} (@code{gcc})
3454 @cindex Inlining, warnings
3455 This switch activates warnings for failure of front end inlining
3456 (activated by @option{-gnatN}) to inline a particular call. There are
3457 many reasons for not being able to inline a call, including most
3458 commonly that the call is too complex to inline.
3459 This warning can also be turned on using @option{-gnatwa}.
3460
3461 @item -gnatwP (suppress warnings on ineffective pragma Inlines)
3462 @cindex @option{-gnatwP} (@code{gcc})
3463 This switch suppresses warnings on ineffective pragma Inlines. If the
3464 inlining mechanism cannot inline a call, it will simply ignore the
3465 request silently.
3466
3467 @item -gnatwr (activate warnings on redundant constructs)
3468 @cindex @option{-gnatwr} (@code{gcc})
3469 This switch activates warnings for redundant constructs. The following
3470 is the current list of constructs regarded as redundant:
3471 This warning can also be turned on using @option{-gnatwa}.
3472
3473 @itemize @bullet
3474 @item
3475 Assignment of an item to itself.
3476 @item
3477 Type conversion that converts an expression to its own type.
3478 @item
3479 Use of the attribute @code{Base} where @code{typ'Base} is the same
3480 as @code{typ}.
3481 @item
3482 Use of pragma @code{Pack} when all components are placed by a record
3483 representation clause.
3484 @end itemize
3485
3486 @item -gnatwR (suppress warnings on redundant constructs)
3487 @cindex @option{-gnatwR} (@code{gcc})
3488 This switch suppresses warnings for redundant constructs.
3489
3490 @item -gnatws (suppress all warnings)
3491 @cindex @option{-gnatws} (@code{gcc})
3492 This switch completely suppresses the
3493 output of all warning messages from the GNAT front end.
3494 Note that it does not suppress warnings from the @code{gcc} back end.
3495 To suppress these back end warnings as well, use the switch @code{-w}
3496 in addition to @option{-gnatws}.
3497
3498 @item -gnatwu (activate warnings on unused entities)
3499 @cindex @option{-gnatwu} (@code{gcc})
3500 This switch activates warnings to be generated for entities that
3501 are defined but not referenced, and for units that are @code{with}'ed
3502 and not
3503 referenced. In the case of packages, a warning is also generated if
3504 no entities in the package are referenced. This means that if the package
3505 is referenced but the only references are in @code{use}
3506 clauses or @code{renames}
3507 declarations, a warning is still generated. A warning is also generated
3508 for a generic package that is @code{with}'ed but never instantiated.
3509 In the case where a package or subprogram body is compiled, and there
3510 is a @code{with} on the corresponding spec
3511 that is only referenced in the body,
3512 a warning is also generated, noting that the
3513 @code{with} can be moved to the body. The default is that
3514 such warnings are not generated.
3515 This switch also activates warnings on unreferenced formals
3516 (it is includes the effect of @option{-gnatwf}).
3517 This warning can also be turned on using @option{-gnatwa}.
3518
3519 @item -gnatwU (suppress warnings on unused entities)
3520 @cindex @option{-gnatwU} (@code{gcc})
3521 This switch suppresses warnings for unused entities and packages.
3522 It also turns off warnings on unreferenced formals (and thus includes
3523 the effect of @option{-gnatwF}).
3524
3525 @noindent
3526 A string of warning parameters can be used in the same parameter. For example:
3527
3528 @smallexample
3529 -gnatwaLe
3530 @end smallexample
3531
3532 @noindent
3533 Would turn on all optional warnings except for elaboration pragma warnings,
3534 and also specify that warnings should be treated as errors.
3535
3536 @item -w
3537 @cindex @code{-w}
3538 This switch suppresses warnings from the @code{gcc} backend. It may be
3539 used in conjunction with @option{-gnatws} to ensure that all warnings
3540 are suppressed during the entire compilation process.
3541
3542 @end table
3543
3544 @node Debugging and Assertion Control
3545 @subsection Debugging and Assertion Control
3546
3547 @table @code
3548 @item -gnata
3549 @cindex @option{-gnata} (@code{gcc})
3550 @findex Assert
3551 @findex Debug
3552 @cindex Assertions
3553
3554 @noindent
3555 The pragmas @code{Assert} and @code{Debug} normally have no effect and
3556 are ignored. This switch, where @samp{a} stands for assert, causes
3557 @code{Assert} and @code{Debug} pragmas to be activated.
3558
3559 The pragmas have the form:
3560
3561 @smallexample
3562 @group
3563 @cartouche
3564    @b{pragma} Assert (@var{Boolean-expression} [,
3565                       @var{static-string-expression}])
3566    @b{pragma} Debug (@var{procedure call})
3567 @end cartouche
3568 @end group
3569 @end smallexample
3570
3571 @noindent
3572 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
3573 If the result is @code{True}, the pragma has no effect (other than
3574 possible side effects from evaluating the expression). If the result is
3575 @code{False}, the exception @code{Assert_Failure} declared in the package
3576 @code{System.Assertions} is
3577 raised (passing @var{static-string-expression}, if present, as the
3578 message associated with the exception). If no string expression is
3579 given the default is a string giving the file name and line number
3580 of the pragma.
3581
3582 The @code{Debug} pragma causes @var{procedure} to be called. Note that
3583 @code{pragma Debug} may appear within a declaration sequence, allowing
3584 debugging procedures to be called between declarations.
3585
3586 @end table
3587
3588 @node Validity Checking
3589 @subsection Validity Checking
3590 @findex Validity Checking
3591
3592 @noindent
3593 The Ada 95 Reference Manual has specific requirements for checking
3594 for invalid values. In particular, RM 13.9.1 requires that the
3595 evaluation of invalid values (for example from unchecked conversions),
3596 not result in erroneous execution. In GNAT, the result of such an
3597 evaluation in normal default mode is to either use the value
3598 unmodified, or to raise Constraint_Error in those cases where use
3599 of the unmodified value would cause erroneous execution. The cases
3600 where unmodified values might lead to erroneous execution are case
3601 statements (where a wild jump might result from an invalid value),
3602 and subscripts on the left hand side (where memory corruption could
3603 occur as a result of an invalid value).
3604
3605 The @option{-gnatVx} switch allows more control over the validity checking
3606 mode. The @code{x} argument here is a string of letters which control which
3607 validity checks are performed in addition to the default checks described
3608 above.
3609
3610 @itemize @bullet
3611 @item
3612 @option{-gnatVc} Validity checks for copies
3613
3614 The right hand side of assignments, and the initializing values of
3615 object declarations are validity checked.
3616
3617 @item
3618 @option{-gnatVd} Default (RM) validity checks
3619
3620 Some validity checks are done by default following normal Ada semantics
3621 (RM 13.9.1 (9-11)).
3622 A check is done in case statements that the expression is within the range
3623 of the subtype. If it is not, Constraint_Error is raised.
3624 For assignments to array components, a check is done that the expression used
3625 as index is within the range. If it is not, Constraint_Error is raised.
3626 Both these validity checks may be turned off using switch @option{-gnatVD}.
3627 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
3628 switch @option{-gnatVd} will leave the checks turned on.
3629 Switch @option{-gnatVD} should be used only if you are sure that all such
3630 expressions have valid values. If you use this switch and invalid values
3631 are present, then the program is erroneous, and wild jumps or memory
3632 overwriting may occur.
3633
3634 @item
3635 @option{-gnatVi} Validity checks for @code{in} mode parameters
3636
3637 Arguments for parameters of mode @code{in} are validity checked in function
3638 and procedure calls at the point of call.
3639
3640 @item
3641 @option{-gnatVm} Validity checks for @code{in out} mode parameters
3642
3643 Arguments for parameters of mode @code{in out} are validity checked in
3644 procedure calls at the point of call. The @code{'m'} here stands for
3645 modify, since this concerns parameters that can be modified by the call.
3646 Note that there is no specific option to test @code{out} parameters,
3647 but any reference within the subprogram will be tested in the usual
3648 manner, and if an invalid value is copied back, any reference to it
3649 will be subject to validity checking.
3650
3651 @item
3652 @option{-gnatVo} Validity checks for operator and attribute operands
3653
3654 Arguments for predefined operators and attributes are validity checked.
3655 This includes all operators in package @code{Standard},
3656 the shift operators defined as intrinsic in package @code{Interfaces}
3657 and operands for attributes such as @code{Pos}.
3658
3659 @item
3660 @option{-gnatVr} Validity checks for function returns
3661
3662 The expression in @code{return} statements in functions is validity
3663 checked.
3664
3665 @item
3666 @option{-gnatVs} Validity checks for subscripts
3667
3668 All subscripts expressions are checked for validity, whether they appear
3669 on the right side or left side (in default mode only left side subscripts
3670 are validity checked).
3671
3672 @item
3673 @option{-gnatVt} Validity checks for tests
3674
3675 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
3676 statements are checked, as well as guard expressions in entry calls.
3677
3678 @item
3679 @option{-gnatVf} Validity checks for floating-point values
3680
3681 In the absence of this switch, validity checking occurs only for discrete
3682 values. If @option{-gnatVf} is specified, then validity checking also applies
3683 for floating-point values, and NaN's and infinities are considered invalid,
3684 as well as out of range values for constrained types. Note that this means
3685 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
3686 in which floating-point values are checked depends on the setting of other
3687 options. For example @option{-gnatVif} or @option{-gnatVfi} (the order does
3688 not matter) specifies that floating-point parameters of mode @code{in} should
3689 be validity checked.
3690
3691 @item
3692 @option{-gnatVa} All validity checks
3693
3694 All the above validity checks are turned on. That is @option{-gnatVa} is
3695 equivalent to @code{gnatVcdfimorst}.
3696
3697 @item
3698 @option{-gnatVn} No validity checks
3699
3700 This switch turns off all validity checking, including the default checking
3701 for case statements and left hand side subscripts. Note that the use of
3702 the switch @option{-gnatp} supresses all run-time checks, including
3703 validity checks, and thus implies @option{-gnatVn}.
3704
3705 @end itemize
3706
3707 The @option{-gnatV} switch may be followed by a string of letters to turn on
3708 a series of validity checking options. For example, @option{-gnatVcr} specifies
3709 that in addition to the default validity checking, copies and function
3710 return expressions be validity checked. In order to make it easier to specify
3711 a set of options, the upper case letters @code{CDFIMORST} may be used to turn
3712 off the corresponding lower case option, so for example @option{-gnatVaM} turns
3713 on all validity checking options except for checking of @code{in out}
3714 procedure arguments.
3715
3716 The specification of additional validity checking generates extra code (and
3717 in the case of @option{-gnatva} the code expansion can be substantial. However,
3718 these additional checks can be very useful in smoking out cases of
3719 uninitialized variables, incorrect use of unchecked conversion, and other
3720 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
3721 is useful in conjunction with the extra validity checking, since this
3722 ensures that wherever possible uninitialized variables have invalid values.
3723
3724 See also the pragma @code{Validity_Checks} which allows modification of
3725 the validity checking mode at the program source level, and also allows for
3726 temporary disabling of validity checks.
3727
3728 @node Style Checking
3729 @subsection Style Checking
3730 @findex Style checking
3731
3732 @noindent
3733 The -gnaty@var{x} switch causes the compiler to
3734 enforce specified style rules. A limited set of style rules has been used
3735 in writing the GNAT sources themselves. This switch allows user programs
3736 to activate all or some of these checks. If the source program fails a
3737 specified style check, an appropriate warning message is given, preceded by
3738 the character sequence "(style)".
3739 The string @var{x} is a sequence of letters or digits
3740 indicating the particular style
3741 checks to be performed. The following checks are defined:
3742
3743 @table @code
3744 @item 1-9 (specify indentation level)
3745 If a digit from 1-9 appears in the string after @option{-gnaty} then proper
3746 indentation is checked, with the digit indicating the indentation level
3747 required. The general style of required indentation is as specified by
3748 the examples in the Ada Reference Manual. Full line comments must be
3749 aligned with the @code{--} starting on a column that is a multiple of
3750 the alignment level.
3751
3752 @item a (check attribute casing)
3753 If the letter a appears in the string after @option{-gnaty} then
3754 attribute names, including the case of keywords such as @code{digits}
3755 used as attributes names, must be written in mixed case, that is, the
3756 initial letter and any letter following an underscore must be uppercase.
3757 All other letters must be lowercase.
3758
3759 @item b (blanks not allowed at statement end)
3760 If the letter b appears in the string after @option{-gnaty} then
3761 trailing blanks are not allowed at the end of statements. The purpose of this
3762 rule, together with h (no horizontal tabs), is to enforce a canonical format
3763 for the use of blanks to separate source tokens.
3764
3765 @item c (check comments)
3766 If the letter c appears in the string after @option{-gnaty} then
3767 comments must meet the following set of rules:
3768
3769 @itemize @bullet
3770
3771 @item
3772 The "--" that starts the column must either start in column one, or else
3773 at least one blank must precede this sequence.
3774
3775 @item
3776 Comments that follow other tokens on a line must have at least one blank
3777 following the "--" at the start of the comment.
3778
3779 @item
3780 Full line comments must have two blanks following the "--" that starts
3781 the comment, with the following exceptions.
3782
3783 @item
3784 A line consisting only of the "--" characters, possibly preceded by blanks
3785 is permitted.
3786
3787 @item
3788 A comment starting with "--x" where x is a special character is permitted.
3789 This alows proper processing of the output generated by specialized tools
3790 including @code{gnatprep} (where --! is used) and the SPARK annnotation
3791 language (where --# is used). For the purposes of this rule, a special
3792 character is defined as being in one of the ASCII ranges
3793 16#21#..16#2F# or 16#3A#..16#3F#.
3794
3795 @item
3796 A line consisting entirely of minus signs, possibly preceded by blanks, is
3797 permitted. This allows the construction of box comments where lines of minus
3798 signs are used to form the top and bottom of the box.
3799
3800 @item
3801 If a comment starts and ends with "--" is permitted as long as at least
3802 one blank follows the initial "--". Together with the preceding rule,
3803 this allows the construction of box comments, as shown in the following
3804 example:
3805 @smallexample
3806 ---------------------------
3807 -- This is a box comment --
3808 -- with two text lines.  --
3809 ---------------------------
3810 @end smallexample
3811 @end itemize
3812
3813 @item e (check end/exit labels)
3814 If the letter e appears in the string after @option{-gnaty} then
3815 optional labels on @code{end} statements ending subprograms and on
3816 @code{exit} statements exiting named loops, are required to be present.
3817
3818 @item f (no form feeds or vertical tabs)
3819 If the letter f appears in the string after @option{-gnaty} then
3820 neither form feeds nor vertical tab characters are not permitted
3821 in the source text.
3822
3823 @item h (no horizontal tabs)
3824 If the letter h appears in the string after @option{-gnaty} then
3825 horizontal tab characters are not permitted in the source text.
3826 Together with the b (no blanks at end of line) check, this
3827 enforces a canonical form for the use of blanks to separate
3828 source tokens.
3829
3830 @item i (check if-then layout)
3831 If the letter i appears in the string after @option{-gnaty},
3832 then the keyword @code{then} must appear either on the same
3833 line as corresponding @code{if}, or on a line on its own, lined
3834 up under the @code{if} with at least one non-blank line in between
3835 containing all or part of the condition to be tested.
3836
3837 @item k (check keyword casing)
3838 If the letter k appears in the string after @option{-gnaty} then
3839 all keywords must be in lower case (with the exception of keywords
3840 such as @code{digits} used as attribute names to which this check
3841 does not apply).
3842
3843 @item l (check layout)
3844 If the letter l appears in the string after @option{-gnaty} then
3845 layout of statement and declaration constructs must follow the
3846 recommendations in the Ada Reference Manual, as indicated by the
3847 form of the syntax rules. For example an @code{else} keyword must
3848 be lined up with the corresponding @code{if} keyword.
3849
3850 There are two respects in which the style rule enforced by this check
3851 option are more liberal than those in the Ada Reference Manual. First
3852 in the case of record declarations, it is permissible to put the
3853 @code{record} keyword on the same line as the @code{type} keyword, and
3854 then the @code{end} in @code{end record} must line up under @code{type}.
3855 For example, either of the following two layouts is acceptable:
3856
3857 @smallexample
3858 @group
3859 @cartouche
3860 @b{type} q @b{is record}
3861    a : integer;
3862    b : integer;
3863 @b{end record};
3864
3865 @b{type} q @b{is}
3866    @b{record}
3867       a : integer;
3868       b : integer;
3869    @b{end record};
3870 @end cartouche
3871 @end group
3872 @end smallexample
3873
3874 @noindent
3875 Second, in the case of a block statement, a permitted alternative
3876 is to put the block label on the same line as the @code{declare} or
3877 @code{begin} keyword, and then line the @code{end} keyword up under
3878 the block label. For example both the following are permitted:
3879
3880 @smallexample
3881 @group
3882 @cartouche
3883 Block : @b{declare}
3884    A : Integer := 3;
3885 @b{begin}
3886    Proc (A, A);
3887 @b{end} Block;
3888
3889 Block :
3890    @b{declare}
3891       A : Integer := 3;
3892    @b{begin}
3893       Proc (A, A);
3894    @b{end} Block;
3895 @end cartouche
3896 @end group
3897 @end smallexample
3898
3899 @noindent
3900 The same alternative format is allowed for loops. For example, both of
3901 the following are permitted:
3902
3903 @smallexample
3904 @group
3905 @cartouche
3906 Clear : @b{while} J < 10 @b{loop}
3907    A (J) := 0;
3908 @b{end loop} Clear;
3909
3910 Clear :
3911    @b{while} J < 10 @b{loop}
3912       A (J) := 0;
3913    @b{end loop} Clear;
3914 @end cartouche
3915 @end group
3916 @end smallexample
3917
3918 @item m (check maximum line length)
3919 If the letter m appears in the string after @option{-gnaty}
3920 then the length of source lines must not exceed 79 characters, including
3921 any trailing blanks. The value of 79 allows convenient display on an
3922 80 character wide device or window, allowing for possible special
3923 treatment of 80 character lines.
3924
3925 @item Mnnn (set maximum line length)
3926 If the sequence Mnnn, where nnn is a decimal number, appears in
3927 the string after @option{-gnaty} then the length of lines must not exceed the
3928 given value.
3929
3930 @item n (check casing of entities in Standard)
3931 If the letter n appears in the string
3932 after @option{-gnaty} then any identifier from Standard must be cased
3933 to match the presentation in the Ada Reference Manual (for example,
3934 @code{Integer} and @code{ASCII.NUL}).
3935
3936 @item o (check order of subprogram bodies)
3937 If the letter o appears in the string
3938 after @option{-gnaty} then all subprogram bodies in a given scope
3939 (e.g. a package body) must be in alphabetical order. The ordering
3940 rule uses normal Ada rules for comparing strings, ignoring casing
3941 of letters, except that if there is a trailing numeric suffix, then
3942 the value of this suffix is used in the ordering (e.g. Junk2 comes
3943 before Junk10).
3944
3945 @item p (check pragma casing)
3946 If the letter p appears in the string after @option{-gnaty} then
3947 pragma names must be written in mixed case, that is, the
3948 initial letter and any letter following an underscore must be uppercase.
3949 All other letters must be lowercase.
3950
3951 @item r (check references)
3952 If the letter r appears in the string after @option{-gnaty}
3953 then all identifier references must be cased in the same way as the
3954 corresponding declaration. No specific casing style is imposed on
3955 identifiers. The only requirement is for consistency of references
3956 with declarations.
3957
3958 @item s (check separate specs)
3959 If the letter s appears in the string after @option{-gnaty} then
3960 separate declarations ("specs") are required for subprograms (a
3961 body is not allowed to serve as its own declaration). The only
3962 exception is that parameterless library level procedures are
3963 not required to have a separate declaration. This exception covers
3964 the most frequent form of main program procedures.
3965
3966 @item t (check token spacing)
3967 If the letter t appears in the string after @option{-gnaty} then
3968 the following token spacing rules are enforced:
3969
3970 @itemize @bullet
3971
3972 @item
3973 The keywords @code{abs} and @code{not} must be followed by a space.
3974
3975 @item
3976 The token @code{=>} must be surrounded by spaces.
3977
3978 @item
3979 The token @code{<>} must be preceded by a space or a left parenthesis.
3980
3981 @item
3982 Binary operators other than @code{**} must be surrounded by spaces.
3983 There is no restriction on the layout of the @code{**} binary operator.
3984
3985 @item
3986 Colon must be surrounded by spaces.
3987
3988 @item
3989 Colon-equal (assignment) must be surrounded by spaces.
3990
3991 @item
3992 Comma must be the first non-blank character on the line, or be
3993 immediately preceded by a non-blank character, and must be followed
3994 by a space.
3995
3996 @item
3997 If the token preceding a left paren ends with a letter or digit, then
3998 a space must separate the two tokens.
3999
4000 @item
4001 A right parenthesis must either be the first non-blank character on
4002 a line, or it must be preceded by a non-blank character.
4003
4004 @item
4005 A semicolon must not be preceded by a space, and must not be followed by
4006 a non-blank character.
4007
4008 @item
4009 A unary plus or minus may not be followed by a space.
4010
4011 @item
4012 A vertical bar must be surrounded by spaces.
4013 @end itemize
4014
4015 @noindent
4016 In the above rules, appearing in column one is always permitted, that is,
4017 counts as meeting either a requirement for a required preceding space,
4018 or as meeting a requirement for no preceding space.
4019
4020 Appearing at the end of a line is also always permitted, that is, counts
4021 as meeting either a requirement for a following space, or as meeting
4022 a requirement for no following space.
4023
4024 @end table
4025
4026 @noindent
4027 If any of these style rules is violated, a message is generated giving
4028 details on the violation. The initial characters of such messages are
4029 always "(style)". Note that these messages are treated as warning
4030 messages, so they normally do not prevent the generation of an object
4031 file. The @option{-gnatwe} switch can be used to treat warning messages,
4032 including style messages, as fatal errors.
4033
4034 @noindent
4035 The switch
4036 @option{-gnaty} on its own (that is not followed by any letters or digits),
4037 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
4038 options are enabled with
4039 the exception of -gnatyo,
4040 with an indentation level of 3. This is the standard
4041 checking option that is used for the GNAT sources.
4042
4043 @node Run-Time Checks
4044 @subsection Run-Time Checks
4045 @cindex Division by zero
4046 @cindex Access before elaboration
4047 @cindex Checks, division by zero
4048 @cindex Checks, access before elaboration
4049
4050 @noindent
4051 If you compile with the default options, GNAT will insert many run-time
4052 checks into the compiled code, including code that performs range
4053 checking against constraints, but not arithmetic overflow checking for
4054 integer operations (including division by zero) or checks for access
4055 before elaboration on subprogram calls. All other run-time checks, as
4056 required by the Ada 95 Reference Manual, are generated by default.
4057 The following @code{gcc} switches refine this default behavior:
4058
4059 @table @code
4060 @item -gnatp
4061 @cindex @option{-gnatp} (@code{gcc})
4062 @cindex Suppressing checks
4063 @cindex Checks, suppressing
4064 @findex Suppress
4065 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
4066 had been present in the source. Validity checks are also suppressed (in
4067 other words @option{-gnatp} also implies @option{-gnatVn}.
4068 Use this switch to improve the performance
4069 of the code at the expense of safety in the presence of invalid data or
4070 program bugs.
4071
4072 @item -gnato
4073 @cindex @option{-gnato} (@code{gcc})
4074 @cindex Overflow checks
4075 @cindex Check, overflow
4076 Enables overflow checking for integer operations.
4077 This causes GNAT to generate slower and larger executable
4078 programs by adding code to check for overflow (resulting in raising
4079 @code{Constraint_Error} as required by standard Ada
4080 semantics). These overflow checks correspond to situations in which
4081 the true value of the result of an operation may be outside the base
4082 range of the result type. The following example shows the distinction:
4083
4084 @smallexample
4085 X1 : Integer := Integer'Last;
4086 X2 : Integer range 1 .. 5 := 5;
4087 ...
4088 X1 := X1 + 1;   -- @option{-gnato} required to catch the Constraint_Error
4089 X2 := X2 + 1;   -- range check, @option{-gnato} has no effect here
4090 @end smallexample
4091
4092 @noindent
4093 Here the first addition results in a value that is outside the base range
4094 of Integer, and hence requires an overflow check for detection of the
4095 constraint error. The second increment operation results in a violation
4096 of the explicit range constraint, and such range checks are always
4097 performed. Basically the compiler can assume that in the absence of
4098 the @option{-gnato} switch that any value of type @code{xxx} is
4099 in range of the base type of @code{xxx}.
4100
4101 @findex Machine_Overflows
4102 Note that the @option{-gnato} switch does not affect the code generated
4103 for any floating-point operations; it applies only to integer
4104 semantics).
4105 For floating-point, GNAT has the @code{Machine_Overflows}
4106 attribute set to @code{False} and the normal mode of operation is to
4107 generate IEEE NaN and infinite values on overflow or invalid operations
4108 (such as dividing 0.0 by 0.0).
4109
4110 The reason that we distinguish overflow checking from other kinds of
4111 range constraint checking is that a failure of an overflow check can
4112 generate an incorrect value, but cannot cause erroneous behavior. This
4113 is unlike the situation with a constraint check on an array subscript,
4114 where failure to perform the check can result in random memory description,
4115 or the range check on a case statement, where failure to perform the check
4116 can cause a wild jump.
4117
4118 Note again that @option{-gnato} is off by default, so overflow checking is
4119 not performed in default mode. This means that out of the box, with the
4120 default settings, GNAT does not do all the checks expected from the
4121 language description in the Ada Reference Manual. If you want all constraint
4122 checks to be performed, as described in this Manual, then you must
4123 explicitly use the -gnato switch either on the @code{gnatmake} or
4124 @code{gcc} command.
4125
4126 @item -gnatE
4127 @cindex @option{-gnatE} (@code{gcc})
4128 @cindex Elaboration checks
4129 @cindex Check, elaboration
4130 Enables dynamic checks for access-before-elaboration
4131 on subprogram calls and generic instantiations.
4132 For full details of the effect and use of this switch,
4133 @xref{Compiling Using gcc}.
4134 @end table
4135
4136 @findex Unsuppress
4137 @noindent
4138 The setting of these switches only controls the default setting of the
4139 checks. You may modify them using either @code{Suppress} (to remove
4140 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
4141 the program source.
4142
4143 @node Stack Overflow Checking
4144 @subsection Stack Overflow Checking
4145 @cindex Stack Overflow Checking
4146 @cindex -fstack-check
4147
4148 @noindent
4149 For most operating systems, @code{gcc} does not perform stack overflow
4150 checking by default. This means that if the main environment task or
4151 some other task exceeds the available stack space, then unpredictable
4152 behavior will occur.
4153
4154 To activate stack checking, compile all units with the gcc option
4155 @code{-fstack-check}. For example:
4156
4157 @smallexample
4158 gcc -c -fstack-check package1.adb
4159 @end smallexample
4160
4161 @noindent
4162 Units compiled with this option will generate extra instructions to check
4163 that any use of the stack (for procedure calls or for declaring local
4164 variables in declare blocks) do not exceed the available stack space.
4165 If the space is exceeded, then a @code{Storage_Error} exception is raised.
4166
4167 For declared tasks, the stack size is always controlled by the size
4168 given in an applicable @code{Storage_Size} pragma (or is set to
4169 the default size if no pragma is used.
4170
4171 For the environment task, the stack size depends on
4172 system defaults and is unknown to the compiler. The stack
4173 may even dynamically grow on some systems, precluding the
4174 normal Ada semantics for stack overflow. In the worst case,
4175 unbounded stack usage, causes unbounded stack expansion
4176 resulting in the system running out of virtual memory.
4177
4178 The stack checking may still work correctly if a fixed
4179 size stack is allocated, but this cannot be guaranteed.
4180 To ensure that a clean exception is signalled for stack
4181 overflow, set the environment variable
4182 @code{GNAT_STACK_LIMIT} to indicate the maximum
4183 stack area that can be used, as in:
4184 @cindex GNAT_STACK_LIMIT
4185
4186 @smallexample
4187 SET GNAT_STACK_LIMIT 1600
4188 @end smallexample
4189
4190 @noindent
4191 The limit is given in kilobytes, so the above declaration would
4192 set the stack limit of the environment task to 1.6 megabytes.
4193 Note that the only purpose of this usage is to limit the amount
4194 of stack used by the environment task. If it is necessary to
4195 increase the amount of stack for the environment task, then this
4196 is an operating systems issue, and must be addressed with the
4197 appropriate operating systems commands.
4198
4199 @node Run-Time Control
4200 @subsection Run-Time Control
4201
4202 @table @code
4203 @item -gnatT nnn
4204 @cindex @option{-gnatT} (@code{gcc})
4205 @cindex Time Slicing
4206
4207 @noindent
4208 The @code{gnatT} switch can be used to specify the time-slicing value
4209 to be used for task switching between equal priority tasks. The value
4210 @code{nnn} is given in microseconds as a decimal integer.
4211
4212 Setting the time-slicing value is only effective if the underlying thread
4213 control system can accommodate time slicing. Check the documentation of
4214 your operating system for details. Note that the time-slicing value can
4215 also be set by use of pragma @code{Time_Slice} or by use of the
4216 @code{t} switch in the gnatbind step. The pragma overrides a command
4217 line argument if both are present, and the @code{t} switch for gnatbind
4218 overrides both the pragma and the @code{gcc} command line switch.
4219 @end table
4220
4221 @node Using gcc for Syntax Checking
4222 @subsection Using @code{gcc} for Syntax Checking
4223 @table @code
4224 @item -gnats
4225 @cindex @option{-gnats} (@code{gcc})
4226
4227 @noindent
4228 The @code{s} stands for syntax.
4229
4230 Run GNAT in syntax checking only mode. For
4231 example, the command
4232
4233 @smallexample
4234 $ gcc -c -gnats x.adb
4235 @end smallexample
4236
4237 @noindent
4238 compiles file @file{x.adb} in syntax-check-only mode. You can check a
4239 series of files in a single command
4240 , and can use wild cards to specify such a group of files.
4241 Note that you must specify the @code{-c} (compile
4242 only) flag in addition to the @option{-gnats} flag.
4243 .
4244
4245 You may use other switches in conjunction with @option{-gnats}. In
4246 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
4247 format of any generated error messages.
4248
4249 The output is simply the error messages, if any. No object file or ALI
4250 file is generated by a syntax-only compilation. Also, no units other
4251 than the one specified are accessed. For example, if a unit @code{X}
4252 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
4253 check only mode does not access the source file containing unit
4254 @code{Y}.
4255
4256 @cindex Multiple units, syntax checking
4257 Normally, GNAT allows only a single unit in a source file. However, this
4258 restriction does not apply in syntax-check-only mode, and it is possible
4259 to check a file containing multiple compilation units concatenated
4260 together. This is primarily used by the @code{gnatchop} utility
4261 (@pxref{Renaming Files Using gnatchop}).
4262 @end table
4263
4264 @node Using gcc for Semantic Checking
4265 @subsection Using @code{gcc} for Semantic Checking
4266 @table @code
4267 @item -gnatc
4268 @cindex @option{-gnatc} (@code{gcc})
4269
4270 @noindent
4271 The @code{c} stands for check.
4272 Causes the compiler to operate in semantic check mode,
4273 with full checking for all illegalities specified in the
4274 Ada 95 Reference Manual, but without generation of any object code
4275 (no object file is generated).
4276
4277 Because dependent files must be accessed, you must follow the GNAT
4278 semantic restrictions on file structuring to operate in this mode:
4279
4280 @itemize @bullet
4281 @item
4282 The needed source files must be accessible
4283 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4284
4285 @item
4286 Each file must contain only one compilation unit.
4287
4288 @item
4289 The file name and unit name must match (@pxref{File Naming Rules}).
4290 @end itemize
4291
4292 The output consists of error messages as appropriate. No object file is
4293 generated. An @file{ALI} file is generated for use in the context of
4294 cross-reference tools, but this file is marked as not being suitable
4295 for binding (since no object file is generated).
4296 The checking corresponds exactly to the notion of
4297 legality in the Ada 95 Reference Manual.
4298
4299 Any unit can be compiled in semantics-checking-only mode, including
4300 units that would not normally be compiled (subunits,
4301 and specifications where a separate body is present).
4302 @end table
4303
4304 @node Compiling Ada 83 Programs
4305 @subsection Compiling Ada 83 Programs
4306 @table @code
4307 @cindex Ada 83 compatibility
4308 @item -gnat83
4309 @cindex @option{-gnat83} (@code{gcc})
4310 @cindex ACVC, Ada 83 tests
4311
4312 @noindent
4313 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
4314 specify that an Ada 83 program is to be compiled in Ada83 mode. If you specify
4315 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
4316 where this can be done easily.
4317 It is not possible to guarantee this switch does a perfect
4318 job; for example, some subtle tests, such as are
4319 found in earlier ACVC tests (that have been removed from the ACVC suite for Ada
4320 95), may not compile correctly. However, for most purposes, using
4321 this switch should help to ensure that programs that compile correctly
4322 under the @option{-gnat83} switch can be ported easily to an Ada 83
4323 compiler. This is the main use of the switch.
4324
4325 With few exceptions (most notably the need to use @code{<>} on
4326 @cindex Generic formal parameters
4327 unconstrained generic formal parameters, the use of the new Ada 95
4328 keywords, and the use of packages
4329 with optional bodies), it is not necessary to use the
4330 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
4331 exceptions, Ada 95 is upwardly compatible with Ada 83. This
4332 means that a correct Ada 83 program is usually also a correct Ada 95
4333 program.
4334
4335 @end table
4336
4337 @node Character Set Control
4338 @subsection Character Set Control
4339 @table @code
4340 @item -gnati@var{c}
4341 @cindex @code{-gnati} (@code{gcc})
4342
4343 @noindent
4344 Normally GNAT recognizes the Latin-1 character set in source program
4345 identifiers, as described in the Ada 95 Reference Manual.
4346 This switch causes
4347 GNAT to recognize alternate character sets in identifiers. @var{c} is a
4348 single character  indicating the character set, as follows:
4349
4350 @table @code
4351 @item 1
4352 Latin-1 identifiers
4353
4354 @item 2
4355 Latin-2 letters allowed in identifiers
4356
4357 @item 3
4358 Latin-3 letters allowed in identifiers
4359
4360 @item 4
4361 Latin-4 letters allowed in identifiers
4362
4363 @item 5
4364 Latin-5 (Cyrillic) letters allowed in identifiers
4365
4366 @item 9
4367 Latin-9 letters allowed in identifiers
4368
4369 @item p
4370 IBM PC letters (code page 437) allowed in identifiers
4371
4372 @item 8
4373 IBM PC letters (code page 850) allowed in identifiers
4374
4375 @item f
4376 Full upper-half codes allowed in identifiers
4377
4378 @item n
4379 No upper-half codes allowed in identifiers
4380
4381 @item w
4382 Wide-character codes (that is, codes greater than 255)
4383 allowed in identifiers
4384 @end table
4385
4386 @xref{Foreign Language Representation}, for full details on the
4387 implementation of these character sets.
4388
4389 @item -gnatW@var{e}
4390 @cindex @code{-gnatW} (@code{gcc})
4391 Specify the method of encoding for wide characters.
4392 @var{e} is one of the following:
4393
4394 @table @code
4395
4396 @item h
4397 Hex encoding (brackets coding also recognized)
4398
4399 @item u
4400 Upper half encoding (brackets encoding also recognized)
4401
4402 @item s
4403 Shift/JIS encoding (brackets encoding also recognized)
4404
4405 @item e
4406 EUC encoding (brackets encoding also recognized)
4407
4408 @item 8
4409 UTF-8 encoding (brackets encoding also recognized)
4410
4411 @item b
4412 Brackets encoding only (default value)
4413 @end table
4414 For full details on the these encoding
4415 methods see @xref{Wide Character Encodings}.
4416 Note that brackets coding is always accepted, even if one of the other
4417 options is specified, so for example @option{-gnatW8} specifies that both
4418 brackets and @code{UTF-8} encodings will be recognized. The units that are
4419 with'ed directly or indirectly will be scanned using the specified
4420 representation scheme, and so if one of the non-brackets scheme is
4421 used, it must be used consistently throughout the program. However,
4422 since brackets encoding is always recognized, it may be conveniently
4423 used in standard libraries, allowing these libraries to be used with
4424 any of the available coding schemes.
4425 scheme. If no @option{-gnatW?} parameter is present, then the default
4426 representation is Brackets encoding only.
4427
4428 Note that the wide character representation that is specified (explicitly
4429 or by default) for the main program also acts as the default encoding used
4430 for Wide_Text_IO files if not specifically overridden by a WCEM form
4431 parameter.
4432
4433 @end table
4434 @node File Naming Control
4435 @subsection File Naming Control
4436
4437 @table @code
4438 @item -gnatk@var{n}
4439 @cindex @option{-gnatk} (@code{gcc})
4440 Activates file name "krunching". @var{n}, a decimal integer in the range
4441 1-999, indicates the maximum allowable length of a file name (not
4442 including the @file{.ads} or @file{.adb} extension). The default is not
4443 to enable file name krunching.
4444
4445 For the source file naming rules, @xref{File Naming Rules}.
4446 @end table
4447
4448 @node Subprogram Inlining Control
4449 @subsection Subprogram Inlining Control
4450
4451 @table @code
4452 @item -gnatn
4453 @cindex @option{-gnatn} (@code{gcc})
4454 The @code{n} here is intended to suggest the first syllable of the
4455 word "inline".
4456 GNAT recognizes and processes @code{Inline} pragmas. However, for the
4457 inlining to actually occur, optimization must be enabled. To enable
4458 inlining across unit boundaries, this is, inlining a call in one unit of
4459 a subprogram declared in a @code{with}'ed unit, you must also specify
4460 this switch.
4461 In the absence of this switch, GNAT does not attempt
4462 inlining across units and does not need to access the bodies of
4463 subprograms for which @code{pragma Inline} is specified if they are not
4464 in the current unit.
4465
4466 If you specify this switch the compiler will access these bodies,
4467 creating an extra source dependency for the resulting object file, and
4468 where possible, the call will be inlined.
4469 For further details on when inlining is possible
4470 see @xref{Inlining of Subprograms}.
4471
4472 @item -gnatN
4473 @cindex @option{-gnatN} (@code{gcc})
4474 The front end inlining activated by this switch is generally more extensive,
4475 and quite often more effective than the standard @option{-gnatn} inlining mode.
4476 It will also generate additional dependencies.
4477
4478 @end table
4479
4480 @node Auxiliary Output Control
4481 @subsection Auxiliary Output Control
4482
4483 @table @code
4484 @item -gnatt
4485 @cindex @option{-gnatt} (@code{gcc})
4486 @cindex Writing internal trees
4487 @cindex Internal trees, writing to file
4488 Causes GNAT to write the internal tree for a unit to a file (with the
4489 extension @file{.adt}.
4490 This not normally required, but is used by separate analysis tools.
4491 Typically
4492 these tools do the necessary compilations automatically, so you should
4493 not have to specify this switch in normal operation.
4494
4495 @item -gnatu
4496 @cindex @option{-gnatu} (@code{gcc})
4497 Print a list of units required by this compilation on @file{stdout}.
4498 The listing includes all units on which the unit being compiled depends
4499 either directly or indirectly.
4500
4501 @item -pass-exit-codes
4502 @cindex @code{-pass-exit-codes} (@code{gcc})
4503 If this switch is not used, the exit code returned by @code{gcc} when
4504 compiling multiple files indicates whether all source files have
4505 been successfully used to generate object files or not.
4506
4507 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
4508 exit status and allows an integrated development environment to better
4509 react to a compilation failure. Those exit status are:
4510
4511 @table @asis
4512 @item 5
4513 There was an error in at least one source file.
4514 @item 3
4515 At least one source file did not generate an object file.
4516 @item 2
4517 The compiler died unexpectedly (internal error for example).
4518 @item 0
4519 An object file has been generated for every source file.
4520 @end table
4521 @end table
4522
4523 @node Debugging Control
4524 @subsection Debugging Control
4525
4526 @table @code
4527 @cindex Debugging options
4528 @item -gnatd@var{x}
4529 Activate internal debugging switches. @var{x} is a letter or digit, or
4530 string of letters or digits, which specifies the type of debugging
4531 outputs desired. Normally these are used only for internal development
4532 or system debugging purposes. You can find full documentation for these
4533 switches in the body of the @code{Debug} unit in the compiler source
4534 file @file{debug.adb}.
4535
4536 @item -gnatG
4537 @cindex @option{-gnatG} (@code{gcc})
4538 This switch causes the compiler to generate auxiliary output containing
4539 a pseudo-source listing of the generated expanded code. Like most Ada
4540 compilers, GNAT works by first transforming the high level Ada code into
4541 lower level constructs. For example, tasking operations are transformed
4542 into calls to the tasking run-time routines. A unique capability of GNAT
4543 is to list this expanded code in a form very close to normal Ada source.
4544 This is very useful in understanding the implications of various Ada
4545 usage on the efficiency of the generated code. There are many cases in
4546 Ada (e.g. the use of controlled types), where simple Ada statements can
4547 generate a lot of run-time code. By using @option{-gnatG} you can identify
4548 these cases, and consider whether it may be desirable to modify the coding
4549 approach to improve efficiency.
4550
4551 The format of the output is very similar to standard Ada source, and is
4552 easily understood by an Ada programmer. The following special syntactic
4553 additions correspond to low level features used in the generated code that
4554 do not have any exact analogies in pure Ada source form. The following
4555 is a partial list of these special constructions. See the specification
4556 of package @code{Sprint} in file @file{sprint.ads} for a full list.
4557
4558 @table @code
4559 @item new @var{xxx} [storage_pool = @var{yyy}]
4560 Shows the storage pool being used for an allocator.
4561
4562 @item at end @var{procedure-name};
4563 Shows the finalization (cleanup) procedure for a scope.
4564
4565 @item (if @var{expr} then @var{expr} else @var{expr})
4566 Conditional expression equivalent to the @code{x?y:z} construction in C.
4567
4568 @item @var{target}^(@var{source})
4569 A conversion with floating-point truncation instead of rounding.
4570
4571 @item @var{target}?(@var{source})
4572 A conversion that bypasses normal Ada semantic checking. In particular
4573 enumeration types and fixed-point types are treated simply as integers.
4574
4575 @item @var{target}?^(@var{source})
4576 Combines the above two cases.
4577
4578 @item @var{x} #/ @var{y}
4579 @itemx @var{x} #mod @var{y}
4580 @itemx @var{x} #* @var{y}
4581 @itemx @var{x} #rem @var{y}
4582 A division or multiplication of fixed-point values which are treated as
4583 integers without any kind of scaling.
4584
4585 @item free @var{expr} [storage_pool = @var{xxx}]
4586 Shows the storage pool associated with a @code{free} statement.
4587
4588 @item freeze @var{typename} [@var{actions}]
4589 Shows the point at which @var{typename} is frozen, with possible
4590 associated actions to be performed at the freeze point.
4591
4592 @item reference @var{itype}
4593 Reference (and hence definition) to internal type @var{itype}.
4594
4595 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
4596 Intrinsic function call.
4597
4598 @item @var{labelname} : label
4599 Declaration of label @var{labelname}.
4600
4601 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
4602 A multiple concatenation (same effect as @var{expr} & @var{expr} &
4603 @var{expr}, but handled more efficiently).
4604
4605 @item [constraint_error]
4606 Raise the @code{Constraint_Error} exception.
4607
4608 @item @var{expression}'reference
4609 A pointer to the result of evaluating @var{expression}.
4610
4611 @item @var{target-type}!(@var{source-expression})
4612 An unchecked conversion of @var{source-expression} to @var{target-type}.
4613
4614 @item [@var{numerator}/@var{denominator}]
4615 Used to represent internal real literals (that) have no exact
4616 representation in base 2-16 (for example, the result of compile time
4617 evaluation of the expression 1.0/27.0).
4618
4619 @item -gnatD
4620 @cindex @option{-gnatD} (@code{gcc})
4621 This switch is used in conjunction with @option{-gnatG} to cause the expanded
4622 source, as described above to be written to files with names
4623 @file{xxx.dg}, where @file{xxx} is the normal file name,
4624 for example, if the source file name is @file{hello.adb},
4625 then a file @file{hello.adb.dg} will be written.
4626 The debugging information generated
4627 by the @code{gcc} @code{-g} switch will refer to the generated
4628 @file{xxx.dg} file. This allows you to do source level debugging using
4629 the generated code which is sometimes useful for complex code, for example
4630 to find out exactly which part of a complex construction raised an
4631 exception. This switch also suppress generation of cross-reference
4632 information (see -gnatx).
4633
4634 @item -gnatC
4635 @cindex @option{-gnatE} (@code{gcc})
4636 In the generated debugging information, and also in the case of long external
4637 names, the compiler uses a compression mechanism if the name is very long.
4638 This compression method uses a checksum, and avoids trouble on some operating
4639 systems which have difficulty with very long names. The @option{-gnatC} switch
4640 forces this compression approach to be used on all external names and names
4641 in the debugging information tables. This reduces the size of the generated
4642 executable, at the expense of making the naming scheme more complex. The
4643 compression only affects the qualification of the name. Thus a name in
4644 the source:
4645
4646 @smallexample
4647 Very_Long_Package.Very_Long_Inner_Package.Var
4648 @end smallexample
4649
4650 @noindent
4651 would normally appear in these tables as:
4652
4653 @smallexample
4654 very_long_package__very_long_inner_package__var
4655 @end smallexample
4656
4657 @noindent
4658 but if the @option{-gnatC} switch is used, then the name appears as
4659
4660 @smallexample
4661 XCb7e0c705__var
4662 @end smallexample
4663
4664 @noindent
4665 Here b7e0c705 is a compressed encoding of the qualification prefix.
4666 The GNAT Ada aware version of GDB understands these encoded prefixes, so if this
4667 debugger is used, the encoding is largely hidden from the user of the compiler.
4668
4669 @end table
4670
4671 @item -gnatR[0|1|2|3][s]
4672 @cindex @option{-gnatR} (@code{gcc})
4673 This switch controls output from the compiler of a listing showing
4674 representation information for declared types and objects. For
4675 @option{-gnatR0}, no information is output (equivalent to omitting
4676 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
4677 so @option{-gnatR} with no parameter has the same effect), size and alignment
4678 information is listed for declared array and record types. For
4679 @option{-gnatR2}, size and alignment information is listed for all
4680 expression information for values that are computed at run time for
4681 variant records. These symbolic expressions have a mostly obvious
4682 format with #n being used to represent the value of the n'th
4683 discriminant. See source files @file{repinfo.ads/adb} in the
4684 @code{GNAT} sources for full detalis on the format of @option{-gnatR3}
4685 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
4686 the output is to a file with the name @file{file.rep} where
4687 file is the name of the corresponding source file.
4688
4689 @item -gnatx
4690 @cindex @option{-gnatx} (@code{gcc})
4691 Normally the compiler generates full cross-referencing information in
4692 the @file{ALI} file. This information is used by a number of tools,
4693 including @code{gnatfind} and @code{gnatxref}. The -gnatx switch
4694 suppresses this information. This saves some space and may slightly
4695 speed up compilation, but means that these tools cannot be used.
4696 @end table
4697
4698 @node Units to Sources Mapping Files
4699 @subsection Units to Sources Mapping Files
4700
4701 @table @code
4702
4703 @item -gnatem@var{path}
4704 @cindex @option{-gnatem} (@code{gcc})
4705 A mapping file is a way to communicate to the compiler two mappings:
4706 from unit names to file names (without any directory information) and from
4707 file names to path names (with full directory information). These mappings
4708 are used by the compiler to short-circuit the path search.
4709
4710 A mapping file is a sequence of sets of three lines. In each set,
4711 the first line is the unit name, in lower case, with "%s" appended for
4712 specifications and "%b" appended for bodies; the second line is the file
4713 name; and the third line is the path name.
4714
4715 Example:
4716 @smallexample
4717    main%b
4718    main.2.ada
4719    /gnat/project1/sources/main.2.ada
4720 @end smallexample
4721
4722 When the switch @option{-gnatem} is specified, the compiler will create
4723 in memory the two mappings from the specified file. If there is any problem
4724 (non existent file, truncated file or duplicate entries), no mapping
4725 will be created.
4726
4727 Several @option{-gnatem} switches may be specified; however, only the last
4728 one on the command line will be taken into account.
4729
4730 When using a project file, @code{gnatmake} create a temporary mapping file
4731 and communicates it to the compiler using this switch.
4732
4733 @end table
4734
4735 @node Search Paths and the Run-Time Library (RTL)
4736 @section Search Paths and the Run-Time Library (RTL)
4737
4738 @noindent
4739 With the GNAT source-based library system, the compiler must be able to
4740 find source files for units that are needed by the unit being compiled.
4741 Search paths are used to guide this process.
4742
4743 The compiler compiles one source file whose name must be given
4744 explicitly on the command line. In other words, no searching is done
4745 for this file. To find all other source files that are needed (the most
4746 common being the specs of units), the compiler examines the following
4747 directories, in the following order:
4748
4749 @enumerate
4750 @item
4751 The directory containing the source file of the main unit being compiled
4752 (the file name on the command line).
4753
4754 @item
4755 Each directory named by an @code{-I} switch given on the @code{gcc}
4756 command line, in the order given.
4757
4758 @item
4759 @findex ADA_INCLUDE_PATH
4760 Each of the directories listed in the value of the
4761 @code{ADA_INCLUDE_PATH} environment variable.
4762 Construct this value
4763 exactly as the @code{PATH} environment variable: a list of directory
4764 names separated by colons (semicolons when working with the NT version).
4765 @item
4766 The content of the "ada_source_path" file which is part of the GNAT
4767 installation tree and is used to store standard libraries such as the
4768 GNAT Run Time Library (RTL) source files.
4769 @ref{Installing an Ada Library}
4770 @end enumerate
4771
4772 @noindent
4773 Specifying the switch @code{-I-}
4774 inhibits the use of the directory
4775 containing the source file named in the command line. You can still
4776 have this directory on your search path, but in this case it must be
4777 explicitly requested with a @code{-I} switch.
4778
4779 Specifying the switch @code{-nostdinc}
4780 inhibits the search of the default location for the GNAT Run Time
4781 Library (RTL) source files.
4782
4783 The compiler outputs its object files and ALI files in the current
4784 working directory.
4785 Caution: The object file can be redirected with the @code{-o} switch;
4786 however, @code{gcc} and @code{gnat1} have not been coordinated on this
4787 so the ALI file will not go to the right place. Therefore, you should
4788 avoid using the @code{-o} switch.
4789
4790 @findex System.IO
4791 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
4792 children make up the GNAT RTL, together with the simple @code{System.IO}
4793 package used in the "Hello World" example. The sources for these units
4794 are needed by the compiler and are kept together in one directory. Not
4795 all of the bodies are needed, but all of the sources are kept together
4796 anyway. In a normal installation, you need not specify these directory
4797 names when compiling or binding. Either the environment variables or
4798 the built-in defaults cause these files to be found.
4799
4800 In addition to the language-defined hierarchies (System, Ada and
4801 Interfaces), the GNAT distribution provides a fourth hierarchy,
4802 consisting of child units of GNAT. This is a collection of generally
4803 useful routines. See the GNAT Reference Manual for further details.
4804
4805 Besides simplifying access to the RTL, a major use of search paths is
4806 in compiling sources from multiple directories. This can make
4807 development environments much more flexible.
4808
4809 @node Order of Compilation Issues
4810 @section Order of Compilation Issues
4811
4812 @noindent
4813 If, in our earlier example, there was a spec for the @code{hello}
4814 procedure, it would be contained in the file @file{hello.ads}; yet this
4815 file would not have to be explicitly compiled. This is the result of the
4816 model we chose to implement library management. Some of the consequences
4817 of this model are as follows:
4818
4819 @itemize @bullet
4820 @item
4821 There is no point in compiling specs (except for package
4822 specs with no bodies) because these are compiled as needed by clients. If
4823 you attempt a useless compilation, you will receive an error message.
4824 It is also useless to compile subunits because they are compiled as needed
4825 by the parent.
4826
4827 @item
4828 There are no order of compilation requirements: performing a
4829 compilation never obsoletes anything. The only way you can obsolete
4830 something and require recompilations is to modify one of the
4831 source files on which it depends.
4832
4833 @item
4834 There is no library as such, apart from the ALI files
4835 (@pxref{The Ada Library Information Files}, for information on the format of these
4836 files). For now we find it convenient to create separate ALI files, but
4837 eventually the information therein may be incorporated into the object
4838 file directly.
4839
4840 @item
4841 When you compile a unit, the source files for the specs of all units
4842 that it @code{with}'s, all its subunits, and the bodies of any generics it
4843 instantiates must be available (reachable by the search-paths mechanism
4844 described above), or you will receive a fatal error message.
4845 @end itemize
4846
4847 @node Examples
4848 @section Examples
4849
4850 @noindent
4851 The following are some typical Ada compilation command line examples:
4852
4853 @table @code
4854 @item $ gcc -c xyz.adb
4855 Compile body in file @file{xyz.adb} with all default options.
4856
4857 @item $ gcc -c -O2 -gnata xyz-def.adb
4858
4859 Compile the child unit package in file @file{xyz-def.adb} with extensive
4860 optimizations, and pragma @code{Assert}/@code{Debug} statements
4861 enabled.
4862
4863 @item $ gcc -c -gnatc abc-def.adb
4864 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
4865 mode.
4866 @end table
4867
4868 @node Binding Using gnatbind
4869 @chapter Binding Using @code{gnatbind}
4870 @findex gnatbind
4871
4872 @menu
4873 * Running gnatbind::
4874 * Generating the Binder Program in C::
4875 * Consistency-Checking Modes::
4876 * Binder Error Message Control::
4877 * Elaboration Control::
4878 * Output Control::
4879 * Binding with Non-Ada Main Programs::
4880 * Binding Programs with No Main Subprogram::
4881 * Summary of Binder Switches::
4882 * Command-Line Access::
4883 * Search Paths for gnatbind::
4884 * Examples of gnatbind Usage::
4885 @end menu
4886
4887 @noindent
4888 This chapter describes the GNAT binder, @code{gnatbind}, which is used
4889 to bind compiled GNAT objects. The @code{gnatbind} program performs
4890 four separate functions:
4891
4892 @enumerate
4893 @item
4894 Checks that a program is consistent, in accordance with the rules in
4895 Chapter 10 of the Ada 95 Reference Manual. In particular, error
4896 messages are generated if a program uses inconsistent versions of a
4897 given unit.
4898
4899 @item
4900 Checks that an acceptable order of elaboration exists for the program
4901 and issues an error message if it cannot find an order of elaboration
4902 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
4903
4904 @item
4905 Generates a main program incorporating the given elaboration order.
4906 This program is a small Ada package (body and spec) that
4907 must be subsequently compiled
4908 using the GNAT compiler. The necessary compilation step is usually
4909 performed automatically by @code{gnatlink}. The two most important
4910 functions of this program
4911 are to call the elaboration routines of units in an appropriate order
4912 and to call the main program.
4913
4914 @item
4915 Determines the set of object files required by the given main program.
4916 This information is output in the forms of comments in the generated program,
4917 to be read by the @code{gnatlink} utility used to link the Ada application.
4918 @end enumerate
4919
4920 @node Running gnatbind
4921 @section Running @code{gnatbind}
4922
4923 @noindent
4924 The form of the @code{gnatbind} command is
4925
4926 @smallexample
4927 $ gnatbind [@var{switches}] @var{mainprog}[.ali] [@var{switches}]
4928 @end smallexample
4929
4930 @noindent
4931 where @var{mainprog}.adb is the Ada file containing the main program
4932 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
4933 package in two files which names are
4934 @file{b~@var{ada_main}.ads}, and @file{b~@var{ada_main}.adb}.
4935 For example, if given the
4936 parameter @samp{hello.ali}, for a main program contained in file
4937 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
4938 and @file{b~hello.adb}.
4939
4940 When doing consistency checking, the binder takes into consideration
4941 any source files it can locate. For example, if the binder determines
4942 that the given main program requires the package @code{Pack}, whose
4943 @file{.ali}
4944 file is @file{pack.ali} and whose corresponding source spec file is
4945 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
4946 (using the same search path conventions as previously described for the
4947 @code{gcc} command). If it can locate this source file, it checks that
4948 the time stamps
4949 or source checksums of the source and its references to in @file{ali} files
4950 match. In other words, any @file{ali} files that mentions this spec must have
4951 resulted from compiling this version of the source file (or in the case
4952 where the source checksums match, a version close enough that the
4953 difference does not matter).
4954
4955 @cindex Source files, use by binder
4956 The effect of this consistency checking, which includes source files, is
4957 that the binder ensures that the program is consistent with the latest
4958 version of the source files that can be located at bind time. Editing a
4959 source file without compiling files that depend on the source file cause
4960 error messages to be generated by the binder.
4961
4962 For example, suppose you have a main program @file{hello.adb} and a
4963 package @code{P}, from file @file{p.ads} and you perform the following
4964 steps:
4965
4966 @enumerate
4967 @item
4968 Enter @code{gcc -c hello.adb} to compile the main program.
4969
4970 @item
4971 Enter @code{gcc -c p.ads} to compile package @code{P}.
4972
4973 @item
4974 Edit file @file{p.ads}.
4975
4976 @item
4977 Enter @code{gnatbind hello}.
4978 @end enumerate
4979
4980 At this point, the file @file{p.ali} contains an out-of-date time stamp
4981 because the file @file{p.ads} has been edited. The attempt at binding
4982 fails, and the binder generates the following error messages:
4983
4984 @smallexample
4985 error: "hello.adb" must be recompiled ("p.ads" has been modified)
4986 error: "p.ads" has been modified and must be recompiled
4987 @end smallexample
4988
4989 @noindent
4990 Now both files must be recompiled as indicated, and then the bind can
4991 succeed, generating a main program. You need not normally be concerned
4992 with the contents of this file, but it is similar to the following which
4993 is the binder file generated for a simple "hello world" program.
4994
4995 @smallexample
4996 @iftex
4997 @leftskip=0cm
4998 @end iftex
4999 --  The package is called Ada_Main unless this name is actually used
5000 --  as a unit name in the partition, in which case some other unique
5001 --  name is used.
5002
5003 with System;
5004 package ada_main is
5005
5006    Elab_Final_Code : Integer;
5007    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
5008
5009    --  The main program saves the parameters (argument count,
5010    --  argument values, environment pointer) in global variables
5011    --  for later access by other units including
5012    --  Ada.Command_Line.
5013
5014    gnat_argc : Integer;
5015    gnat_argv : System.Address;
5016    gnat_envp : System.Address;
5017
5018    --  The actual variables are stored in a library routine. This
5019    --  is useful for some shared library situations, where there
5020    --  are problems if variables are not in the library.
5021
5022    pragma Import (C, gnat_argc);
5023    pragma Import (C, gnat_argv);
5024    pragma Import (C, gnat_envp);
5025
5026    --  The exit status is similarly an external location
5027
5028    gnat_exit_status : Integer;
5029    pragma Import (C, gnat_exit_status);
5030
5031    GNAT_Version : constant String :=
5032                     "GNAT Version: 3.15w (20010315)";
5033    pragma Export (C, GNAT_Version, "__gnat_version");
5034
5035    --  This is the generated adafinal routine that performs
5036    --  finalization at the end of execution. In the case where
5037    --  Ada is the main program, this main program makes a call
5038    --  to adafinal at program termination.
5039
5040    procedure adafinal;
5041    pragma Export (C, adafinal, "adafinal");
5042
5043    --  This is the generated adainit routine that performs
5044    --  initialization at the start of execution. In the case
5045    --  where Ada is the main program, this main program makes
5046    --  a call to adainit at program startup.
5047
5048    procedure adainit;
5049    pragma Export (C, adainit, "adainit");
5050
5051    --  This routine is called at the start of execution. It is
5052    --  a dummy routine that is used by the debugger to breakpoint
5053    --  at the start of execution.
5054
5055    procedure Break_Start;
5056    pragma Import (C, Break_Start, "__gnat_break_start");
5057
5058    --  This is the actual generated main program (it would be
5059    --  suppressed if the no main program switch were used). As
5060    --  required by standard system conventions, this program has
5061    --  the external name main.
5062
5063    function main
5064      (argc : Integer;
5065       argv : System.Address;
5066       envp : System.Address)
5067       return Integer;
5068    pragma Export (C, main, "main");
5069
5070    --  The following set of constants give the version
5071    --  identification values for every unit in the bound
5072    --  partition. This identification is computed from all
5073    --  dependent semantic units, and corresponds to the
5074    --  string that would be returned by use of the
5075    --  Body_Version or Version attributes.
5076
5077    type Version_32 is mod 2 ** 32;
5078    u00001 : constant Version_32 := 16#7880BEB3#;
5079    u00002 : constant Version_32 := 16#0D24CBD0#;
5080    u00003 : constant Version_32 := 16#3283DBEB#;
5081    u00004 : constant Version_32 := 16#2359F9ED#;
5082    u00005 : constant Version_32 := 16#664FB847#;
5083    u00006 : constant Version_32 := 16#68E803DF#;
5084    u00007 : constant Version_32 := 16#5572E604#;
5085    u00008 : constant Version_32 := 16#46B173D8#;
5086    u00009 : constant Version_32 := 16#156A40CF#;
5087    u00010 : constant Version_32 := 16#033DABE0#;
5088    u00011 : constant Version_32 := 16#6AB38FEA#;
5089    u00012 : constant Version_32 := 16#22B6217D#;
5090    u00013 : constant Version_32 := 16#68A22947#;
5091    u00014 : constant Version_32 := 16#18CC4A56#;
5092    u00015 : constant Version_32 := 16#08258E1B#;
5093    u00016 : constant Version_32 := 16#367D5222#;
5094    u00017 : constant Version_32 := 16#20C9ECA4#;
5095    u00018 : constant Version_32 := 16#50D32CB6#;
5096    u00019 : constant Version_32 := 16#39A8BB77#;
5097    u00020 : constant Version_32 := 16#5CF8FA2B#;
5098    u00021 : constant Version_32 := 16#2F1EB794#;
5099    u00022 : constant Version_32 := 16#31AB6444#;
5100    u00023 : constant Version_32 := 16#1574B6E9#;
5101    u00024 : constant Version_32 := 16#5109C189#;
5102    u00025 : constant Version_32 := 16#56D770CD#;
5103    u00026 : constant Version_32 := 16#02F9DE3D#;
5104    u00027 : constant Version_32 := 16#08AB6B2C#;
5105    u00028 : constant Version_32 := 16#3FA37670#;
5106    u00029 : constant Version_32 := 16#476457A0#;
5107    u00030 : constant Version_32 := 16#731E1B6E#;
5108    u00031 : constant Version_32 := 16#23C2E789#;
5109    u00032 : constant Version_32 := 16#0F1BD6A1#;
5110    u00033 : constant Version_32 := 16#7C25DE96#;
5111    u00034 : constant Version_32 := 16#39ADFFA2#;
5112    u00035 : constant Version_32 := 16#571DE3E7#;
5113    u00036 : constant Version_32 := 16#5EB646AB#;
5114    u00037 : constant Version_32 := 16#4249379B#;
5115    u00038 : constant Version_32 := 16#0357E00A#;
5116    u00039 : constant Version_32 := 16#3784FB72#;
5117    u00040 : constant Version_32 := 16#2E723019#;
5118    u00041 : constant Version_32 := 16#623358EA#;
5119    u00042 : constant Version_32 := 16#107F9465#;
5120    u00043 : constant Version_32 := 16#6843F68A#;
5121    u00044 : constant Version_32 := 16#63305874#;
5122    u00045 : constant Version_32 := 16#31E56CE1#;
5123    u00046 : constant Version_32 := 16#02917970#;
5124    u00047 : constant Version_32 := 16#6CCBA70E#;
5125    u00048 : constant Version_32 := 16#41CD4204#;
5126    u00049 : constant Version_32 := 16#572E3F58#;
5127    u00050 : constant Version_32 := 16#20729FF5#;
5128    u00051 : constant Version_32 := 16#1D4F93E8#;
5129    u00052 : constant Version_32 := 16#30B2EC3D#;
5130    u00053 : constant Version_32 := 16#34054F96#;
5131    u00054 : constant Version_32 := 16#5A199860#;
5132    u00055 : constant Version_32 := 16#0E7F912B#;
5133    u00056 : constant Version_32 := 16#5760634A#;
5134    u00057 : constant Version_32 := 16#5D851835#;
5135
5136    --  The following Export pragmas export the version numbers
5137    --  with symbolic names ending in B (for body) or S
5138    --  (for spec) so that they can be located in a link. The
5139    --  information provided here is sufficient to track down
5140    --  the exact versions of units used in a given build.
5141
5142    pragma Export (C, u00001, "helloB");
5143    pragma Export (C, u00002, "system__standard_libraryB");
5144    pragma Export (C, u00003, "system__standard_libraryS");
5145    pragma Export (C, u00004, "adaS");
5146    pragma Export (C, u00005, "ada__text_ioB");
5147    pragma Export (C, u00006, "ada__text_ioS");
5148    pragma Export (C, u00007, "ada__exceptionsB");
5149    pragma Export (C, u00008, "ada__exceptionsS");
5150    pragma Export (C, u00009, "gnatS");
5151    pragma Export (C, u00010, "gnat__heap_sort_aB");
5152    pragma Export (C, u00011, "gnat__heap_sort_aS");
5153    pragma Export (C, u00012, "systemS");
5154    pragma Export (C, u00013, "system__exception_tableB");
5155    pragma Export (C, u00014, "system__exception_tableS");
5156    pragma Export (C, u00015, "gnat__htableB");
5157    pragma Export (C, u00016, "gnat__htableS");
5158    pragma Export (C, u00017, "system__exceptionsS");
5159    pragma Export (C, u00018, "system__machine_state_operationsB");
5160    pragma Export (C, u00019, "system__machine_state_operationsS");
5161    pragma Export (C, u00020, "system__machine_codeS");
5162    pragma Export (C, u00021, "system__storage_elementsB");
5163    pragma Export (C, u00022, "system__storage_elementsS");
5164    pragma Export (C, u00023, "system__secondary_stackB");
5165    pragma Export (C, u00024, "system__secondary_stackS");
5166    pragma Export (C, u00025, "system__parametersB");
5167    pragma Export (C, u00026, "system__parametersS");
5168    pragma Export (C, u00027, "system__soft_linksB");
5169    pragma Export (C, u00028, "system__soft_linksS");
5170    pragma Export (C, u00029, "system__stack_checkingB");
5171    pragma Export (C, u00030, "system__stack_checkingS");
5172    pragma Export (C, u00031, "system__tracebackB");
5173    pragma Export (C, u00032, "system__tracebackS");
5174    pragma Export (C, u00033, "ada__streamsS");
5175    pragma Export (C, u00034, "ada__tagsB");
5176    pragma Export (C, u00035, "ada__tagsS");
5177    pragma Export (C, u00036, "system__string_opsB");
5178    pragma Export (C, u00037, "system__string_opsS");
5179    pragma Export (C, u00038, "interfacesS");
5180    pragma Export (C, u00039, "interfaces__c_streamsB");
5181    pragma Export (C, u00040, "interfaces__c_streamsS");
5182    pragma Export (C, u00041, "system__file_ioB");
5183    pragma Export (C, u00042, "system__file_ioS");
5184    pragma Export (C, u00043, "ada__finalizationB");
5185    pragma Export (C, u00044, "ada__finalizationS");
5186    pragma Export (C, u00045, "system__finalization_rootB");
5187    pragma Export (C, u00046, "system__finalization_rootS");
5188    pragma Export (C, u00047, "system__finalization_implementationB");
5189    pragma Export (C, u00048, "system__finalization_implementationS");
5190    pragma Export (C, u00049, "system__string_ops_concat_3B");
5191    pragma Export (C, u00050, "system__string_ops_concat_3S");
5192    pragma Export (C, u00051, "system__stream_attributesB");
5193    pragma Export (C, u00052, "system__stream_attributesS");
5194    pragma Export (C, u00053, "ada__io_exceptionsS");
5195    pragma Export (C, u00054, "system__unsigned_typesS");
5196    pragma Export (C, u00055, "system__file_control_blockS");
5197    pragma Export (C, u00056, "ada__finalization__list_controllerB");
5198    pragma Export (C, u00057, "ada__finalization__list_controllerS");
5199
5200    -- BEGIN ELABORATION ORDER
5201    -- ada (spec)
5202    -- gnat (spec)
5203    -- gnat.heap_sort_a (spec)
5204    -- gnat.heap_sort_a (body)
5205    -- gnat.htable (spec)
5206    -- gnat.htable (body)
5207    -- interfaces (spec)
5208    -- system (spec)
5209    -- system.machine_code (spec)
5210    -- system.parameters (spec)
5211    -- system.parameters (body)
5212    -- interfaces.c_streams (spec)
5213    -- interfaces.c_streams (body)
5214    -- system.standard_library (spec)
5215    -- ada.exceptions (spec)
5216    -- system.exception_table (spec)
5217    -- system.exception_table (body)
5218    -- ada.io_exceptions (spec)
5219    -- system.exceptions (spec)
5220    -- system.storage_elements (spec)
5221    -- system.storage_elements (body)
5222    -- system.machine_state_operations (spec)
5223    -- system.machine_state_operations (body)
5224    -- system.secondary_stack (spec)
5225    -- system.stack_checking (spec)
5226    -- system.soft_links (spec)
5227    -- system.soft_links (body)
5228    -- system.stack_checking (body)
5229    -- system.secondary_stack (body)
5230    -- system.standard_library (body)
5231    -- system.string_ops (spec)
5232    -- system.string_ops (body)
5233    -- ada.tags (spec)
5234    -- ada.tags (body)
5235    -- ada.streams (spec)
5236    -- system.finalization_root (spec)
5237    -- system.finalization_root (body)
5238    -- system.string_ops_concat_3 (spec)
5239    -- system.string_ops_concat_3 (body)
5240    -- system.traceback (spec)
5241    -- system.traceback (body)
5242    -- ada.exceptions (body)
5243    -- system.unsigned_types (spec)
5244    -- system.stream_attributes (spec)
5245    -- system.stream_attributes (body)
5246    -- system.finalization_implementation (spec)
5247    -- system.finalization_implementation (body)
5248    -- ada.finalization (spec)
5249    -- ada.finalization (body)
5250    -- ada.finalization.list_controller (spec)
5251    -- ada.finalization.list_controller (body)
5252    -- system.file_control_block (spec)
5253    -- system.file_io (spec)
5254    -- system.file_io (body)
5255    -- ada.text_io (spec)
5256    -- ada.text_io (body)
5257    -- hello (body)
5258    -- END ELABORATION ORDER
5259
5260 end ada_main;
5261
5262 --  The following source file name pragmas allow the generated file
5263 --  names to be unique for different main programs. They are needed
5264 --  since the package name will always be Ada_Main.
5265
5266 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
5267 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
5268
5269 --  Generated package body for Ada_Main starts here
5270
5271 package body ada_main is
5272
5273    --  The actual finalization is performed by calling the
5274    --  library routine in System.Standard_Library.Adafinal
5275
5276    procedure Do_Finalize;
5277    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
5278
5279    -------------
5280    -- adainit --
5281    -------------
5282
5283 @findex adainit
5284    procedure adainit is
5285
5286       --  These booleans are set to True once the associated unit has
5287       --  been elaborated. It is also used to avoid elaborating the
5288       --  same unit twice.
5289
5290       E040 : Boolean; pragma Import (Ada, E040, "interfaces__c_streams_E");
5291       E008 : Boolean; pragma Import (Ada, E008, "ada__exceptions_E");
5292       E014 : Boolean; pragma Import (Ada, E014, "system__exception_table_E");
5293       E053 : Boolean; pragma Import (Ada, E053, "ada__io_exceptions_E");
5294       E017 : Boolean; pragma Import (Ada, E017, "system__exceptions_E");
5295       E024 : Boolean; pragma Import (Ada, E024, "system__secondary_stack_E");
5296       E030 : Boolean; pragma Import (Ada, E030, "system__stack_checking_E");
5297       E028 : Boolean; pragma Import (Ada, E028, "system__soft_links_E");
5298       E035 : Boolean; pragma Import (Ada, E035, "ada__tags_E");
5299       E033 : Boolean; pragma Import (Ada, E033, "ada__streams_E");
5300       E046 : Boolean; pragma Import (Ada, E046, "system__finalization_root_E");
5301       E048 : Boolean; pragma Import (Ada, E048, "system__finalization_implementation_E");
5302       E044 : Boolean; pragma Import (Ada, E044, "ada__finalization_E");
5303       E057 : Boolean; pragma Import (Ada, E057, "ada__finalization__list_controller_E");
5304       E055 : Boolean; pragma Import (Ada, E055, "system__file_control_block_E");
5305       E042 : Boolean; pragma Import (Ada, E042, "system__file_io_E");
5306       E006 : Boolean; pragma Import (Ada, E006, "ada__text_io_E");
5307
5308       --  Set_Globals is a library routine that stores away the
5309       --  value of the indicated set of global values in global
5310       --  variables within the library.
5311
5312       procedure Set_Globals
5313         (Main_Priority            : Integer;
5314          Time_Slice_Value         : Integer;
5315          WC_Encoding              : Character;
5316          Locking_Policy           : Character;
5317          Queuing_Policy           : Character;
5318          Task_Dispatching_Policy  : Character;
5319          Adafinal                 : System.Address;
5320          Unreserve_All_Interrupts : Integer;
5321          Exception_Tracebacks     : Integer);
5322 @findex __gnat_set_globals
5323       pragma Import (C, Set_Globals, "__gnat_set_globals");
5324
5325       --  SDP_Table_Build is a library routine used to build the
5326       --  exception tables. See unit Ada.Exceptions in files
5327       --  a-except.ads/adb for full details of how zero cost
5328       --  exception handling works. This procedure, the call to
5329       --  it, and the two following tables are all omitted if the
5330       --  build is in longjmp/setjump exception mode.
5331
5332 @findex SDP_Table_Build
5333 @findex Zero Cost Exceptions
5334       procedure SDP_Table_Build
5335         (SDP_Addresses   : System.Address;
5336          SDP_Count       : Natural;
5337          Elab_Addresses  : System.Address;
5338          Elab_Addr_Count : Natural);
5339       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
5340
5341       --  Table of Unit_Exception_Table addresses. Used for zero
5342       --  cost exception handling to build the top level table.
5343
5344       ST : aliased constant array (1 .. 23) of System.Address := (
5345         Hello'UET_Address,
5346         Ada.Text_Io'UET_Address,
5347         Ada.Exceptions'UET_Address,
5348         Gnat.Heap_Sort_A'UET_Address,
5349         System.Exception_Table'UET_Address,
5350         System.Machine_State_Operations'UET_Address,
5351         System.Secondary_Stack'UET_Address,
5352         System.Parameters'UET_Address,
5353         System.Soft_Links'UET_Address,
5354         System.Stack_Checking'UET_Address,
5355         System.Traceback'UET_Address,
5356         Ada.Streams'UET_Address,
5357         Ada.Tags'UET_Address,
5358         System.String_Ops'UET_Address,
5359         Interfaces.C_Streams'UET_Address,
5360         System.File_Io'UET_Address,
5361         Ada.Finalization'UET_Address,
5362         System.Finalization_Root'UET_Address,
5363         System.Finalization_Implementation'UET_Address,
5364         System.String_Ops_Concat_3'UET_Address,
5365         System.Stream_Attributes'UET_Address,
5366         System.File_Control_Block'UET_Address,
5367         Ada.Finalization.List_Controller'UET_Address);
5368
5369       --  Table of addresses of elaboration routines. Used for
5370       --  zero cost exception handling to make sure these
5371       --  addresses are included in the top level procedure
5372       --  address table.
5373
5374       EA : aliased constant array (1 .. 23) of System.Address := (
5375         adainit'Code_Address,
5376         Do_Finalize'Code_Address,
5377         Ada.Exceptions'Elab_Spec'Address,
5378         System.Exceptions'Elab_Spec'Address,
5379         Interfaces.C_Streams'Elab_Spec'Address,
5380         System.Exception_Table'Elab_Body'Address,
5381         Ada.Io_Exceptions'Elab_Spec'Address,
5382         System.Stack_Checking'Elab_Spec'Address,
5383         System.Soft_Links'Elab_Body'Address,
5384         System.Secondary_Stack'Elab_Body'Address,
5385         Ada.Tags'Elab_Spec'Address,
5386         Ada.Tags'Elab_Body'Address,
5387         Ada.Streams'Elab_Spec'Address,
5388         System.Finalization_Root'Elab_Spec'Address,
5389         Ada.Exceptions'Elab_Body'Address,
5390         System.Finalization_Implementation'Elab_Spec'Address,
5391         System.Finalization_Implementation'Elab_Body'Address,
5392         Ada.Finalization'Elab_Spec'Address,
5393         Ada.Finalization.List_Controller'Elab_Spec'Address,
5394         System.File_Control_Block'Elab_Spec'Address,
5395         System.File_Io'Elab_Body'Address,
5396         Ada.Text_Io'Elab_Spec'Address,
5397         Ada.Text_Io'Elab_Body'Address);
5398
5399    --  Start of processing for adainit
5400
5401    begin
5402
5403       --  Call SDP_Table_Build to build the top level procedure
5404       --  table for zero cost exception handling (omitted in
5405       --  longjmp/setjump mode).
5406
5407       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
5408
5409       --  Call Set_Globals to record various information for
5410       --  this partition.  The values are derived by the binder
5411       --  from information stored in the ali files by the compiler.
5412
5413 @findex __gnat_set_globals
5414       Set_Globals
5415         (Main_Priority            => -1,
5416          --  Priority of main program, -1 if no pragma Priority used
5417
5418          Time_Slice_Value         => -1,
5419          --  Time slice from Time_Slice pragma, -1 if none used
5420
5421          WC_Encoding              => 'b',
5422          --  Wide_Character encoding used, default is brackets
5423
5424          Locking_Policy           => ' ',
5425          --  Locking_Policy used, default of space means not
5426          --  specified, otherwise it is the first character of
5427          --  the policy name.
5428
5429          Queuing_Policy           => ' ',
5430          --  Queuing_Policy used, default of space means not
5431          --  specified, otherwise it is the first character of
5432          --  the policy name.
5433
5434          Task_Dispatching_Policy  => ' ',
5435          --  Task_Dispatching_Policy used, default of space means
5436          --  not specified, otherwise first character of the
5437          --  policy name.
5438
5439          Adafinal                 => System.Null_Address,
5440          --  Address of Adafinal routine, not used anymore
5441
5442          Unreserve_All_Interrupts => 0,
5443          --  Set true if pragma Unreserve_All_Interrupts was used
5444
5445          Exception_Tracebacks     => 0);
5446          --  Indicates if exception tracebacks are enabled
5447
5448       Elab_Final_Code := 1;
5449
5450       --  Now we have the elaboration calls for all units in the partition.
5451       --  The Elab_Spec and Elab_Body attributes generate references to the
5452       --  implicit elaboration procedures generated by the compiler for
5453       --  each unit that requires elaboration.
5454
5455       if not E040 then
5456          Interfaces.C_Streams'Elab_Spec;
5457       end if;
5458       E040 := True;
5459       if not E008 then
5460          Ada.Exceptions'Elab_Spec;
5461       end if;
5462       if not E014 then
5463          System.Exception_Table'Elab_Body;
5464          E014 := True;
5465       end if;
5466       if not E053 then
5467          Ada.Io_Exceptions'Elab_Spec;
5468          E053 := True;
5469       end if;
5470       if not E017 then
5471          System.Exceptions'Elab_Spec;
5472          E017 := True;
5473       end if;
5474       if not E030 then
5475          System.Stack_Checking'Elab_Spec;
5476       end if;
5477       if not E028 then
5478          System.Soft_Links'Elab_Body;
5479          E028 := True;
5480       end if;
5481       E030 := True;
5482       if not E024 then
5483          System.Secondary_Stack'Elab_Body;
5484          E024 := True;
5485       end if;
5486       if not E035 then
5487          Ada.Tags'Elab_Spec;
5488       end if;
5489       if not E035 then
5490          Ada.Tags'Elab_Body;
5491          E035 := True;
5492       end if;
5493       if not E033 then
5494          Ada.Streams'Elab_Spec;
5495          E033 := True;
5496       end if;
5497       if not E046 then
5498          System.Finalization_Root'Elab_Spec;
5499       end if;
5500       E046 := True;
5501       if not E008 then
5502          Ada.Exceptions'Elab_Body;
5503          E008 := True;
5504       end if;
5505       if not E048 then
5506          System.Finalization_Implementation'Elab_Spec;
5507       end if;
5508       if not E048 then
5509          System.Finalization_Implementation'Elab_Body;
5510          E048 := True;
5511       end if;
5512       if not E044 then
5513          Ada.Finalization'Elab_Spec;
5514       end if;
5515       E044 := True;
5516       if not E057 then
5517          Ada.Finalization.List_Controller'Elab_Spec;
5518       end if;
5519       E057 := True;
5520       if not E055 then
5521          System.File_Control_Block'Elab_Spec;
5522          E055 := True;
5523       end if;
5524       if not E042 then
5525          System.File_Io'Elab_Body;
5526          E042 := True;
5527       end if;
5528       if not E006 then
5529          Ada.Text_Io'Elab_Spec;
5530       end if;
5531       if not E006 then
5532          Ada.Text_Io'Elab_Body;
5533          E006 := True;
5534       end if;
5535
5536       Elab_Final_Code := 0;
5537    end adainit;
5538
5539    --------------
5540    -- adafinal --
5541    --------------
5542
5543 @findex adafinal
5544    procedure adafinal is
5545    begin
5546       Do_Finalize;
5547    end adafinal;
5548
5549    ----------
5550    -- main --
5551    ----------
5552
5553    --  main is actually a function, as in the ANSI C standard,
5554    --  defined to return the exit status. The three parameters
5555    --  are the argument count, argument values and environment
5556    --  pointer.
5557
5558 @findex Main Program
5559    function main
5560      (argc : Integer;
5561       argv : System.Address;
5562       envp : System.Address)
5563       return Integer
5564    is
5565       --  The initialize routine performs low level system
5566       --  initialization using a standard library routine which
5567       --  sets up signal handling and performs any other
5568       --  required setup. The routine can be found in file
5569       --  a-init.c.
5570
5571 @findex __gnat_initialize
5572       procedure initialize;
5573       pragma Import (C, initialize, "__gnat_initialize");
5574
5575       --  The finalize routine performs low level system
5576       --  finalization using a standard library routine. The
5577       --  routine is found in file a-final.c and in the standard
5578       --  distribution is a dummy routine that does nothing, so
5579       --  really this is a hook for special user finalization.
5580
5581 @findex __gnat_finalize
5582       procedure finalize;
5583       pragma Import (C, finalize, "__gnat_finalize");
5584
5585       --  We get to the main program of the partition by using
5586       --  pragma Import because if we try to with the unit and
5587       --  call it Ada style, then not only do we waste time
5588       --  recompiling it, but also, we don't really know the right
5589       --  switches (e.g. identifier character set) to be used
5590       --  to compile it.
5591
5592       procedure Ada_Main_Program;
5593       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
5594
5595    --  Start of processing for main
5596
5597    begin
5598       --  Save global variables
5599
5600       gnat_argc := argc;
5601       gnat_argv := argv;
5602       gnat_envp := envp;
5603
5604       --  Call low level system initialization
5605
5606       Initialize;
5607
5608       --  Call our generated Ada initialization routine
5609
5610       adainit;
5611
5612       --  This is the point at which we want the debugger to get
5613       --  control
5614
5615       Break_Start;
5616
5617       --  Now we call the main program of the partition
5618
5619       Ada_Main_Program;
5620
5621       --  Perform Ada finalization
5622
5623       adafinal;
5624
5625       --  Perform low level system finalization
5626
5627       Finalize;
5628
5629       --  Return the proper exit status
5630       return (gnat_exit_status);
5631    end;
5632
5633 --  This section is entirely comments, so it has no effect on the
5634 --  compilation of the Ada_Main package. It provides the list of
5635 --  object files and linker options, as well as some standard
5636 --  libraries needed for the link. The gnatlink utility parses
5637 --  this b~hello.adb file to read these comment lines to generate
5638 --  the appropriate command line arguments for the call to the
5639 --  system linker. The BEGIN/END lines are used for sentinels for
5640 --  this parsing operation.
5641
5642 --  The exact file names will of course depend on the environment,
5643 --  host/target and location of files on the host system.
5644
5645 @findex Object file list
5646 -- BEGIN Object file/option list
5647    --   ./hello.o
5648    --   -L./
5649    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
5650    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
5651 -- END Object file/option list
5652
5653 end ada_main;
5654
5655 @end smallexample
5656
5657 @noindent
5658 The Ada code in the above example is exactly what is generated by the
5659 binder. We have added comments to more clearly indicate the function
5660 of each part of the generated @code{Ada_Main} package.
5661
5662 The code is standard Ada in all respects, and can be processed by any
5663 tools that handle Ada. In particular, it is possible to use the debugger
5664 in Ada mode to debug the generated Ada_Main package. For example, suppose
5665 that for reasons that you do not understand, your program is blowing up
5666 during elaboration of the body of @code{Ada.Text_IO}. To chase this bug
5667 down, you can place a breakpoint on the call:
5668
5669 @smallexample
5670 Ada.Text_Io'Elab_Body;
5671 @end smallexample
5672
5673 @noindent
5674 and trace the elaboration routine for this package to find out where
5675 the problem might be (more usually of course you would be debugging
5676 elaboration code in your own application).
5677
5678 @node Generating the Binder Program in C
5679 @section Generating the Binder Program in C
5680 @noindent
5681 In most normal usage, the default mode of @code{gnatbind} which is to
5682 generate the main package in Ada, as described in the previous section.
5683 In particular, this means that any Ada programmer can read and understand
5684 the generated main program. It can also be debugged just like any other
5685 Ada code provided the @code{-g} switch is used for @code{gnatbind}
5686 and @code{gnatlink}.
5687
5688 However for some purposes it may be convenient to generate the main
5689 program in C rather than Ada. This may for example be helpful when you
5690 are generating a mixed language program with the main program in C. The
5691 GNAT compiler itself is an example. The use of the @code{-C} switch
5692 for both @code{gnatbind} and @code{gnatlink} will cause the program to
5693 be generated in C (and compiled using the gnu C compiler). The
5694 following shows the C code generated for the same "Hello World"
5695 program:
5696
5697 @smallexample
5698
5699 #ifdef __STDC__
5700 #define PARAMS(paramlist) paramlist
5701 #else
5702 #define PARAMS(paramlist) ()
5703 #endif
5704
5705 extern void __gnat_set_globals
5706  PARAMS ((int, int, int, int, int, int,
5707           void (*) PARAMS ((void)), int, int));
5708 extern void adafinal PARAMS ((void));
5709 extern void adainit PARAMS ((void));
5710 extern void system__standard_library__adafinal PARAMS ((void));
5711 extern int main PARAMS ((int, char **, char **));
5712 extern void exit PARAMS ((int));
5713 extern void __gnat_break_start PARAMS ((void));
5714 extern void _ada_hello PARAMS ((void));
5715 extern void __gnat_initialize PARAMS ((void));
5716 extern void __gnat_finalize PARAMS ((void));
5717
5718 extern void ada__exceptions___elabs PARAMS ((void));
5719 extern void system__exceptions___elabs PARAMS ((void));
5720 extern void interfaces__c_streams___elabs PARAMS ((void));
5721 extern void system__exception_table___elabb PARAMS ((void));
5722 extern void ada__io_exceptions___elabs PARAMS ((void));
5723 extern void system__stack_checking___elabs PARAMS ((void));
5724 extern void system__soft_links___elabb PARAMS ((void));
5725 extern void system__secondary_stack___elabb PARAMS ((void));
5726 extern void ada__tags___elabs PARAMS ((void));
5727 extern void ada__tags___elabb PARAMS ((void));
5728 extern void ada__streams___elabs PARAMS ((void));
5729 extern void system__finalization_root___elabs PARAMS ((void));
5730 extern void ada__exceptions___elabb PARAMS ((void));
5731 extern void system__finalization_implementation___elabs PARAMS ((void));
5732 extern void system__finalization_implementation___elabb PARAMS ((void));
5733 extern void ada__finalization___elabs PARAMS ((void));
5734 extern void ada__finalization__list_controller___elabs PARAMS ((void));
5735 extern void system__file_control_block___elabs PARAMS ((void));
5736 extern void system__file_io___elabb PARAMS ((void));
5737 extern void ada__text_io___elabs PARAMS ((void));
5738 extern void ada__text_io___elabb PARAMS ((void));
5739
5740 extern int __gnat_inside_elab_final_code;
5741
5742 extern int gnat_argc;
5743 extern char **gnat_argv;
5744 extern char **gnat_envp;
5745 extern int gnat_exit_status;
5746
5747 char __gnat_version[] = "GNAT Version: 3.15w (20010315)";
5748 void adafinal () @{
5749    system__standard_library__adafinal ();
5750 @}
5751
5752 void adainit ()
5753 @{
5754    extern char ada__exceptions_E;
5755    extern char system__exceptions_E;
5756    extern char interfaces__c_streams_E;
5757    extern char system__exception_table_E;
5758    extern char ada__io_exceptions_E;
5759    extern char system__secondary_stack_E;
5760    extern char system__stack_checking_E;
5761    extern char system__soft_links_E;
5762    extern char ada__tags_E;
5763    extern char ada__streams_E;
5764    extern char system__finalization_root_E;
5765    extern char system__finalization_implementation_E;
5766    extern char ada__finalization_E;
5767    extern char ada__finalization__list_controller_E;
5768    extern char system__file_control_block_E;
5769    extern char system__file_io_E;
5770    extern char ada__text_io_E;
5771
5772    extern void *__gnat_hello__SDP;
5773    extern void *__gnat_ada__text_io__SDP;
5774    extern void *__gnat_ada__exceptions__SDP;
5775    extern void *__gnat_gnat__heap_sort_a__SDP;
5776    extern void *__gnat_system__exception_table__SDP;
5777    extern void *__gnat_system__machine_state_operations__SDP;
5778    extern void *__gnat_system__secondary_stack__SDP;
5779    extern void *__gnat_system__parameters__SDP;
5780    extern void *__gnat_system__soft_links__SDP;
5781    extern void *__gnat_system__stack_checking__SDP;
5782    extern void *__gnat_system__traceback__SDP;
5783    extern void *__gnat_ada__streams__SDP;
5784    extern void *__gnat_ada__tags__SDP;
5785    extern void *__gnat_system__string_ops__SDP;
5786    extern void *__gnat_interfaces__c_streams__SDP;
5787    extern void *__gnat_system__file_io__SDP;
5788    extern void *__gnat_ada__finalization__SDP;
5789    extern void *__gnat_system__finalization_root__SDP;
5790    extern void *__gnat_system__finalization_implementation__SDP;
5791    extern void *__gnat_system__string_ops_concat_3__SDP;
5792    extern void *__gnat_system__stream_attributes__SDP;
5793    extern void *__gnat_system__file_control_block__SDP;
5794    extern void *__gnat_ada__finalization__list_controller__SDP;
5795
5796    void **st[23] = @{
5797      &__gnat_hello__SDP,
5798      &__gnat_ada__text_io__SDP,
5799      &__gnat_ada__exceptions__SDP,
5800      &__gnat_gnat__heap_sort_a__SDP,
5801      &__gnat_system__exception_table__SDP,
5802      &__gnat_system__machine_state_operations__SDP,
5803      &__gnat_system__secondary_stack__SDP,
5804      &__gnat_system__parameters__SDP,
5805      &__gnat_system__soft_links__SDP,
5806      &__gnat_system__stack_checking__SDP,
5807      &__gnat_system__traceback__SDP,
5808      &__gnat_ada__streams__SDP,
5809      &__gnat_ada__tags__SDP,
5810      &__gnat_system__string_ops__SDP,
5811      &__gnat_interfaces__c_streams__SDP,
5812      &__gnat_system__file_io__SDP,
5813      &__gnat_ada__finalization__SDP,
5814      &__gnat_system__finalization_root__SDP,
5815      &__gnat_system__finalization_implementation__SDP,
5816      &__gnat_system__string_ops_concat_3__SDP,
5817      &__gnat_system__stream_attributes__SDP,
5818      &__gnat_system__file_control_block__SDP,
5819      &__gnat_ada__finalization__list_controller__SDP@};
5820
5821    extern void ada__exceptions___elabs ();
5822    extern void system__exceptions___elabs ();
5823    extern void interfaces__c_streams___elabs ();
5824    extern void system__exception_table___elabb ();
5825    extern void ada__io_exceptions___elabs ();
5826    extern void system__stack_checking___elabs ();
5827    extern void system__soft_links___elabb ();
5828    extern void system__secondary_stack___elabb ();
5829    extern void ada__tags___elabs ();
5830    extern void ada__tags___elabb ();
5831    extern void ada__streams___elabs ();
5832    extern void system__finalization_root___elabs ();
5833    extern void ada__exceptions___elabb ();
5834    extern void system__finalization_implementation___elabs ();
5835    extern void system__finalization_implementation___elabb ();
5836    extern void ada__finalization___elabs ();
5837    extern void ada__finalization__list_controller___elabs ();
5838    extern void system__file_control_block___elabs ();
5839    extern void system__file_io___elabb ();
5840    extern void ada__text_io___elabs ();
5841    extern void ada__text_io___elabb ();
5842
5843    void (*ea[23]) () = @{
5844      adainit,
5845      system__standard_library__adafinal,
5846      ada__exceptions___elabs,
5847      system__exceptions___elabs,
5848      interfaces__c_streams___elabs,
5849      system__exception_table___elabb,
5850      ada__io_exceptions___elabs,
5851      system__stack_checking___elabs,
5852      system__soft_links___elabb,
5853      system__secondary_stack___elabb,
5854      ada__tags___elabs,
5855      ada__tags___elabb,
5856      ada__streams___elabs,
5857      system__finalization_root___elabs,
5858      ada__exceptions___elabb,
5859      system__finalization_implementation___elabs,
5860      system__finalization_implementation___elabb,
5861      ada__finalization___elabs,
5862      ada__finalization__list_controller___elabs,
5863      system__file_control_block___elabs,
5864      system__file_io___elabb,
5865      ada__text_io___elabs,
5866      ada__text_io___elabb@};
5867
5868    __gnat_SDP_Table_Build (&st, 23, ea, 23);
5869    __gnat_set_globals (
5870       -1,      /* Main_Priority              */
5871       -1,      /* Time_Slice_Value           */
5872       'b',     /* WC_Encoding                */
5873       ' ',     /* Locking_Policy             */
5874       ' ',     /* Queuing_Policy             */
5875       ' ',     /* Tasking_Dispatching_Policy */
5876       0,       /* Finalization routine address, not used anymore */
5877       0,       /* Unreserve_All_Interrupts */
5878       0);      /* Exception_Tracebacks */
5879
5880    __gnat_inside_elab_final_code = 1;
5881
5882    if (ada__exceptions_E == 0) @{
5883       ada__exceptions___elabs ();
5884    @}
5885    if (system__exceptions_E == 0) @{
5886       system__exceptions___elabs ();
5887       system__exceptions_E++;
5888    @}
5889    if (interfaces__c_streams_E == 0) @{
5890       interfaces__c_streams___elabs ();
5891    @}
5892    interfaces__c_streams_E = 1;
5893    if (system__exception_table_E == 0) @{
5894       system__exception_table___elabb ();
5895       system__exception_table_E++;
5896    @}
5897    if (ada__io_exceptions_E == 0) @{
5898       ada__io_exceptions___elabs ();
5899       ada__io_exceptions_E++;
5900    @}
5901    if (system__stack_checking_E == 0) @{
5902       system__stack_checking___elabs ();
5903    @}
5904    if (system__soft_links_E == 0) @{
5905       system__soft_links___elabb ();
5906       system__soft_links_E++;
5907    @}
5908    system__stack_checking_E = 1;
5909    if (system__secondary_stack_E == 0) @{
5910       system__secondary_stack___elabb ();
5911       system__secondary_stack_E++;
5912    @}
5913    if (ada__tags_E == 0) @{
5914       ada__tags___elabs ();
5915    @}
5916    if (ada__tags_E == 0) @{
5917       ada__tags___elabb ();
5918       ada__tags_E++;
5919    @}
5920    if (ada__streams_E == 0) @{
5921       ada__streams___elabs ();
5922       ada__streams_E++;
5923    @}
5924    if (system__finalization_root_E == 0) @{
5925       system__finalization_root___elabs ();
5926    @}
5927    system__finalization_root_E = 1;
5928    if (ada__exceptions_E == 0) @{
5929       ada__exceptions___elabb ();
5930       ada__exceptions_E++;
5931    @}
5932    if (system__finalization_implementation_E == 0) @{
5933       system__finalization_implementation___elabs ();
5934    @}
5935    if (system__finalization_implementation_E == 0) @{
5936       system__finalization_implementation___elabb ();
5937       system__finalization_implementation_E++;
5938    @}
5939    if (ada__finalization_E == 0) @{
5940       ada__finalization___elabs ();
5941    @}
5942    ada__finalization_E = 1;
5943    if (ada__finalization__list_controller_E == 0) @{
5944       ada__finalization__list_controller___elabs ();
5945    @}
5946    ada__finalization__list_controller_E = 1;
5947    if (system__file_control_block_E == 0) @{
5948       system__file_control_block___elabs ();
5949       system__file_control_block_E++;
5950    @}
5951    if (system__file_io_E == 0) @{
5952       system__file_io___elabb ();
5953       system__file_io_E++;
5954    @}
5955    if (ada__text_io_E == 0) @{
5956       ada__text_io___elabs ();
5957    @}
5958    if (ada__text_io_E == 0) @{
5959       ada__text_io___elabb ();
5960       ada__text_io_E++;
5961    @}
5962
5963    __gnat_inside_elab_final_code = 0;
5964 @}
5965 int main (argc, argv, envp)
5966     int argc;
5967     char **argv;
5968     char **envp;
5969 @{
5970    gnat_argc = argc;
5971    gnat_argv = argv;
5972    gnat_envp = envp;
5973
5974    __gnat_initialize ();
5975    adainit ();
5976    __gnat_break_start ();
5977
5978    _ada_hello ();
5979
5980    system__standard_library__adafinal ();
5981    __gnat_finalize ();
5982    exit (gnat_exit_status);
5983 @}
5984 unsigned helloB = 0x7880BEB3;
5985 unsigned system__standard_libraryB = 0x0D24CBD0;
5986 unsigned system__standard_libraryS = 0x3283DBEB;
5987 unsigned adaS = 0x2359F9ED;
5988 unsigned ada__text_ioB = 0x47C85FC4;
5989 unsigned ada__text_ioS = 0x496FE45C;
5990 unsigned ada__exceptionsB = 0x74F50187;
5991 unsigned ada__exceptionsS = 0x6736945B;
5992 unsigned gnatS = 0x156A40CF;
5993 unsigned gnat__heap_sort_aB = 0x033DABE0;
5994 unsigned gnat__heap_sort_aS = 0x6AB38FEA;
5995 unsigned systemS = 0x0331C6FE;
5996 unsigned system__exceptionsS = 0x20C9ECA4;
5997 unsigned system__exception_tableB = 0x68A22947;
5998 unsigned system__exception_tableS = 0x394BADD5;
5999 unsigned gnat__htableB = 0x08258E1B;
6000 unsigned gnat__htableS = 0x367D5222;
6001 unsigned system__machine_state_operationsB = 0x4F3B7492;
6002 unsigned system__machine_state_operationsS = 0x182F5CF4;
6003 unsigned system__storage_elementsB = 0x2F1EB794;
6004 unsigned system__storage_elementsS = 0x102C83C7;
6005 unsigned system__secondary_stackB = 0x1574B6E9;
6006 unsigned system__secondary_stackS = 0x708E260A;
6007 unsigned system__parametersB = 0x56D770CD;
6008 unsigned system__parametersS = 0x237E39BE;
6009 unsigned system__soft_linksB = 0x08AB6B2C;
6010 unsigned system__soft_linksS = 0x1E2491F3;
6011 unsigned system__stack_checkingB = 0x476457A0;
6012 unsigned system__stack_checkingS = 0x5299FCED;
6013 unsigned system__tracebackB = 0x2971EBDE;
6014 unsigned system__tracebackS = 0x2E9C3122;
6015 unsigned ada__streamsS = 0x7C25DE96;
6016 unsigned ada__tagsB = 0x39ADFFA2;
6017 unsigned ada__tagsS = 0x769A0464;
6018 unsigned system__string_opsB = 0x5EB646AB;
6019 unsigned system__string_opsS = 0x63CED018;
6020 unsigned interfacesS = 0x0357E00A;
6021 unsigned interfaces__c_streamsB = 0x3784FB72;
6022 unsigned interfaces__c_streamsS = 0x2E723019;
6023 unsigned system__file_ioB = 0x623358EA;
6024 unsigned system__file_ioS = 0x31F873E6;
6025 unsigned ada__finalizationB = 0x6843F68A;
6026 unsigned ada__finalizationS = 0x63305874;
6027 unsigned system__finalization_rootB = 0x31E56CE1;
6028 unsigned system__finalization_rootS = 0x23169EF3;
6029 unsigned system__finalization_implementationB = 0x6CCBA70E;
6030 unsigned system__finalization_implementationS = 0x604AA587;
6031 unsigned system__string_ops_concat_3B = 0x572E3F58;
6032 unsigned system__string_ops_concat_3S = 0x01F57876;
6033 unsigned system__stream_attributesB = 0x1D4F93E8;
6034 unsigned system__stream_attributesS = 0x30B2EC3D;
6035 unsigned ada__io_exceptionsS = 0x34054F96;
6036 unsigned system__unsigned_typesS = 0x7B9E7FE3;
6037 unsigned system__file_control_blockS = 0x2FF876A8;
6038 unsigned ada__finalization__list_controllerB = 0x5760634A;
6039 unsigned ada__finalization__list_controllerS = 0x5D851835;
6040
6041 /* BEGIN ELABORATION ORDER
6042 ada (spec)
6043 gnat (spec)
6044 gnat.heap_sort_a (spec)
6045 gnat.htable (spec)
6046 gnat.htable (body)
6047 interfaces (spec)
6048 system (spec)
6049 system.parameters (spec)
6050 system.standard_library (spec)
6051 ada.exceptions (spec)
6052 system.exceptions (spec)
6053 system.parameters (body)
6054 gnat.heap_sort_a (body)
6055 interfaces.c_streams (spec)
6056 interfaces.c_streams (body)
6057 system.exception_table (spec)
6058 system.exception_table (body)
6059 ada.io_exceptions (spec)
6060 system.storage_elements (spec)
6061 system.storage_elements (body)
6062 system.machine_state_operations (spec)
6063 system.machine_state_operations (body)
6064 system.secondary_stack (spec)
6065 system.stack_checking (spec)
6066 system.soft_links (spec)
6067 system.soft_links (body)
6068 system.stack_checking (body)
6069 system.secondary_stack (body)
6070 system.standard_library (body)
6071 system.string_ops (spec)
6072 system.string_ops (body)
6073 ada.tags (spec)
6074 ada.tags (body)
6075 ada.streams (spec)
6076 system.finalization_root (spec)
6077 system.finalization_root (body)
6078 system.string_ops_concat_3 (spec)
6079 system.string_ops_concat_3 (body)
6080 system.traceback (spec)
6081 system.traceback (body)
6082 ada.exceptions (body)
6083 system.unsigned_types (spec)
6084 system.stream_attributes (spec)
6085 system.stream_attributes (body)
6086 system.finalization_implementation (spec)
6087 system.finalization_implementation (body)
6088 ada.finalization (spec)
6089 ada.finalization (body)
6090 ada.finalization.list_controller (spec)
6091 ada.finalization.list_controller (body)
6092 system.file_control_block (spec)
6093 system.file_io (spec)
6094 system.file_io (body)
6095 ada.text_io (spec)
6096 ada.text_io (body)
6097 hello (body)
6098    END ELABORATION ORDER */
6099
6100 /* BEGIN Object file/option list
6101 ./hello.o
6102 -L./
6103 -L/usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/
6104 /usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/libgnat.a
6105 -lexc
6106    END Object file/option list */
6107
6108 @end smallexample
6109
6110 @noindent
6111 Here again, the C code is exactly what is generated by the binder. The
6112 functions of the various parts of this code correspond in an obvious
6113 manner with the commented Ada code shown in the example in the previous
6114 section.
6115
6116 @node Consistency-Checking Modes
6117 @section Consistency-Checking Modes
6118
6119 @noindent
6120 As described in the previous section, by default @code{gnatbind} checks
6121 that object files are consistent with one another and are consistent
6122 with any source files it can locate. The following switches control binder
6123 access to sources.
6124
6125 @table @code
6126 @item -s
6127 @cindex @code{-s} (@code{gnatbind})
6128 Require source files to be present. In this mode, the binder must be
6129 able to locate all source files that are referenced, in order to check
6130 their consistency. In normal mode, if a source file cannot be located it
6131 is simply ignored. If you specify this switch, a missing source
6132 file is an error.
6133
6134 @item -x
6135 @cindex @code{-x} (@code{gnatbind})
6136 Exclude source files. In this mode, the binder only checks that ALI
6137 files are consistent with one another. Source files are not accessed.
6138 The binder runs faster in this mode, and there is still a guarantee that
6139 the resulting program is self-consistent.
6140 If a source file has been edited since it was last compiled, and you
6141 specify this switch, the binder will not detect that the object
6142 file is out of date with respect to the source file. Note that this is the
6143 mode that is automatically used by @code{gnatmake} because in this
6144 case the checking against sources has already been performed by
6145 @code{gnatmake} in the course of compilation (i.e. before binding).
6146
6147 @end table
6148
6149 @node Binder Error Message Control
6150 @section Binder Error Message Control
6151
6152 @noindent
6153 The following switches provide control over the generation of error
6154 messages from the binder:
6155
6156 @table @code
6157 @item -v
6158 @cindex @code{-v} (@code{gnatbind})
6159 Verbose mode. In the normal mode, brief error messages are generated to
6160 @file{stderr}. If this switch is present, a header is written
6161 to @file{stdout} and any error messages are directed to @file{stdout}.
6162 All that is written to @file{stderr} is a brief summary message.
6163
6164 @item -b
6165 @cindex @code{-b} (@code{gnatbind})
6166 Generate brief error messages to @file{stderr} even if verbose mode is
6167 specified. This is relevant only when used with the
6168 @code{-v} switch.
6169
6170 @item -m@var{n}
6171 @cindex @code{-m} (@code{gnatbind})
6172 Limits the number of error messages to @var{n}, a decimal integer in the
6173 range 1-999. The binder terminates immediately if this limit is reached.
6174
6175 @item -M@var{xxx}
6176 @cindex @code{-M} (@code{gnatbind})
6177 Renames the generated main program from @code{main} to @code{xxx}.
6178 This is useful in the case of some cross-building environments, where
6179 the actual main program is separate from the one generated
6180 by @code{gnatbind}.
6181
6182 @item -ws
6183 @cindex @code{-ws} (@code{gnatbind})
6184 @cindex Warnings
6185 Suppress all warning messages.
6186
6187 @item -we
6188 @cindex @code{-we} (@code{gnatbind})
6189 Treat any warning messages as fatal errors.
6190
6191
6192 @item -t
6193 @cindex @code{-t} (@code{gnatbind})
6194 @cindex Time stamp checks, in binder
6195 @cindex Binder consistency checks
6196 @cindex Consistency checks, in binder
6197 The binder performs a number of consistency checks including:
6198
6199 @itemize @bullet
6200 @item
6201 Check that time stamps of a given source unit are consistent
6202 @item
6203 Check that checksums of a given source unit are consistent
6204 @item
6205 Check that consistent versions of @code{GNAT} were used for compilation
6206 @item
6207 Check consistency of configuration pragmas as required
6208 @end itemize
6209
6210 @noindent
6211 Normally failure of such checks, in accordance with the consistency
6212 requirements of the Ada Reference Manual, causes error messages to be
6213 generated which abort the binder and prevent the output of a binder
6214 file and subsequent link to obtain an executable.
6215
6216 The @code{-t} switch converts these error messages
6217 into warnings, so that
6218 binding and linking can continue to completion even in the presence of such
6219 errors. The result may be a failed link (due to missing symbols), or a
6220 non-functional executable which has undefined semantics.
6221 @emph{This means that
6222 @code{-t} should be used only in unusual situations,
6223 with extreme care.}
6224 @end table
6225
6226 @node Elaboration Control
6227 @section Elaboration Control
6228
6229 @noindent
6230 The following switches provide additional control over the elaboration
6231 order. For full details see @xref{Elaboration Order Handling in GNAT}.
6232
6233 @table @code
6234 @item -p
6235 @cindex @code{-h} (@code{gnatbind})
6236 Normally the binder attempts to choose an elaboration order that is
6237 likely to minimize the likelihood of an elaboration order error resulting
6238 in raising a @code{Program_Error} exception. This switch reverses the
6239 action of the binder, and requests that it deliberately choose an order
6240 that is likely to maximize the likelihood of an elaboration error.
6241 This is useful in ensuring portability and avoiding dependence on
6242 accidental fortuitous elaboration ordering.
6243
6244 Normally it only makes sense to use the @code{-p} switch if dynamic
6245 elaboration checking is used (@option{-gnatE} switch used for compilation).
6246 This is because in the default static elaboration mode, all necessary
6247 @code{Elaborate_All} pragmas are implicitly inserted. These implicit
6248 pragmas are still respected by the binder in @code{-p} mode, so a
6249 safe elaboration order is assured.
6250 @end table
6251
6252 @node Output Control
6253 @section Output Control
6254
6255 @noindent
6256 The following switches allow additional control over the output
6257 generated by the binder.
6258
6259 @table @code
6260
6261 @item -A
6262 @cindex @code{-A} (@code{gnatbind})
6263 Generate binder program in Ada (default). The binder program is named
6264 @file{b~@var{mainprog}.adb} by default. This can be changed with
6265 @code{-o} @code{gnatbind} option.
6266
6267 @item -c
6268 @cindex @code{-c} (@code{gnatbind})
6269 Check only. Do not generate the binder output file. In this mode the
6270 binder performs all error checks but does not generate an output file.
6271
6272 @item -C
6273 @cindex @code{-C} (@code{gnatbind})
6274 Generate binder program in C. The binder program is named
6275 @file{b_@var{mainprog}.c}. This can be changed with @code{-o} @code{gnatbind}
6276 option.
6277
6278 @item -e
6279 @cindex @code{-e} (@code{gnatbind})
6280 Output complete list of elaboration-order dependencies, showing the
6281 reason for each dependency. This output can be rather extensive but may
6282 be useful in diagnosing problems with elaboration order. The output is
6283 written to @file{stdout}.
6284
6285 @item -h
6286 @cindex @code{-h} (@code{gnatbind})
6287 Output usage information. The output is written to @file{stdout}.
6288
6289 @item -K
6290 @cindex @code{-K} (@code{gnatbind})
6291 Output linker options to @file{stdout}. Includes library search paths,
6292 contents of pragmas Ident and Linker_Options, and libraries added
6293 by @code{gnatbind}.
6294
6295 @item -l
6296 @cindex @code{-l} (@code{gnatbind})
6297 Output chosen elaboration order. The output is written to @file{stdout}.
6298
6299 @item -O
6300 @cindex @code{-O} (@code{gnatbind})
6301 Output full names of all the object files that must be linked to provide
6302 the Ada component of the program. The output is written to @file{stdout}.
6303 This list includes the files explicitly supplied and referenced by the user
6304 as well as implicitly referenced run-time unit files. The latter are
6305 omitted if the corresponding units reside in shared libraries. The
6306 directory names for the run-time units depend on the system configuration.
6307
6308 @item -o @var{file}
6309 @cindex @code{-o} (@code{gnatbind})
6310 Set name of output file to @var{file} instead of the normal
6311 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
6312 binder generated body filename. In C mode you would normally give
6313 @var{file} an extension of @file{.c} because it will be a C source program.
6314 Note that if this option is used, then linking must be done manually.
6315 It is not possible to use gnatlink in this case, since it cannot locate
6316 the binder file.
6317
6318 @item -r
6319 @cindex @code{-r} (@code{gnatbind})
6320 Generate list of @code{pragma Rerstrictions} that could be applied to
6321 the current unit. This is useful for code audit purposes, and also may
6322 be used to improve code generation in some cases.
6323
6324 @end table
6325
6326 @node Binding with Non-Ada Main Programs
6327 @section Binding with Non-Ada Main Programs
6328
6329 @noindent
6330 In our description so far we have assumed that the main
6331 program is in Ada, and that the task of the binder is to generate a
6332 corresponding function @code{main} that invokes this Ada main
6333 program. GNAT also supports the building of executable programs where
6334 the main program is not in Ada, but some of the called routines are
6335 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
6336 The following switch is used in this situation:
6337
6338 @table @code
6339 @item -n
6340 @cindex @code{-n} (@code{gnatbind})
6341 No main program. The main program is not in Ada.
6342 @end table
6343
6344 @noindent
6345 In this case, most of the functions of the binder are still required,
6346 but instead of generating a main program, the binder generates a file
6347 containing the following callable routines:
6348
6349 @table @code
6350 @item adainit
6351 @findex adainit
6352 You must call this routine to initialize the Ada part of the program by
6353 calling the necessary elaboration routines. A call to @code{adainit} is
6354 required before the first call to an Ada subprogram.
6355
6356 Note that it is assumed that the basic execution environment must be setup
6357 to be appropriate for Ada execution at the point where the first Ada
6358 subprogram is called. In particular, if the Ada code will do any
6359 floating-point operations, then the FPU must be setup in an appropriate
6360 manner. For the case of the x86, for example, full precision mode is
6361 required. The procedure GNAT.Float_Control.Reset may be used to ensure
6362 that the FPU is in the right state.
6363
6364 @item adafinal
6365 @findex adafinal
6366 You must call this routine to perform any library-level finalization
6367 required by the Ada subprograms. A call to @code{adafinal} is required
6368 after the last call to an Ada subprogram, and before the program
6369 terminates.
6370 @end table
6371
6372 @noindent
6373 If the @code{-n} switch
6374 @cindex Binder, multiple input files
6375 is given, more than one ALI file may appear on
6376 the command line for @code{gnatbind}. The normal @dfn{closure}
6377 calculation is performed for each of the specified units. Calculating
6378 the closure means finding out the set of units involved by tracing
6379 @code{with} references. The reason it is necessary to be able to
6380 specify more than one ALI file is that a given program may invoke two or
6381 more quite separate groups of Ada units.
6382
6383 The binder takes the name of its output file from the last specified ALI
6384 file, unless overridden by the use of the @code{-o file}.
6385 The output is an Ada unit in source form that can
6386 be compiled with GNAT unless the -C switch is used in which case the
6387 output is a C source file, which must be compiled using the C compiler.
6388 This compilation occurs automatically as part of the @code{gnatlink}
6389 processing.
6390
6391 Currently the GNAT run time requires a FPU using 80 bits mode
6392 precision. Under targets where this is not the default it is required to
6393 call GNAT.Float_Control.Reset before using floating point numbers (this
6394 include float computation, float input and output) in the Ada code. A
6395 side effect is that this could be the wrong mode for the foreign code
6396 where floating point computation could be broken after this call.
6397
6398 @node Binding Programs with No Main Subprogram
6399 @section Binding Programs with No Main Subprogram
6400
6401 @noindent
6402 It is possible to have an Ada program which does not have a main
6403 subprogram. This program will call the elaboration routines of all the
6404 packages, then the finalization routines.
6405
6406 The following switch is used to bind programs organized in this manner:
6407
6408 @table @code
6409 @item -z
6410 @cindex @code{-z} (@code{gnatbind})
6411 Normally the binder checks that the unit name given on the command line
6412 corresponds to a suitable main subprogram. When this switch is used,
6413 a list of ALI files can be given, and the execution of the program
6414 consists of elaboration of these units in an appropriate order.
6415 @end table
6416
6417 @node Summary of Binder Switches
6418 @section Summary of Binder Switches
6419
6420 @noindent
6421 The following are the switches available with @code{gnatbind}:
6422
6423 @table @code
6424 @item -aO
6425 Specify directory to be searched for ALI files.
6426
6427 @item -aI
6428 Specify directory to be searched for source file.
6429
6430 @item -A
6431 Generate binder program in Ada (default)
6432
6433 @item -b
6434 Generate brief messages to @file{stderr} even if verbose mode set.
6435
6436 @item -c
6437 Check only, no generation of binder output file.
6438
6439 @item -C
6440 Generate binder program in C
6441
6442 @item -e
6443 Output complete list of elaboration-order dependencies.
6444
6445 @item -E
6446 Store tracebacks in exception occurrences when the target supports it.
6447 This is the default with the zero cost exception mechanism.
6448 This option is currently supported on the following targets:
6449 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6450 See also the packages @code{GNAT.Traceback} and
6451 @code{GNAT.Traceback.Symbolic} for more information.
6452 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
6453 @code{gcc} option.
6454
6455 @item -h
6456 Output usage (help) information
6457
6458 @item -I
6459 Specify directory to be searched for source and ALI files.
6460
6461 @item -I-
6462 Do not look for sources in the current directory where @code{gnatbind} was
6463 invoked, and do not look for ALI files in the directory containing the
6464 ALI file named in the @code{gnatbind} command line.
6465
6466 @item -l
6467 Output chosen elaboration order.
6468
6469 @item -Lxxx
6470 Binds the units for library building. In this case the adainit and
6471 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
6472 are renamed to xxxinit and xxxfinal. Implies -n.
6473 See @pxref{GNAT and Libraries} for more details.
6474
6475 @item -Mxyz
6476 Rename generated main program from main to xyz
6477
6478 @item -m@var{n}
6479 Limit number of detected errors to @var{n} (1-999).
6480 Furthermore, under Windows, the sources pointed to by the libraries path
6481 set in the registry are not searched for.
6482
6483 @item -n
6484 No main program.
6485
6486 @item -nostdinc
6487 Do not look for sources in the system default directory.
6488
6489 @item -nostdlib
6490 Do not look for library files in the system default directory.
6491
6492 @item --RTS=@var{rts-path}
6493 @cindex @code{--RTS} (@code{gnatbind})
6494 Specifies the default location of the runtime library. Same meaning as the
6495 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
6496
6497 @item -o @var{file}
6498 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
6499 Note that if this option is used, then linking must be done manually,
6500 gnatlink cannot be used.
6501
6502 @item -O
6503 Output object list.
6504
6505 @item -p
6506 Pessimistic (worst-case) elaboration order
6507
6508 @item -s
6509 Require all source files to be present.
6510
6511 @item -static
6512 Link against a static GNAT run time.
6513
6514 @item -shared
6515 Link against a shared GNAT run time when available.
6516
6517 @item -t
6518 Tolerate time stamp and other consistency errors
6519
6520 @item -T@var{n}
6521 Set the time slice value to n microseconds. A value of zero means no time
6522 slicing and also indicates to the tasking run time to match as close as
6523 possible to the annex D requirements of the RM.
6524
6525 @item -v
6526 Verbose mode. Write error messages, header, summary output to
6527 @file{stdout}.
6528
6529 @item -w@var{x}
6530 Warning mode (@var{x}=s/e for suppress/treat as error)
6531
6532
6533 @item -x
6534 Exclude source files (check object consistency only).
6535
6536
6537 @item -z
6538 No main subprogram.
6539
6540 @end table
6541
6542 You may obtain this listing by running the program @code{gnatbind} with
6543 no arguments.
6544
6545 @node Command-Line Access
6546 @section Command-Line Access
6547
6548 @noindent
6549 The package @code{Ada.Command_Line} provides access to the command-line
6550 arguments and program name. In order for this interface to operate
6551 correctly, the two variables
6552
6553 @smallexample
6554 @group
6555 @cartouche
6556 int gnat_argc;
6557 char **gnat_argv;
6558 @end cartouche
6559 @end group
6560 @end smallexample
6561
6562 @noindent
6563 @findex gnat_argv
6564 @findex gnat_argc
6565 are declared in one of the GNAT library routines. These variables must
6566 be set from the actual @code{argc} and @code{argv} values passed to the
6567 main program. With no @code{n} present, @code{gnatbind}
6568 generates the C main program to automatically set these variables.
6569 If the @code{n} switch is used, there is no automatic way to
6570 set these variables. If they are not set, the procedures in
6571 @code{Ada.Command_Line} will not be available, and any attempt to use
6572 them will raise @code{Constraint_Error}. If command line access is
6573 required, your main program must set @code{gnat_argc} and
6574 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
6575 it.
6576
6577 @node Search Paths for gnatbind
6578 @section Search Paths for @code{gnatbind}
6579
6580 @noindent
6581 The binder takes the name of an ALI file as its argument and needs to
6582 locate source files as well as other ALI files to verify object consistency.
6583
6584 For source files, it follows exactly the same search rules as @code{gcc}
6585 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
6586 directories searched are:
6587
6588 @enumerate
6589 @item
6590 The directory containing the ALI file named in the command line, unless
6591 the switch @code{-I-} is specified.
6592
6593 @item
6594 All directories specified by @code{-I}
6595 switches on the @code{gnatbind}
6596 command line, in the order given.
6597
6598 @item
6599 @findex ADA_OBJECTS_PATH
6600 Each of the directories listed in the value of the
6601 @code{ADA_OBJECTS_PATH} environment variable.
6602 Construct this value
6603 exactly as the @code{PATH} environment variable: a list of directory
6604 names separated by colons (semicolons when working with the NT version
6605 of GNAT).
6606
6607 @item
6608 The content of the "ada_object_path" file which is part of the GNAT
6609 installation tree and is used to store standard libraries such as the
6610 GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is
6611 specified.
6612 @ref{Installing an Ada Library}
6613 @end enumerate
6614
6615 @noindent
6616 In the binder the switch @code{-I}
6617 is used to specify both source and
6618 library file paths. Use @code{-aI}
6619 instead if you want to specify
6620 source paths only, and @code{-aO}
6621 if you want to specify library paths
6622 only. This means that for the binder
6623 @code{-I}@var{dir} is equivalent to
6624 @code{-aI}@var{dir}
6625 @code{-aO}@var{dir}.
6626 The binder generates the bind file (a C language source file) in the
6627 current working directory.
6628
6629 @findex Ada
6630 @findex System
6631 @findex Interfaces
6632 @findex GNAT
6633 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6634 children make up the GNAT Run-Time Library, together with the package
6635 GNAT and its children, which contain a set of useful additional
6636 library functions provided by GNAT. The sources for these units are
6637 needed by the compiler and are kept together in one directory. The ALI
6638 files and object files generated by compiling the RTL are needed by the
6639 binder and the linker and are kept together in one directory, typically
6640 different from the directory containing the sources. In a normal
6641 installation, you need not specify these directory names when compiling
6642 or binding. Either the environment variables or the built-in defaults
6643 cause these files to be found.
6644
6645 Besides simplifying access to the RTL, a major use of search paths is
6646 in compiling sources from multiple directories. This can make
6647 development environments much more flexible.
6648
6649 @node Examples of gnatbind Usage
6650 @section Examples of @code{gnatbind} Usage
6651
6652 @noindent
6653 This section contains a number of examples of using the GNAT binding
6654 utility @code{gnatbind}.
6655
6656 @table @code
6657 @item gnatbind hello
6658 The main program @code{Hello} (source program in @file{hello.adb}) is
6659 bound using the standard switch settings. The generated main program is
6660 @file{b~hello.adb}. This is the normal, default use of the binder.
6661
6662 @item gnatbind hello -o mainprog.adb
6663 The main program @code{Hello} (source program in @file{hello.adb}) is
6664 bound using the standard switch settings. The generated main program is
6665 @file{mainprog.adb} with the associated spec in
6666 @file{mainprog.ads}. Note that you must specify the body here not the
6667 spec, in the case where the output is in Ada. Note that if this option
6668 is used, then linking must be done manually, since gnatlink will not
6669 be able to find the generated file.
6670
6671 @item gnatbind main -C -o mainprog.c -x
6672 The main program @code{Main} (source program in
6673 @file{main.adb}) is bound, excluding source files from the
6674 consistency checking, generating
6675 the file @file{mainprog.c}.
6676
6677 @item gnatbind -x main_program -C -o mainprog.c
6678 This command is exactly the same as the previous example. Switches may
6679 appear anywhere in the command line, and single letter switches may be
6680 combined into a single switch.
6681
6682 @item gnatbind -n math dbase -C -o ada-control.c
6683 The main program is in a language other than Ada, but calls to
6684 subprograms in packages @code{Math} and @code{Dbase} appear. This call
6685 to @code{gnatbind} generates the file @file{ada-control.c} containing
6686 the @code{adainit} and @code{adafinal} routines to be called before and
6687 after accessing the Ada units.
6688 @end table
6689
6690 @node Linking Using gnatlink
6691 @chapter Linking Using @code{gnatlink}
6692 @findex gnatlink
6693
6694 @noindent
6695 This chapter discusses @code{gnatlink}, a utility program used to link
6696 Ada programs and build an executable file. This is a simple program
6697 that invokes the Unix linker (via the @code{gcc}
6698 command) with a correct list of object files and library references.
6699 @code{gnatlink} automatically determines the list of files and
6700 references for the Ada part of a program. It uses the binder file
6701 generated by the binder to determine this list.
6702
6703 @menu
6704 * Running gnatlink::
6705 * Switches for gnatlink::
6706 * Setting Stack Size from gnatlink::
6707 * Setting Heap Size from gnatlink::
6708 @end menu
6709
6710 @node Running gnatlink
6711 @section Running @code{gnatlink}
6712
6713 @noindent
6714 The form of the @code{gnatlink} command is
6715
6716 @smallexample
6717 $ gnatlink [@var{switches}] @var{mainprog}[.ali] [@var{non-Ada objects}]
6718       [@var{linker options}]
6719 @end smallexample
6720
6721 @noindent
6722 @file{@var{mainprog}.ali} references the ALI file of the main program.
6723 The @file{.ali} extension of this file can be omitted. From this
6724 reference, @code{gnatlink} locates the corresponding binder file
6725 @file{b~@var{mainprog}.adb} and, using the information in this file along
6726 with the list of non-Ada objects and linker options, constructs a Unix
6727 linker command file to create the executable.
6728
6729 The arguments following @file{@var{mainprog}.ali} are passed to the
6730 linker uninterpreted. They typically include the names of object files
6731 for units written in other languages than Ada and any library references
6732 required to resolve references in any of these foreign language units,
6733 or in @code{pragma Import} statements in any Ada units.
6734
6735 @var{linker options} is an optional list of linker specific
6736 switches. The default linker called by gnatlink is @var{gcc} which in
6737 turn calls the appropriate system linker usually called
6738 @var{ld}. Standard options for the linker such as @code{-lmy_lib} or
6739 @code{-Ldir} can be added as is. For options that are not recognized by
6740 @var{gcc} as linker options, the @var{gcc} switches @code{-Xlinker} or
6741 @code{-Wl,} shall be used. Refer to the GCC documentation for
6742 details. Here is an example showing how to generate a linker map
6743 assuming that the underlying linker is GNU ld:
6744
6745 @smallexample
6746 $ gnatlink my_prog -Wl,-Map,MAPFILE
6747 @end smallexample
6748
6749 Using @var{linker options} it is possible to set the program stack and
6750 heap size. See @pxref{Setting Stack Size from gnatlink} and
6751 @pxref{Setting Heap Size from gnatlink}.
6752
6753 @code{gnatlink} determines the list of objects required by the Ada
6754 program and prepends them to the list of objects passed to the linker.
6755 @code{gnatlink} also gathers any arguments set by the use of
6756 @code{pragma Linker_Options} and adds them to the list of arguments
6757 presented to the linker.
6758
6759
6760 @node Switches for gnatlink
6761 @section Switches for @code{gnatlink}
6762
6763 @noindent
6764 The following switches are available with the @code{gnatlink} utility:
6765
6766 @table @code
6767
6768 @item -A
6769 @cindex @code{-A} (@code{gnatlink})
6770 The binder has generated code in Ada. This is the default.
6771
6772 @item -C
6773 @cindex @code{-C} (@code{gnatlink})
6774 If instead of generating a file in Ada, the binder has generated one in
6775 C, then the linker needs to know about it. Use this switch to signal
6776 to @code{gnatlink} that the binder has generated C code rather than
6777 Ada code.
6778
6779 @item -f
6780 @cindex Command line length
6781 @cindex @code{-f} (@code{gnatlink})
6782 On some targets, the command line length is limited, and @code{gnatlink}
6783 will generate a separate file for the linker if the list of object files
6784 is too long. The @code{-f} flag forces this file to be generated even if
6785 the limit is not exceeded. This is useful in some cases to deal with
6786 special situations where the command line length is exceeded.
6787
6788 @item -g
6789 @cindex Debugging information, including
6790 @cindex @code{-g} (@code{gnatlink})
6791 The option to include debugging information causes the Ada bind file (in
6792 other words, @file{b~@var{mainprog}.adb}) to be compiled with
6793 @code{-g}.
6794 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
6795 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
6796 Without @code{-g}, the binder removes these files by
6797 default. The same procedure apply if a C bind file was generated using
6798 @code{-C} @code{gnatbind} option, in this case the filenames are
6799 @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
6800
6801 @item -n
6802 @cindex @code{-n} (@code{gnatlink})
6803 Do not compile the file generated by the binder. This may be used when
6804 a link is rerun with different options, but there is no need to recompile
6805 the binder file.
6806
6807 @item -v
6808 @cindex @code{-v} (@code{gnatlink})
6809 Causes additional information to be output, including a full list of the
6810 included object files. This switch option is most useful when you want
6811 to see what set of object files are being used in the link step.
6812
6813 @item -v -v
6814 @cindex @code{-v -v} (@code{gnatlink})
6815 Very verbose mode. Requests that the compiler operate in verbose mode when
6816 it compiles the binder file, and that the system linker run in verbose mode.
6817
6818 @item -o @var{exec-name}
6819 @cindex @code{-o} (@code{gnatlink})
6820 @var{exec-name} specifies an alternate name for the generated
6821 executable program. If this switch is omitted, the executable has the same
6822 name as the main unit. For example, @code{gnatlink try.ali} creates
6823 an executable called @file{try}.
6824
6825 @item -b @var{target}
6826 @cindex @code{-b} (@code{gnatlink})
6827 Compile your program to run on @var{target}, which is the name of a
6828 system configuration. You must have a GNAT cross-compiler built if
6829 @var{target} is not the same as your host system.
6830
6831 @item -B@var{dir}
6832 @cindex @code{-B} (@code{gnatlink})
6833 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
6834 from @var{dir} instead of the default location. Only use this switch
6835 when multiple versions of the GNAT compiler are available. See the
6836 @code{gcc} manual page for further details. You would normally use the
6837 @code{-b} or @code{-V} switch instead.
6838
6839 @item --GCC=@var{compiler_name}
6840 @cindex @code{--GCC=compiler_name} (@code{gnatlink})
6841 Program used for compiling the binder file. The default is
6842 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
6843 @code{compiler_name} contains spaces or other separator characters. As
6844 an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
6845 @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
6846 inserted after your command name. Thus in the above example the compiler
6847 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
6848 If several @code{--GCC=compiler_name} are used, only the last
6849 @var{compiler_name} is taken into account. However, all the additional
6850 switches are also taken into account. Thus,
6851 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
6852 @code{--GCC="bar -x -y -z -t"}.
6853
6854 @item --LINK=@var{name}
6855 @cindex @code{--LINK=} (@code{gnatlink})
6856 @var{name} is the name of the linker to be invoked. This is especially
6857 useful in mixed language programs since languages such as c++ require
6858 their own linker to be used. When this switch is omitted, the default
6859 name for the linker is (@file{gcc}). When this switch is used, the
6860 specified linker is called instead of (@file{gcc}) with exactly the same
6861 parameters that would have been passed to (@file{gcc}) so if the desired
6862 linker requires different parameters it is necessary to use a wrapper
6863 script that massages the parameters before invoking the real linker. It
6864 may be useful to control the exact invocation by using the verbose
6865 switch.
6866
6867
6868
6869 @end table
6870
6871 @node Setting Stack Size from gnatlink
6872 @section Setting Stack Size from @code{gnatlink}
6873
6874 @noindent
6875 It is possible to specify the program stack size from @code{gnatlink}.
6876 Assuming that the underlying linker is GNU ld there is two ways to do so:
6877
6878 @itemize @bullet
6879
6880 @item using @code{-Xlinker} linker option
6881
6882 @smallexample
6883 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
6884 @end smallexample
6885
6886 This set the stack reserve size to 0x10000 bytes and the stack commit
6887 size to 0x1000 bytes.
6888
6889 @item using @code{-Wl} linker option
6890
6891 @smallexample
6892 $ gnatlink hello -Wl,--stack=0x1000000
6893 @end smallexample
6894
6895 This set the stack reserve size to 0x1000000 bytes. Note that with
6896 @code{-Wl} option it is not possible to set the stack commit size
6897 because the coma is a separator for this option.
6898
6899 @end itemize
6900
6901 @node Setting Heap Size from gnatlink
6902 @section Setting Heap Size from @code{gnatlink}
6903
6904 @noindent
6905 It is possible to specify the program heap size from @code{gnatlink}.
6906 Assuming that the underlying linker is GNU ld there is two ways to do so:
6907
6908 @itemize @bullet
6909
6910 @item using @code{-Xlinker} linker option
6911
6912 @smallexample
6913 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
6914 @end smallexample
6915
6916 This set the heap reserve size to 0x10000 bytes and the heap commit
6917 size to 0x1000 bytes.
6918
6919 @item using @code{-Wl} linker option
6920
6921 @smallexample
6922 $ gnatlink hello -Wl,--heap=0x1000000
6923 @end smallexample
6924
6925 This set the heap reserve size to 0x1000000 bytes. Note that with
6926 @code{-Wl} option it is not possible to set the heap commit size
6927 because the coma is a separator for this option.
6928
6929 @end itemize
6930
6931 @node The GNAT Make Program gnatmake
6932 @chapter The GNAT Make Program @code{gnatmake}
6933 @findex gnatmake
6934
6935 @menu
6936 * Running gnatmake::
6937 * Switches for gnatmake::
6938 * Mode Switches for gnatmake::
6939 * Notes on the Command Line::
6940 * How gnatmake Works::
6941 * Examples of gnatmake Usage::
6942 @end menu
6943 @noindent
6944 A typical development cycle when working on an Ada program consists of
6945 the following steps:
6946
6947 @enumerate
6948 @item
6949 Edit some sources to fix bugs.
6950
6951 @item
6952 Add enhancements.
6953
6954 @item
6955 Compile all sources affected.
6956
6957 @item
6958 Rebind and relink.
6959
6960 @item
6961 Test.
6962 @end enumerate
6963
6964 @noindent
6965 The third step can be tricky, because not only do the modified files
6966 @cindex Dependency rules
6967 have to be compiled, but any files depending on these files must also be
6968 recompiled. The dependency rules in Ada can be quite complex, especially
6969 in the presence of overloading, @code{use} clauses, generics and inlined
6970 subprograms.
6971
6972 @code{gnatmake} automatically takes care of the third and fourth steps
6973 of this process. It determines which sources need to be compiled,
6974 compiles them, and binds and links the resulting object files.
6975
6976 Unlike some other Ada make programs, the dependencies are always
6977 accurately recomputed from the new sources. The source based approach of
6978 the GNAT compilation model makes this possible. This means that if
6979 changes to the source program cause corresponding changes in
6980 dependencies, they will always be tracked exactly correctly by
6981 @code{gnatmake}.
6982
6983 @node Running gnatmake
6984 @section Running @code{gnatmake}
6985
6986 @noindent
6987 The usual form of the @code{gnatmake} command is
6988
6989 @smallexample
6990 $ gnatmake [@var{switches}] @var{file_name} [@var{file_names}] [@var{mode_switches}]
6991 @end smallexample
6992
6993 @noindent
6994 The only required argument is one @var{file_name}, which specifies
6995 a compilation unit that is a main program. Several @var{file_names} can be
6996 specified: this will result in several executables being built.
6997 If @code{switches} are present, they can be placed before the first
6998 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
6999 If @var{mode_switches} are present, they must always be placed after
7000 the last @var{file_name} and all @code{switches}.
7001
7002 If you are using standard file extensions (.adb and .ads), then the
7003 extension may be omitted from the @var{file_name} arguments. However, if
7004 you are using non-standard extensions, then it is required that the
7005 extension be given. A relative or absolute directory path can be
7006 specified in a @var{file_name}, in which case, the input source file will
7007 be searched for in the specified directory only. Otherwise, the input
7008 source file will first be searched in the directory where
7009 @code{gnatmake} was invoked and if it is not found, it will be search on
7010 the source path of the compiler as described in
7011 @ref{Search Paths and the Run-Time Library (RTL)}.
7012
7013 When several @var{file_names} are specified, if an executable needs to be
7014 rebuilt and relinked, all subsequent executables will be rebuilt and
7015 relinked, even if this would not be absolutely necessary.
7016
7017 All @code{gnatmake} output (except when you specify
7018 @code{-M}) is to
7019 @file{stderr}. The output produced by the
7020 @code{-M} switch is send to
7021 @file{stdout}.
7022
7023 @node Switches for gnatmake
7024 @section Switches for @code{gnatmake}
7025
7026 @noindent
7027 You may specify any of the following switches to @code{gnatmake}:
7028
7029 @table @code
7030 @item --GCC=@var{compiler_name}
7031 @cindex @code{--GCC=compiler_name} (@code{gnatmake})
7032 Program used for compiling. The default is `@code{gcc}'. You need to use
7033 quotes around @var{compiler_name} if @code{compiler_name} contains
7034 spaces or other separator characters. As an example @code{--GCC="foo -x
7035 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
7036 compiler. Note that switch @code{-c} is always inserted after your
7037 command name. Thus in the above example the compiler command that will
7038 be used by @code{gnatmake} will be @code{foo -c -x -y}.
7039 If several @code{--GCC=compiler_name} are used, only the last
7040 @var{compiler_name} is taken into account. However, all the additional
7041 switches are also taken into account. Thus,
7042 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7043 @code{--GCC="bar -x -y -z -t"}.
7044
7045 @item --GNATBIND=@var{binder_name}
7046 @cindex @code{--GNATBIND=binder_name} (@code{gnatmake})
7047 Program used for binding. The default is `@code{gnatbind}'. You need to
7048 use quotes around @var{binder_name} if @var{binder_name} contains spaces
7049 or other separator characters. As an example @code{--GNATBIND="bar -x
7050 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
7051 binder. Binder switches that are normally appended by @code{gnatmake} to
7052 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
7053
7054 @item --GNATLINK=@var{linker_name}
7055 @cindex @code{--GNATLINK=linker_name} (@code{gnatmake})
7056 Program used for linking. The default is `@code{gnatlink}'. You need to
7057 use quotes around @var{linker_name} if @var{linker_name} contains spaces
7058 or other separator characters. As an example @code{--GNATLINK="lan -x
7059 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
7060 linker. Linker switches that are normally appended by @code{gnatmake} to
7061 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
7062
7063
7064 @item -a
7065 @cindex @code{-a} (@code{gnatmake})
7066 Consider all files in the make process, even the GNAT internal system
7067 files (for example, the predefined Ada library files), as well as any
7068 locked files. Locked files are files whose ALI file is write-protected.
7069 By default,
7070 @code{gnatmake} does not check these files,
7071 because the assumption is that the GNAT internal files are properly up
7072 to date, and also that any write protected ALI files have been properly
7073 installed. Note that if there is an installation problem, such that one
7074 of these files is not up to date, it will be properly caught by the
7075 binder.
7076 You may have to specify this switch if you are working on GNAT
7077 itself. @code{-a} is also useful in conjunction with
7078 @code{-f}
7079 if you need to recompile an entire application,
7080 including run-time files, using special configuration pragma settings,
7081 such as a non-standard @code{Float_Representation} pragma.
7082 By default
7083 @code{gnatmake -a} compiles all GNAT
7084 internal files with
7085 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7086
7087 @item -b
7088 @cindex @code{-b} (@code{gnatmake})
7089 Bind only. Can be combined with @code{-c} to do compilation
7090 and binding, but no link. Can be combined with @code{-l}
7091 to do binding and linking. When not combined with @code{-c}
7092 all the units in the closure of the main program must have been previously
7093 compiled and must be up to date. The root unit specified by @var{file_name}
7094 may be given without extension, with the source extension or, if no GNAT
7095 Project File is specified, with the ALI file extension.
7096
7097 @item -c
7098 @cindex @code{-c} (@code{gnatmake})
7099 Compile only. Do not perform binding, except when @code{-b}
7100 is also specified. Do not perform linking, except if both
7101 @code{-b} and
7102  @code{-l} are also specified.
7103 If the root unit specified by @var{file_name} is not a main unit, this is the
7104 default. Otherwise @code{gnatmake} will attempt binding and linking
7105 unless all objects are up to date and the executable is more recent than
7106 the objects.
7107
7108 @item -C
7109 @cindex @code{-C} (@code{gnatmake})
7110 Use a mapping file. A mapping file is a way to communicate to the compiler
7111 two mappings: from unit names to file names (without any directory information)
7112 and from file names to path names (with full directory information).
7113 These mappings are used by the compiler to short-circuit the path search.
7114 When @code{gnatmake} is invoked with this switch, it will create a mapping
7115 file, initially populated by the project manager, if @code{-P} is used,
7116 otherwise initially empty. Each invocation of the compiler will add the newly
7117 accessed sources to the mapping file. This will improve the source search
7118 during the next invocation of the compiler.
7119
7120 @item -f
7121 @cindex @code{-f} (@code{gnatmake})
7122 Force recompilations. Recompile all sources, even though some object
7123 files may be up to date, but don't recompile predefined or GNAT internal
7124 files or locked files (files with a write-protected ALI file),
7125 unless the @code{-a} switch is also specified.
7126
7127 @item
7128 @item -i
7129 @cindex @code{-i} (@code{gnatmake})
7130 In normal mode, @code{gnatmake} compiles all object files and ALI files
7131 into the current directory. If the @code{-i} switch is used,
7132 then instead object files and ALI files that already exist are overwritten
7133 in place. This means that once a large project is organized into separate
7134 directories in the desired manner, then @code{gnatmake} will automatically
7135 maintain and update this organization. If no ALI files are found on the
7136 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
7137 the new object and ALI files are created in the
7138 directory containing the source being compiled. If another organization
7139 is desired, where objects and sources are kept in different directories,
7140 a useful technique is to create dummy ALI files in the desired directories.
7141 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
7142 the corresponding source file, and it will be put the resulting object
7143 and ALI files in the directory where it found the dummy file.
7144
7145 @item -j@var{n}
7146 @cindex @code{-j} (@code{gnatmake})
7147 @cindex Parallel make
7148 Use @var{n} processes to carry out the (re)compilations. On a
7149 multiprocessor machine compilations will occur in parallel. In the
7150 event of compilation errors, messages from various compilations might
7151 get interspersed (but @code{gnatmake} will give you the full ordered
7152 list of failing compiles at the end). If this is problematic, rerun
7153 the make process with n set to 1 to get a clean list of messages.
7154
7155 @item -k
7156 @cindex @code{-k} (@code{gnatmake})
7157 Keep going. Continue as much as possible after a compilation error. To
7158 ease the programmer's task in case of compilation errors, the list of
7159 sources for which the compile fails is given when @code{gnatmake}
7160 terminates.
7161
7162 If @code{gnatmake} is invoked with several @file{file_names} and with this
7163 switch, if there are compilation errors when building an executable,
7164 @code{gnatmake} will not attempt to build the following executables.
7165
7166 @item -l
7167 @cindex @code{-l} (@code{gnatmake})
7168 Link only. Can be combined with @code{-b} to binding
7169 and linking. Linking will not be performed if combined with
7170 @code{-c}
7171 but not with @code{-b}.
7172 When not combined with @code{-b}
7173 all the units in the closure of the main program must have been previously
7174 compiled and must be up to date, and the main program need to have been bound.
7175 The root unit specified by @var{file_name}
7176 may be given without extension, with the source extension or, if no GNAT
7177 Project File is specified, with the ALI file extension.
7178
7179 @item -m
7180 @cindex @code{-m} (@code{gnatmake})
7181 Specifies that the minimum necessary amount of recompilations
7182 be performed. In this mode @code{gnatmake} ignores time
7183 stamp differences when the only
7184 modifications to a source file consist in adding/removing comments,
7185 empty lines, spaces or tabs. This means that if you have changed the
7186 comments in a source file or have simply reformatted it, using this
7187 switch will tell gnatmake not to recompile files that depend on it
7188 (provided other sources on which these files depend have undergone no
7189 semantic modifications). Note that the debugging information may be
7190 out of date with respect to the sources if the @code{-m} switch causes
7191 a compilation to be switched, so the use of this switch represents a
7192 trade-off between compilation time and accurate debugging information.
7193
7194 @item -M
7195 @cindex Dependencies, producing list
7196 @cindex @code{-M} (@code{gnatmake})
7197 Check if all objects are up to date. If they are, output the object
7198 dependences to @file{stdout} in a form that can be directly exploited in
7199 a @file{Makefile}. By default, each source file is prefixed with its
7200 (relative or absolute) directory name. This name is whatever you
7201 specified in the various @code{-aI}
7202 and @code{-I} switches. If you use
7203 @code{gnatmake -M}
7204 @code{-q}
7205 (see below), only the source file names,
7206 without relative paths, are output. If you just specify the
7207 @code{-M}
7208 switch, dependencies of the GNAT internal system files are omitted. This
7209 is typically what you want. If you also specify
7210 the @code{-a} switch,
7211 dependencies of the GNAT internal files are also listed. Note that
7212 dependencies of the objects in external Ada libraries (see switch
7213 @code{-aL}@var{dir} in the following list) are never reported.
7214
7215 @item -n
7216 @cindex @code{-n} (@code{gnatmake})
7217 Don't compile, bind, or link. Checks if all objects are up to date.
7218 If they are not, the full name of the first file that needs to be
7219 recompiled is printed.
7220 Repeated use of this option, followed by compiling the indicated source
7221 file, will eventually result in recompiling all required units.
7222
7223 @item -o @var{exec_name}
7224 @cindex @code{-o} (@code{gnatmake})
7225 Output executable name. The name of the final executable program will be
7226 @var{exec_name}. If the @code{-o} switch is omitted the default
7227 name for the executable will be the name of the input file in appropriate form
7228 for an executable file on the host system.
7229
7230 This switch cannot be used when invoking @code{gnatmake} with several
7231 @file{file_names}.
7232
7233 @item -q
7234 @cindex @code{-q} (@code{gnatmake})
7235 Quiet. When this flag is not set, the commands carried out by
7236 @code{gnatmake} are displayed.
7237
7238 @item -s
7239 @cindex @code{-s} (@code{gnatmake})
7240 Recompile if compiler switches have changed since last compilation.
7241 All compiler switches but -I and -o are taken into account in the
7242 following way:
7243 orders between different ``first letter'' switches are ignored, but
7244 orders between same switches are taken into account. For example,
7245 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O} is equivalent
7246 to @code{-O -g}.
7247
7248 @item -u
7249 @cindex @code{-u} (@code{gnatmake})
7250 Unique. Recompile at most the main file. It implies -c. Combined with
7251 -f, it is equivalent to calling the compiler directly.
7252
7253 @item -v
7254 @cindex @code{-v} (@code{gnatmake})
7255 Verbose. Displays the reason for all recompilations @code{gnatmake}
7256 decides are necessary.
7257
7258 @item -z
7259 @cindex @code{-z} (@code{gnatmake})
7260 No main subprogram. Bind and link the program even if the unit name
7261 given on the command line is a package name. The resulting executable
7262 will execute the elaboration routines of the package and its closure,
7263 then the finalization routines.
7264
7265 @item @code{gcc} @asis{switches}
7266 The switch @code{-g} or any uppercase switch (other than @code{-A},
7267 @code{-L} or
7268 @code{-S}) or any switch that is more than one character is passed to
7269 @code{gcc} (e.g. @code{-O}, @option{-gnato,} etc.)
7270 @end table
7271
7272 @noindent
7273 Source and library search path switches:
7274
7275 @table @code
7276 @item -aI@var{dir}
7277 @cindex @code{-aI} (@code{gnatmake})
7278 When looking for source files also look in directory @var{dir}.
7279 The order in which source files search is undertaken is
7280 described in @ref{Search Paths and the Run-Time Library (RTL)}.
7281
7282 @item -aL@var{dir}
7283 @cindex @code{-aL} (@code{gnatmake})
7284 Consider @var{dir} as being an externally provided Ada library.
7285 Instructs @code{gnatmake} to skip compilation units whose @file{.ali}
7286 files have been located in directory @var{dir}. This allows you to have
7287 missing bodies for the units in @var{dir} and to ignore out of date bodies
7288 for the same units. You still need to specify
7289 the location of the specs for these units by using the switches
7290 @code{-aI@var{dir}}
7291 or @code{-I@var{dir}}.
7292 Note: this switch is provided for compatibility with previous versions
7293 of @code{gnatmake}. The easier method of causing standard libraries
7294 to be excluded from consideration is to write-protect the corresponding
7295 ALI files.
7296
7297 @item -aO@var{dir}
7298 @cindex @code{-aO} (@code{gnatmake})
7299 When searching for library and object files, look in directory
7300 @var{dir}. The order in which library files are searched is described in
7301 @ref{Search Paths for gnatbind}.
7302
7303 @item -A@var{dir}
7304 @cindex Search paths, for @code{gnatmake}
7305 @cindex @code{-A} (@code{gnatmake})
7306 Equivalent to @code{-aL@var{dir}
7307 -aI@var{dir}}.
7308
7309 @item -I@var{dir}
7310 @cindex @code{-I} (@code{gnatmake})
7311 Equivalent to @code{-aO@var{dir}
7312 -aI@var{dir}}.
7313
7314 @item -I-
7315 @cindex @code{-I-} (@code{gnatmake})
7316 @cindex Source files, suppressing search
7317 Do not look for source files in the directory containing the source
7318 file named in the command line.
7319 Do not look for ALI or object files in the directory
7320 where @code{gnatmake} was invoked.
7321
7322 @item -L@var{dir}
7323 @cindex @code{-L} (@code{gnatmake})
7324 @cindex Linker libraries
7325 Add directory @var{dir} to the list of directories in which the linker
7326 Furthermore, under Windows, the sources pointed to by the libraries path
7327 set in the registry are not searched for.
7328 will search for libraries. This is equivalent to
7329 @code{-largs -L}@var{dir}.
7330
7331 @item -nostdinc
7332 @cindex @code{-nostdinc} (@code{gnatmake})
7333 Do not look for source files in the system default directory.
7334
7335 @item -nostdlib
7336 @cindex @code{-nostdlib} (@code{gnatmake})
7337 Do not look for library files in the system default directory.
7338
7339 @item --RTS=@var{rts-path}
7340 @cindex @code{--RTS} (@code{gnatmake})
7341 Specifies the default location of the runtime library. We look for the runtime
7342 in the following directories, and stop as soon as a valid runtime is found
7343 ("adainclude" or "ada_source_path", and "adalib" or "ada_object_path" present):
7344
7345 @itemize @bullet
7346 @item <current directory>/$rts_path
7347
7348 @item <default-search-dir>/$rts_path
7349
7350 @item <default-search-dir>/rts-$rts_path
7351 @end itemize
7352
7353 @noindent
7354 The selected path is handled like a normal RTS path.
7355
7356 @end table
7357
7358 @node Mode Switches for gnatmake
7359 @section Mode Switches for @code{gnatmake}
7360
7361 @noindent
7362 The mode switches (referred to as @code{mode_switches}) allow the
7363 inclusion of switches that are to be passed to the compiler itself, the
7364 binder or the linker. The effect of a mode switch is to cause all
7365 subsequent switches up to the end of the switch list, or up to the next
7366 mode switch, to be interpreted as switches to be passed on to the
7367 designated component of GNAT.
7368
7369 @table @code
7370 @item -cargs @var{switches}
7371 @cindex @code{-cargs} (@code{gnatmake})
7372 Compiler switches. Here @var{switches} is a list of switches
7373 that are valid switches for @code{gcc}. They will be passed on to
7374 all compile steps performed by @code{gnatmake}.
7375
7376 @item -bargs @var{switches}
7377 @cindex @code{-bargs} (@code{gnatmake})
7378 Binder switches. Here @var{switches} is a list of switches
7379 that are valid switches for @code{gcc}. They will be passed on to
7380 all bind steps performed by @code{gnatmake}.
7381
7382 @item -largs @var{switches}
7383 @cindex @code{-largs} (@code{gnatmake})
7384 Linker switches. Here @var{switches} is a list of switches
7385 that are valid switches for @code{gcc}. They will be passed on to
7386 all link steps performed by @code{gnatmake}.
7387 @end table
7388
7389 @node Notes on the Command Line
7390 @section Notes on the Command Line
7391
7392 @noindent
7393 This section contains some additional useful notes on the operation
7394 of the @code{gnatmake} command.
7395
7396 @itemize @bullet
7397 @item
7398 @cindex Recompilation, by @code{gnatmake}
7399 If @code{gnatmake} finds no ALI files, it recompiles the main program
7400 and all other units required by the main program.
7401 This means that @code{gnatmake}
7402 can be used for the initial compile, as well as during subsequent steps of
7403 the development cycle.
7404
7405 @item
7406 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
7407 is a subunit or body of a generic unit, @code{gnatmake} recompiles
7408 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
7409 warning.
7410
7411 @item
7412 In @code{gnatmake} the switch @code{-I}
7413 is used to specify both source and
7414 library file paths. Use @code{-aI}
7415 instead if you just want to specify
7416 source paths only and @code{-aO}
7417 if you want to specify library paths
7418 only.
7419
7420 @item
7421 @code{gnatmake} examines both an ALI file and its corresponding object file
7422 for consistency. If an ALI is more recent than its corresponding object,
7423 or if the object file is missing, the corresponding source will be recompiled.
7424 Note that @code{gnatmake} expects an ALI and the corresponding object file
7425 to be in the same directory.
7426
7427 @item
7428 @code{gnatmake} will ignore any files whose ALI file is write-protected.
7429 This may conveniently be used to exclude standard libraries from
7430 consideration and in particular it means that the use of the
7431 @code{-f} switch will not recompile these files
7432 unless @code{-a} is also specified.
7433
7434 @item
7435 @code{gnatmake} has been designed to make the use of Ada libraries
7436 particularly convenient. Assume you have an Ada library organized
7437 as follows: @var{obj-dir} contains the objects and ALI files for
7438 of your Ada compilation units,
7439 whereas @var{include-dir} contains the
7440 specs of these units, but no bodies. Then to compile a unit
7441 stored in @code{main.adb}, which uses this Ada library you would just type
7442
7443 @smallexample
7444 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
7445 @end smallexample
7446
7447 @item
7448 Using @code{gnatmake} along with the
7449 @code{-m (minimal recompilation)}
7450 switch provides a mechanism for avoiding unnecessary rcompilations. Using
7451 this switch,
7452 you can update the comments/format of your
7453 source files without having to recompile everything. Note, however, that
7454 adding or deleting lines in a source files may render its debugging
7455 info obsolete. If the file in question is a spec, the impact is rather
7456 limited, as that debugging info will only be useful during the
7457 elaboration phase of your program. For bodies the impact can be more
7458 significant. In all events, your debugger will warn you if a source file
7459 is more recent than the corresponding object, and alert you to the fact
7460 that the debugging information may be out of date.
7461 @end itemize
7462
7463 @node How gnatmake Works
7464 @section How @code{gnatmake} Works
7465
7466 @noindent
7467 Generally @code{gnatmake} automatically performs all necessary
7468 recompilations and you don't need to worry about how it works. However,
7469 it may be useful to have some basic understanding of the @code{gnatmake}
7470 approach and in particular to understand how it uses the results of
7471 previous compilations without incorrectly depending on them.
7472
7473 First a definition: an object file is considered @dfn{up to date} if the
7474 corresponding ALI file exists and its time stamp predates that of the
7475 object file and if all the source files listed in the
7476 dependency section of this ALI file have time stamps matching those in
7477 the ALI file. This means that neither the source file itself nor any
7478 files that it depends on have been modified, and hence there is no need
7479 to recompile this file.
7480
7481 @code{gnatmake} works by first checking if the specified main unit is up
7482 to date. If so, no compilations are required for the main unit. If not,
7483 @code{gnatmake} compiles the main program to build a new ALI file that
7484 reflects the latest sources. Then the ALI file of the main unit is
7485 examined to find all the source files on which the main program depends,
7486 and @code{gnatmake} recursively applies the above procedure on all these files.
7487
7488 This process ensures that @code{gnatmake} only trusts the dependencies
7489 in an existing ALI file if they are known to be correct. Otherwise it
7490 always recompiles to determine a new, guaranteed accurate set of
7491 dependencies. As a result the program is compiled "upside down" from what may
7492 be more familiar as the required order of compilation in some other Ada
7493 systems. In particular, clients are compiled before the units on which
7494 they depend. The ability of GNAT to compile in any order is critical in
7495 allowing an order of compilation to be chosen that guarantees that
7496 @code{gnatmake} will recompute a correct set of new dependencies if
7497 necessary.
7498
7499 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
7500 imported by several of the executables, it will be recompiled at most once.
7501
7502 @node Examples of gnatmake Usage
7503 @section Examples of @code{gnatmake} Usage
7504
7505 @table @code
7506 @item gnatmake hello.adb
7507 Compile all files necessary to bind and link the main program
7508 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
7509 resulting object files to generate an executable file @file{hello}.
7510
7511 @item gnatmake main1 main2 main3
7512 Compile all files necessary to bind and link the main programs
7513 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
7514 (containing unit @code{Main2}) and @file{main3.adb}
7515 (containing unit @code{Main3}) and bind and link the resulting object files
7516 to generate three executable files @file{main1},
7517 @file{main2}
7518 and @file{main3}.
7519
7520 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
7521
7522 Compile all files necessary to bind and link the main program unit
7523 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
7524 be done with optimization level 2 and the order of elaboration will be
7525 listed by the binder. @code{gnatmake} will operate in quiet mode, not
7526 displaying commands it is executing.
7527 @end table
7528
7529 @node Renaming Files Using gnatchop
7530 @chapter Renaming Files Using @code{gnatchop}
7531 @findex gnatchop
7532
7533 @noindent
7534 This chapter discusses how to handle files with multiple units by using
7535 the @code{gnatchop} utility. This utility is also useful in renaming
7536 files to meet the standard GNAT default file naming conventions.
7537
7538 @menu
7539 * Handling Files with Multiple Units::
7540 * Operating gnatchop in Compilation Mode::
7541 * Command Line for gnatchop::
7542 * Switches for gnatchop::
7543 * Examples of gnatchop Usage::
7544 @end menu
7545
7546 @node Handling Files with Multiple Units
7547 @section Handling Files with Multiple Units
7548
7549 @noindent
7550 The basic compilation model of GNAT requires that a file submitted to the
7551 compiler have only one unit and there be a strict correspondence
7552 between the file name and the unit name.
7553
7554 The @code{gnatchop} utility allows both of these rules to be relaxed,
7555 allowing GNAT to process files which contain multiple compilation units
7556 and files with arbitrary file names. @code{gnatchop}
7557 reads the specified file and generates one or more output files,
7558 containing one unit per file. The unit and the file name correspond,
7559 as required by GNAT.
7560
7561 If you want to permanently restructure a set of "foreign" files so that
7562 they match the GNAT rules, and do the remaining development using the
7563 GNAT structure, you can simply use @code{gnatchop} once, generate the
7564 new set of files and work with them from that point on.
7565
7566 Alternatively, if you want to keep your files in the "foreign" format,
7567 perhaps to maintain compatibility with some other Ada compilation
7568 system, you can set up a procedure where you use @code{gnatchop} each
7569 time you compile, regarding the source files that it writes as temporary
7570 files that you throw away.
7571
7572 @node Operating gnatchop in Compilation Mode
7573 @section Operating gnatchop in Compilation Mode
7574
7575 @noindent
7576 The basic function of @code{gnatchop} is to take a file with multiple units
7577 and split it into separate files. The boundary between files is reasonably
7578 clear, except for the issue of comments and pragmas. In default mode, the
7579 rule is that any pragmas between units belong to the previous unit, except
7580 that configuration pragmas always belong to the following unit. Any comments
7581 belong to the following unit. These rules
7582 almost always result in the right choice of
7583 the split point without needing to mark it explicitly and most users will
7584 find this default to be what they want. In this default mode it is incorrect to
7585 submit a file containing only configuration pragmas, or one that ends in
7586 configuration pragmas, to @code{gnatchop}.
7587
7588 However, using a special option to activate "compilation mode",
7589 @code{gnatchop}
7590 can perform another function, which is to provide exactly the semantics
7591 required by the RM for handling of configuration pragmas in a compilation.
7592 In the absence of configuration pragmas (at the main file level), this
7593 option has no effect, but it causes such configuration pragmas to be handled
7594 in a quite different manner.
7595
7596 First, in compilation mode, if @code{gnatchop} is given a file that consists of
7597 only configuration pragmas, then this file is appended to the
7598 @file{gnat.adc} file in the current directory. This behavior provides
7599 the required behavior described in the RM for the actions to be taken
7600 on submitting such a file to the compiler, namely that these pragmas
7601 should apply to all subsequent compilations in the same compilation
7602 environment. Using GNAT, the current directory, possibly containing a
7603 @file{gnat.adc} file is the representation
7604 of a compilation environment. For more information on the
7605 @file{gnat.adc} file, see the section on handling of configuration
7606 pragmas @pxref{Handling of Configuration Pragmas}.
7607
7608 Second, in compilation mode, if @code{gnatchop}
7609 is given a file that starts with
7610 configuration pragmas, and contains one or more units, then these
7611 configuration pragmas are prepended to each of the chopped files. This
7612 behavior provides the required behavior described in the RM for the
7613 actions to be taken on compiling such a file, namely that the pragmas
7614 apply to all units in the compilation, but not to subsequently compiled
7615 units.
7616
7617 Finally, if configuration pragmas appear between units, they are appended
7618 to the previous unit. This results in the previous unit being illegal,
7619 since the compiler does not accept configuration pragmas that follow
7620 a unit. This provides the required RM behavior that forbids configuration
7621 pragmas other than those preceding the first compilation unit of a
7622 compilation.
7623
7624 For most purposes, @code{gnatchop} will be used in default mode. The
7625 compilation mode described above is used only if you need exactly
7626 accurate behavior with respect to compilations, and you have files
7627 that contain multiple units and configuration pragmas. In this
7628 circumstance the use of @code{gnatchop} with the compilation mode
7629 switch provides the required behavior, and is for example the mode
7630 in which GNAT processes the ACVC tests.
7631
7632 @node Command Line for gnatchop
7633 @section Command Line for @code{gnatchop}
7634
7635 @noindent
7636 The @code{gnatchop} command has the form:
7637
7638 @smallexample
7639 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
7640       [@var{directory}]
7641 @end smallexample
7642
7643 @noindent
7644 The only required argument is the file name of the file to be chopped.
7645 There are no restrictions on the form of this file name. The file itself
7646 contains one or more Ada units, in normal GNAT format, concatenated
7647 together. As shown, more than one file may be presented to be chopped.
7648
7649 When run in default mode, @code{gnatchop} generates one output file in
7650 the current directory for each unit in each of the files.
7651
7652 @var{directory}, if specified, gives the name of the directory to which
7653 the output files will be written. If it is not specified, all files are
7654 written to the current directory.
7655
7656 For example, given a
7657 file called @file{hellofiles} containing
7658
7659 @smallexample
7660 @group
7661 @cartouche
7662 @b{procedure} hello;
7663
7664 @b{with} Text_IO; @b{use} Text_IO;
7665 @b{procedure} hello @b{is}
7666 @b{begin}
7667    Put_Line ("Hello");
7668 @b{end} hello;
7669 @end cartouche
7670 @end group
7671 @end smallexample
7672
7673 @noindent
7674 the command
7675
7676 @smallexample
7677 $ gnatchop hellofiles
7678 @end smallexample
7679
7680 @noindent
7681 generates two files in the current directory, one called
7682 @file{hello.ads} containing the single line that is the procedure spec,
7683 and the other called @file{hello.adb} containing the remaining text. The
7684 original file is not affected. The generated files can be compiled in
7685 the normal manner.
7686
7687 @node Switches for gnatchop
7688 @section Switches for @code{gnatchop}
7689
7690 @noindent
7691 @code{gnatchop} recognizes the following switches:
7692
7693 @table @code
7694
7695 @item -c
7696 @cindex @code{-c} (@code{gnatchop})
7697 Causes @code{gnatchop} to operate in compilation mode, in which
7698 configuration pragmas are handled according to strict RM rules. See
7699 previous section for a full description of this mode.
7700
7701 @item -gnatxxx
7702 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
7703 used to parse the given file. Not all @code{xxx} options make sense,
7704 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
7705 process a source file that uses Latin-2 coding for identifiers.
7706
7707 @item -h
7708 Causes @code{gnatchop} to generate a brief help summary to the standard
7709 output file showing usage information.
7710
7711 @item -k@var{mm}
7712 @cindex @code{-k} (@code{gnatchop})
7713 Limit generated file names to the specified number @code{mm}
7714 of characters.
7715 This is useful if the
7716 resulting set of files is required to be interoperable with systems
7717 which limit the length of file names.
7718 No space is allowed between the @code{-k} and the numeric value. The numeric
7719 value may be omitted in which case a default of @code{-k8},
7720 suitable for use
7721 with DOS-like file systems, is used. If no @code{-k} switch
7722 is present then
7723 there is no limit on the length of file names.
7724
7725 @item -p
7726 @cindex @code{-p} (@code{gnatchop})
7727 Causes the file modification time stamp of the input file to be
7728 preserved and used for the time stamp of the output file(s). This may be
7729 useful for preserving coherency of time stamps in an enviroment where
7730 @code{gnatchop} is used as part of a standard build process.
7731
7732 @item -q
7733 @cindex @code{-q} (@code{gnatchop})
7734 Causes output of informational messages indicating the set of generated
7735 files to be suppressed. Warnings and error messages are unaffected.
7736
7737 @item -r
7738 @cindex @code{-r} (@code{gnatchop})
7739 @findex Source_Reference
7740 Generate @code{Source_Reference} pragmas. Use this switch if the output
7741 files are regarded as temporary and development is to be done in terms
7742 of the original unchopped file. This switch causes
7743 @code{Source_Reference} pragmas to be inserted into each of the
7744 generated files to refers back to the original file name and line number.
7745 The result is that all error messages refer back to the original
7746 unchopped file.
7747 In addition, the debugging information placed into the object file (when
7748 the @code{-g} switch of @code{gcc} or @code{gnatmake} is specified) also
7749 refers back to this original file so that tools like profilers and
7750 debuggers will give information in terms of the original unchopped file.
7751
7752 If the original file to be chopped itself contains
7753 a @code{Source_Reference}
7754 pragma referencing a third file, then gnatchop respects
7755 this pragma, and the generated @code{Source_Reference} pragmas
7756 in the chopped file refer to the original file, with appropriate
7757 line numbers. This is particularly useful when @code{gnatchop}
7758 is used in conjunction with @code{gnatprep} to compile files that
7759 contain preprocessing statements and multiple units.
7760
7761 @item -v
7762 @cindex @code{-v} (@code{gnatchop})
7763 Causes @code{gnatchop} to operate in verbose mode. The version
7764 number and copyright notice are output, as well as exact copies of
7765 the gnat1 commands spawned to obtain the chop control information.
7766
7767 @item -w
7768 @cindex @code{-w} (@code{gnatchop})
7769 Overwrite existing file names. Normally @code{gnatchop} regards it as a
7770 fatal error if there is already a file with the same name as a
7771 file it would otherwise output, in other words if the files to be
7772 chopped contain duplicated units. This switch bypasses this
7773 check, and causes all but the last instance of such duplicated
7774 units to be skipped.
7775
7776 @item --GCC=xxxx
7777 @cindex @code{--GCC=} (@code{gnatchop})
7778 Specify the path of the GNAT parser to be used. When this switch is used,
7779 no attempt is made to add the prefix to the GNAT parser executable.
7780 @end table
7781
7782 @node Examples of gnatchop Usage
7783 @section Examples of @code{gnatchop} Usage
7784
7785 @table @code
7786 @item gnatchop -w hello_s.ada ichbiah/files
7787
7788 Chops the source file @file{hello_s.ada}. The output files will be
7789 placed in the directory @file{ichbiah/files},
7790 overwriting any
7791 files with matching names in that directory (no files in the current
7792 directory are modified).
7793
7794 @item gnatchop archive
7795 Chops the source file @file{archive}
7796 into the current directory. One
7797 useful application of @code{gnatchop} is in sending sets of sources
7798 around, for example in email messages. The required sources are simply
7799 concatenated (for example, using a Unix @code{cat}
7800 command), and then
7801 @code{gnatchop} is used at the other end to reconstitute the original
7802 file names.
7803
7804 @item gnatchop file1 file2 file3 direc
7805 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
7806 the resulting files in the directory @file{direc}. Note that if any units
7807 occur more than once anywhere within this set of files, an error message
7808 is generated, and no files are written. To override this check, use the
7809 @code{-w} switch,
7810 in which case the last occurrence in the last file will
7811 be the one that is output, and earlier duplicate occurrences for a given
7812 unit will be skipped.
7813 @end table
7814
7815 @node Configuration Pragmas
7816 @chapter Configuration Pragmas
7817 @cindex Configuration pragmas
7818 @cindex Pragmas, configuration
7819
7820 @noindent
7821 In Ada 95, configuration pragmas include those pragmas described as
7822 such in the Ada 95 Reference Manual, as well as
7823 implementation-dependent pragmas that are configuration pragmas. See the
7824 individual descriptions of pragmas in the GNAT Reference Manual for
7825 details on these additional GNAT-specific configuration pragmas. Most
7826 notably, the pragma @code{Source_File_Name}, which allows
7827 specifying non-default names for source files, is a configuration
7828 pragma. The following is a complete list of configuration pragmas
7829 recognized by @code{GNAT}:
7830
7831 @smallexample
7832    Ada_83
7833    Ada_95
7834    C_Pass_By_Copy
7835    Component_Alignment
7836    Discard_Names
7837    Elaboration_Checks
7838    Eliminate
7839    Extend_System
7840    Extensions_Allowed
7841    External_Name_Casing
7842    Float_Representation
7843    Initialize_Scalars
7844    License
7845    Locking_Policy
7846    Long_Float
7847    No_Run_Time
7848    Normalize_Scalars
7849    Polling
7850    Propagate_Exceptions
7851    Queuing_Policy
7852    Ravenscar
7853    Restricted_Run_Time
7854    Restrictions
7855    Reviewable
7856    Source_File_Name
7857    Style_Checks
7858    Suppress
7859    Task_Dispatching_Policy
7860    Unsuppress
7861    Use_VADS_Size
7862    Warnings
7863    Validity_Checks
7864 @end smallexample
7865
7866 @menu
7867 * Handling of Configuration Pragmas::
7868 * The Configuration Pragmas Files::
7869 @end menu
7870
7871 @node Handling of Configuration Pragmas
7872 @section Handling of Configuration Pragmas
7873
7874 Configuration pragmas may either appear at the start of a compilation
7875 unit, in which case they apply only to that unit, or they may apply to
7876 all compilations performed in a given compilation environment.
7877
7878 GNAT also provides the @code{gnatchop} utility to provide an automatic
7879 way to handle configuration pragmas following the semantics for
7880 compilations (that is, files with multiple units), described in the RM.
7881 See section @pxref{Operating gnatchop in Compilation Mode} for details.
7882 However, for most purposes, it will be more convenient to edit the
7883 @file{gnat.adc} file that contains configuration pragmas directly,
7884 as described in the following section.
7885
7886 @node The Configuration Pragmas Files
7887 @section The Configuration Pragmas Files
7888 @cindex @file{gnat.adc}
7889
7890 @noindent
7891 In GNAT a compilation environment is defined by the current
7892 directory at the time that a compile command is given. This current
7893 directory is searched for a file whose name is @file{gnat.adc}. If
7894 this file is present, it is expected to contain one or more
7895 configuration pragmas that will be applied to the current compilation.
7896 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
7897 considered.
7898
7899 Configuration pragmas may be entered into the @file{gnat.adc} file
7900 either by running @code{gnatchop} on a source file that consists only of
7901 configuration pragmas, or more conveniently  by
7902 direct editing of the @file{gnat.adc} file, which is a standard format
7903 source file.
7904
7905 In addition to @file{gnat.adc}, one additional file containing configuration
7906 pragmas may be applied to the current compilation using the switch
7907 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
7908 contains only configuration pragmas. These configuration pragmas are
7909 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
7910 is present and switch @option{-gnatA} is not used).
7911
7912 It is allowed to specify several switches @option{-gnatec}, however only
7913 the last one on the command line will be taken into account.
7914
7915
7916 @node Handling Arbitrary File Naming Conventions Using gnatname
7917 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
7918 @cindex Arbitrary File Naming Conventions
7919
7920 @menu
7921 * Arbitrary File Naming Conventions::
7922 * Running gnatname::
7923 * Switches for gnatname::
7924 * Examples of gnatname Usage::
7925 @end menu
7926
7927 @node Arbitrary File Naming Conventions
7928 @section Arbitrary File Naming Conventions
7929
7930 @noindent
7931 The GNAT compiler must be able to know the source file name of a compilation unit.
7932 When using the standard GNAT default file naming conventions (@code{.ads} for specs,
7933 @code{.adb} for bodies), the GNAT compiler does not need additional information.
7934
7935 @noindent
7936 When the source file names do not follow the standard GNAT default file naming
7937 conventions, the GNAT compiler must be given additional information through
7938 a configuration pragmas file (see @ref{Configuration Pragmas}) or a project file.
7939 When the non standard file naming conventions are well-defined, a small number of
7940 pragmas @code{Source_File_Name} specifying a naming pattern
7941 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
7942 if the file naming conventions are irregular or arbitrary, a number
7943 of pragma @code{Source_File_Name} for individual compilation units must be defined.
7944 To help maintain the correspondence between compilation unit names and
7945 source file names within the compiler,
7946 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
7947 set of files.
7948
7949 @node Running gnatname
7950 @section Running @code{gnatname}
7951
7952 @noindent
7953 The usual form of the @code{gnatname} command is
7954
7955 @smallexample
7956 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
7957 @end smallexample
7958
7959 @noindent
7960 All of the arguments are optional. If invoked without any argument,
7961 @code{gnatname} will display its usage.
7962
7963 @noindent
7964 When used with at least one naming pattern, @code{gnatname} will attempt to
7965 find all the compilation units in files that follow at least one of the
7966 naming patterns. To find these compilation units,
7967 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
7968 regular files.
7969
7970 @noindent
7971 One or several Naming Patterns may be given as arguments to @code{gnatname}.
7972 Each Naming Pattern is enclosed between double quotes.
7973 A Naming Pattern is a regular expression similar to the wildcard patterns
7974 used in file names by the Unix shells or the DOS prompt.
7975
7976 @noindent
7977 Examples of Naming Patterns are
7978
7979 @smallexample
7980    "*.[12].ada"
7981    "*.ad[sb]*"
7982    "body_*"    "spec_*"
7983 @end smallexample
7984
7985 @noindent
7986 For a more complete description of the syntax of Naming Patterns, see the second kind
7987 of regular expressions described in @file{g-regexp.ads} (the "Glob" regular
7988 expressions).
7989
7990 @noindent
7991 When invoked with no switches, @code{gnatname} will create a configuration
7992 pragmas file @file{gnat.adc} in the current working directory, with pragmas
7993 @code{Source_File_Name} for each file that contains a valid Ada unit.
7994
7995 @node Switches for gnatname
7996 @section Switches for @code{gnatname}
7997
7998 @noindent
7999 Switches for @code{gnatname} must precede any specified Naming Pattern.
8000
8001 @noindent
8002 You may specify any of the following switches to @code{gnatname}:
8003
8004 @table @code
8005
8006 @item -c@file{file}
8007 @cindex @code{-c} (@code{gnatname})
8008 Create a configuration pragmas file @file{file} (instead of the default
8009 @file{gnat.adc}). There may be zero, one or more space between @code{-c} and
8010 @file{file}. @file{file} may include directory information. @file{file} must be
8011 writeable. There may be only one switch @code{-c}. When a switch @code{-c} is
8012 specified, no switch @code{-P} may be specified (see below).
8013
8014 @item -d@file{dir}
8015 @cindex @code{-d} (@code{gnatname})
8016 Look for source files in directory @file{dir}. There may be zero, one or more spaces
8017 between @code{-d} and @file{dir}. When a switch @code{-d} is specified,
8018 the current working directory will not be searched for source files, unless it
8019 is explictly
8020 specified with a @code{-d} or @code{-D} switch. Several switches @code{-d} may be
8021 specified. If @file{dir} is a relative path, it is relative to the directory of
8022 the configuration pragmas file specified with switch @code{-c}, or to the directory
8023 of the project file specified with switch @code{-P} or, if neither switch @code{-c}
8024 nor switch @code{-P} are specified, it is relative to the current working
8025 directory. The directory
8026 specified with switch @code{-c} must exist and be readable.
8027
8028 @item -D@file{file}
8029 @cindex @code{-D} (@code{gnatname})
8030 Look for source files in all directories listed in text file @file{file}. There may be
8031 zero, one or more spaces between @code{-d} and @file{dir}. @file{file}
8032 must be an existing, readable text file. Each non empty line in @file{file} must be
8033 a directory. Specifying switch @code{-D} is equivalent to specifying as many switches
8034 @code{-d} as there are non empty lines in @file{file}.
8035
8036 @item -h
8037 @cindex @code{-h} (@code{gnatname})
8038 Output usage (help) information. The output is written to @file{stdout}.
8039
8040 @item -P@file{proj}
8041 @cindex @code{-P} (@code{gnatname})
8042 Create or update project file @file{proj}. There may be zero, one or more space
8043 between @code{-P} and @file{proj}. @file{proj} may include directory information.
8044 @file{proj} must be writeable. There may be only one switch @code{-P}.
8045 When a switch @code{-P} is specified, no switch @code{-c} may be specified.
8046
8047 @item -v
8048 @cindex @code{-v} (@code{gnatname})
8049 Verbose mode. Output detailed explanation of behavior to @file{stdout}. This includes
8050 name of the file written, the name of the directories to search and, for each file
8051 in those directories whose name matches at least one of the Naming Patterns, an
8052 indication of whether the file contains a unit, and if so the name of the unit.
8053
8054 @item -v -v
8055 Very Verbose mode. In addition to the output produced in verbose mode, for each file
8056 in the searched directories whose name matches none of the Naming Patterns, an
8057 indication is given that there is no match.
8058
8059 @item -x@file{pattern}
8060 Excluded patterns. Using this switch, it is possible to exclude some files
8061 that would match the name patterns. For example,
8062 @code{"gnatname -x "*_nt.ada" "*.ada"} will look for Ada units in all files
8063 with the @file{.ada} extension, except those whose names end with
8064 @file{_nt.ada}.
8065
8066 @end table
8067
8068 @node Examples of gnatname Usage
8069 @section Examples of @code{gnatname} Usage
8070
8071 @smallexample
8072 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
8073 @end smallexample
8074
8075 In this example, the directory @file{/home/me} must already exist and be
8076 writeable. In addition, the directory @file{/home/me/sources} (specified by
8077 @code{-d sources}) must exist and be readable. Note the optional spaces after
8078 @code{-c} and @code{-d}.
8079
8080 @smallexample
8081 $ gnatname -P/home/me/proj -x "*_nt_body.ada" -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
8082 @end smallexample
8083
8084 Note that several switches @code{-d} may be used, even in conjunction with one
8085 or several switches @code{-D}. Several Naming Patterns and one excluded pattern
8086 are used in this example.
8087
8088
8089 @c *****************************************
8090 @c * G N A T  P r o j e c t  M a n a g e r *
8091 @c *****************************************
8092 @node GNAT Project Manager
8093 @chapter GNAT Project Manager
8094
8095 @menu
8096 * Introduction::
8097 * Examples of Project Files::
8098 * Project File Syntax::
8099 * Objects and Sources in Project Files::
8100 * Importing Projects::
8101 * Project Extension::
8102 * External References in Project Files::
8103 * Packages in Project Files::
8104 * Variables from Imported Projects::
8105 * Naming Schemes::
8106 * Library Projects::
8107 * Switches Related to Project Files::
8108 * Tools Supporting Project Files::
8109 * An Extended Example::
8110 * Project File Complete Syntax::
8111 @end menu
8112
8113
8114 @c ****************
8115 @c * Introduction *
8116 @c ****************
8117
8118 @node Introduction
8119 @section Introduction
8120
8121 @noindent
8122 This chapter describes GNAT's @emph{Project Manager}, a facility that
8123 lets you configure various properties for a collection of source files.  In
8124 particular, you can specify:
8125 @itemize @bullet
8126 @item
8127 The directory or set of directories containing the source files, and/or the
8128 names of the specific source files themselves
8129 @item
8130 The directory in which the compiler's output
8131 (@file{ALI} files, object files, tree files) will be placed
8132 @item
8133 The directory in which the executable programs will be placed
8134 @item
8135 Switch settings for any of the project-enabled tools (@command{gnatmake},
8136 compiler, binder, linker, @code{gnatls}, @code{gnatxref}, @code{gnatfind});
8137 you can apply these settings either globally or to individual units
8138 @item
8139 The source files containing the main subprogram(s) to be built
8140 @item
8141 The source programming language(s) (currently Ada and/or C)
8142 @item
8143 Source file naming conventions; you can specify these either globally or for
8144 individual units
8145 @end itemize
8146
8147 @menu
8148 * Project Files::
8149 @end menu
8150
8151 @node Project Files
8152 @subsection Project Files
8153
8154 @noindent
8155 A @dfn{project} is a specific set of values for these properties.  You can
8156 define a project's settings in a @dfn{project file}, a text file with an
8157 Ada-like syntax; a property value is either a string or a list of strings.
8158 Properties that are not explicitly set receive default values.  A project
8159 file may interrogate the values of @dfn{external variables} (user-defined
8160 command-line switches or environment variables), and it may specify property
8161 settings conditionally, based on the value of such variables.
8162
8163 In simple cases, a project's source files depend only on other source files
8164 in the same project, or on the predefined libraries.  ("Dependence" is in
8165 the technical sense; for example, one Ada unit "with"ing another.)  However,
8166 the Project Manager also allows much more sophisticated arrangements,
8167 with the source files in one project depending on source files in other
8168 projects:
8169 @itemize @bullet
8170 @item
8171 One project can @emph{import} other projects containing needed source files.
8172 @item
8173 You can organize GNAT projects in a hierarchy: a @emph{child} project
8174 can extend a @emph{parent} project, inheriting the parent's source files and
8175 optionally overriding any of them with alternative versions
8176 @end itemize
8177
8178 @noindent
8179 More generally, the Project Manager lets you structure large development
8180 efforts into hierarchical subsystems, with build decisions deferred to the
8181 subsystem level and thus different compilation environments (switch settings)
8182 used for different subsystems.
8183
8184 The Project Manager is invoked through the @option{-P@emph{projectfile}}
8185 switch to @command{gnatmake} or to the @command{gnat} front driver.
8186 If you want to define (on the command line) an external variable that is
8187 queried by the project file, additionally use the
8188 @option{-X@emph{vbl}=@emph{value}} switch.
8189 The Project Manager parses and interprets the project file, and drives the
8190 invoked tool based on the project settings.
8191
8192 The Project Manager supports a wide range of development strategies,
8193 for systems of all sizes.  Some typical practices that are easily handled:
8194 @itemize @bullet
8195 @item
8196 Using a common set of source files, but generating object files in different
8197 directories via different switch settings
8198 @item
8199 Using a mostly-shared set of source files, but with different versions of
8200 some unit or units
8201 @end itemize
8202
8203 @noindent
8204 The destination of an executable can be controlled inside a project file
8205 using the @option{-o} switch. In the absence of such a switch either inside
8206 the project file or on the command line, any executable files generated by
8207 @command{gnatmake} will be placed in the directory @code{Exec_Dir} specified
8208 in the project file. If no @code{Exec_Dir} is specified, they will be placed
8209 in the object directory of the project.
8210
8211 You can use project files to achieve some of the effects of a source
8212 versioning system (for example, defining separate projects for
8213 the different sets of sources that comprise different releases) but the
8214 Project Manager is independent of any source configuration management tools
8215 that might be used by the developers.
8216
8217 The next section introduces the main features of GNAT's project facility
8218 through a sequence of examples; subsequent sections will present the syntax
8219 and semantics in more detail.
8220
8221
8222 @c *****************************
8223 @c * Examples of Project Files *
8224 @c *****************************
8225
8226 @node Examples of Project Files
8227 @section Examples of Project Files
8228 @noindent
8229 This section illustrates some of the typical uses of project files and
8230 explains their basic structure and behavior.
8231
8232 @menu
8233 * Common Sources with Different Switches and Different Output Directories::
8234 * Using External Variables::
8235 * Importing Other Projects::
8236 * Extending a Project::
8237 @end menu
8238
8239 @node Common Sources with Different Switches and Different Output Directories
8240 @subsection Common Sources with Different Switches and Different Output Directories
8241
8242 @menu
8243 * Source Files::
8244 * Specifying the Object Directory::
8245 * Specifying the Exec Directory::
8246 * Project File Packages::
8247 * Specifying Switch Settings::
8248 * Main Subprograms::
8249 * Source File Naming Conventions::
8250 * Source Language(s)::
8251 @end menu
8252
8253 @noindent
8254 Assume that the Ada source files @file{pack.ads}, @file{pack.adb}, and
8255 @file{proc.adb} are in the @file{/common} directory.  The file
8256 @file{proc.adb} contains an Ada main subprogram @code{Proc} that "with"s
8257 package @code{Pack}.  We want to compile these source files under two sets
8258 of switches:
8259 @itemize @bullet
8260 @item
8261 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
8262 and the @option{-gnata}, @option{-gnato}, and @option{-gnatE} switches to the
8263 compiler; the compiler's output is to appear in @file{/common/debug}
8264 @item
8265 When preparing a release version, we want to pass the @option{-O2} switch to
8266 the compiler; the compiler's output is to appear in @file{/common/release}
8267 @end itemize
8268
8269 @noindent
8270 The GNAT project files shown below, respectively @file{debug.gpr} and
8271 @file{release.gpr} in the @file{/common} directory, achieve these effects.
8272
8273 Diagrammatically:
8274 @smallexample
8275 @group
8276 /common
8277   debug.gpr
8278   release.gpr
8279   pack.ads
8280   pack.adb
8281   proc.adb
8282 @end group
8283 @group
8284 /common/debug @{-g, -gnata, -gnato, -gnatE@}
8285   proc.ali, proc.o
8286   pack.ali, pack.o
8287 @end group
8288 @group
8289 /common/release @{-O2@}
8290   proc.ali, proc.o
8291   pack.ali, pack.o
8292 @end group
8293 @end smallexample
8294 Here are the project files:
8295 @smallexample
8296 @group
8297 project Debug is
8298   for Object_Dir use "debug";
8299   for Main use ("proc");
8300
8301   package Builder is
8302     for Default_Switches ("Ada") use ("-g");
8303   end Builder;
8304 @end group
8305
8306 @group
8307   package Compiler is
8308     for Default_Switches ("Ada")
8309        use ("-fstack-check", "-gnata", "-gnato", "-gnatE");
8310   end Compiler;
8311 end Debug;
8312 @end group
8313 @end smallexample
8314
8315 @smallexample
8316 @group
8317 project Release is
8318   for Object_Dir use "release";
8319   for Exec_Dir use ".";
8320   for Main use ("proc");
8321
8322   package Compiler is
8323     for Default_Switches ("Ada") use ("-O2");
8324   end Compiler;
8325 end Release;
8326 @end group
8327 @end smallexample
8328
8329 @noindent
8330 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
8331 insensitive), and analogously the project defined by @file{release.gpr} is
8332 @code{"Release"}.  For consistency the file should have the same name as the
8333 project, and the project file's extension should be @code{"gpr"}. These
8334 conventions are not required, but a warning is issued if they are not followed.
8335
8336 If the current directory is @file{/temp}, then the command
8337 @smallexample
8338 gnatmake -P/common/debug.gpr
8339 @end smallexample
8340
8341 @noindent
8342 generates object and ALI files in @file{/common/debug}, and the @code{proc}
8343 executable also in @file{/common/debug}, using the switch settings defined in
8344 the project file.
8345
8346 Likewise, the command
8347 @smallexample
8348 gnatmake -P/common/release.gpr
8349 @end smallexample
8350
8351 @noindent
8352 generates object and ALI files in @file{/common/release}, and the @code{proc}
8353 executable in @file{/common}, using the switch settings from the project file.
8354
8355 @node Source Files
8356 @unnumberedsubsubsec Source Files
8357
8358 @noindent
8359 If a project file does not explicitly specify a set of source directories or
8360 a set of source files, then by default the project's source files are the
8361 Ada source files in the project file directory.  Thus @file{pack.ads},
8362 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
8363
8364 @node Specifying the Object Directory
8365 @unnumberedsubsubsec Specifying the Object Directory
8366
8367 @noindent
8368 Several project properties are modeled by Ada-style @emph{attributes};
8369 you define the property by supplying the equivalent of an Ada attribute
8370 definition clause in the project file.
8371 A project's object directory is such a property; the corresponding
8372 attribute is @code{Object_Dir}, and its value is a string expression.  A
8373 directory may be specified either as absolute or as relative; in the latter
8374 case, it is relative to the project file directory.  Thus the compiler's
8375 output is directed to @file{/common/debug} (for the @code{Debug} project)
8376 and to @file{/common/release} (for the @code{Release} project).  If
8377 @code{Object_Dir} is not specified, then the default is the project file
8378 directory.
8379
8380 @node Specifying the Exec Directory
8381 @unnumberedsubsubsec Specifying the Exec Directory
8382
8383 @noindent
8384 A project's exec directory is another property; the corresponding
8385 attribute is @code{Exec_Dir}, and its value is also a string expression,
8386 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
8387 then the default is the object directory (which may also be the project file
8388 directory if attribute @code{Object_Dir} is not specified). Thus the executable
8389 is placed in @file{/common/debug} for the @code{Debug} project (attribute
8390 @code{Exec_Dir} not specified) and in @file{/common} for the @code{Release}
8391 project.
8392
8393 @node Project File Packages
8394 @unnumberedsubsubsec Project File Packages
8395
8396 @noindent
8397 A GNAT tool integrated with the Project Manager is modeled by a
8398 corresponding package in the project file.
8399 The @code{Debug} project defines the packages @code{Builder}
8400 (for @command{gnatmake}) and @code{Compiler};
8401 the @code{Release} project defines only the @code{Compiler} package.
8402
8403 The Ada package syntax is not to be taken literally.  Although packages in
8404 project files bear a surface resemblance to packages in Ada source code, the
8405 notation is simply a way to convey a grouping of properties for a named
8406 entity.  Indeed, the package names permitted in project files are restricted
8407 to a predefined set, corresponding to the project-aware tools, and the contents
8408 of packages are limited to a small set of constructs.
8409 The packages in the example above contain attribute definitions.
8410
8411
8412 @node Specifying Switch Settings
8413 @unnumberedsubsubsec Specifying Switch Settings
8414
8415 @noindent
8416 Switch settings for a project-aware tool can be specified through attributes
8417 in the package corresponding to the tool.
8418 The example above illustrates one of the relevant attributes,
8419 @code{Default_Switches}, defined in the packages in both project files.
8420 Unlike simple attributes like @code{Source_Dirs}, @code{Default_Switches} is
8421 known as an @emph{associative array}.  When you define this attribute, you must
8422 supply an "index" (a literal string), and the effect of the attribute
8423 definition is to set the value of the "array" at the specified "index".
8424 For the @code{Default_Switches} attribute, the index is a programming
8425 language (in our case, Ada) , and the value specified (after @code{use})
8426 must be a list of string expressions.
8427
8428 The attributes permitted in project files are restricted to a predefined set.
8429 Some may appear at project level, others in packages.
8430 For any attribute that is an associate array, the index must always be a
8431 literal string, but the restrictions on this string (e.g., a file name or a
8432 language name) depend on the individual attribute.
8433 Also depending on the attribute, its specified value will need to be either a
8434 string or a string list.
8435
8436 In the @code{Debug} project, we set the switches for two tools,
8437 @command{gnatmake} and the compiler, and thus we include corresponding
8438 packages, with each package defining the @code{Default_Switches} attribute
8439 with index @code{"Ada"}.
8440 Note that the package corresponding to
8441 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
8442 similar, but with just the @code{Compiler} package.
8443
8444 In project @code{Debug} above the switches starting with @option{-gnat} that
8445 are specified in package @code{Compiler} could have been placed in package
8446 @code{Builder}, since @command{gnatmake} transmits all such switches to the
8447 compiler.
8448
8449 @node Main Subprograms
8450 @unnumberedsubsubsec Main Subprograms
8451
8452 @noindent
8453 One of the properties of a project is its list of main subprograms (actually
8454 a list of names of source files containing main subprograms, with the file
8455 extension optional.  This property is captured in the @code{Main} attribute,
8456 whose value is a list of strings.  If a project defines the @code{Main}
8457 attribute, then you do not need to identify the main subprogram(s) when
8458 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
8459
8460 @node Source File Naming Conventions
8461 @unnumberedsubsubsec Source File Naming Conventions
8462
8463 @noindent
8464 Since the project files do not specify any source file naming conventions,
8465 the GNAT defaults are used.  The mechanism for defining source file naming
8466 conventions -- a package named @code{Naming} -- will be described below
8467 (@pxref{Naming Schemes}).
8468
8469 @node Source Language(s)
8470 @unnumberedsubsubsec Source Language(s)
8471
8472 @noindent
8473 Since the project files do not specify a @code{Languages} attribute, by
8474 default the GNAT tools assume that the language of the project file is Ada.
8475 More generally, a project can comprise source files
8476 in Ada, C, and/or other languages.
8477
8478 @node Using External Variables
8479 @subsection Using External Variables
8480
8481 @noindent
8482 Instead of supplying different project files for debug and release, we can
8483 define a single project file that queries an external variable (set either
8484 on the command line or via an environment variable) in order to
8485 conditionally define the appropriate settings.  Again, assume that the
8486 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
8487 located in directory @file{/common}.  The following project file,
8488 @file{build.gpr}, queries the external variable named @code{STYLE} and
8489 defines an object directory and switch settings based on whether the value
8490 is @code{"deb"} (debug) or @code{"rel"} (release), where the default is
8491 @code{"deb"}.
8492
8493 @smallexample
8494 @group
8495 project Build is
8496   for Main use ("proc");
8497
8498   type Style_Type is ("deb", "rel");
8499   Style : Style_Type := external ("STYLE", "deb");
8500
8501   case Style is
8502     when "deb" =>
8503       for Object_Dir use "debug";
8504
8505     when "rel" =>
8506       for Object_Dir use "release";
8507       for Exec_Dir use ".";
8508   end case;
8509 @end group
8510
8511 @group
8512   package Builder is
8513
8514     case Style is
8515       when "deb" =>
8516         for Default_Switches ("Ada") use ("-g");
8517     end case;
8518
8519   end Builder;
8520 @end group
8521
8522 @group
8523   package Compiler is
8524
8525     case Style is
8526       when "deb" =>
8527         for Default_Switches ("Ada") use ("-gnata", "-gnato", "-gnatE");
8528
8529       when "rel" =>
8530         for Default_Switches ("Ada") use ("-O2");
8531     end case;
8532
8533   end Compiler;
8534
8535 end Build;
8536 @end group
8537 @end smallexample
8538
8539 @noindent
8540 @code{Style_Type} is an example of a @emph{string type}, which is the project
8541 file analog of an Ada enumeration type but containing string literals rather
8542 than identifiers.  @code{Style} is declared as a variable of this type.
8543
8544 The form @code{external("STYLE", "deb")} is known as an
8545 @emph{external reference}; its first argument is the name of an
8546 @emph{external variable}, and the second argument is a default value to be
8547 used if the external variable doesn't exist.  You can define an external
8548 variable on the command line via the @option{-X} switch, or you can use an
8549 environment variable as an external variable.
8550
8551 Each @code{case} construct is expanded by the Project Manager based on the
8552 value of @code{Style}. Thus the command
8553 @smallexample
8554 gnatmake -P/common/build.gpr -XSTYLE=deb
8555 @end smallexample
8556
8557 @noindent
8558 is equivalent to the @command{gnatmake} invocation using the project file
8559 @file{debug.gpr} in the earlier example.  So is the command
8560 @smallexample
8561 gnatmake -P/common/build.gpr
8562 @end smallexample
8563
8564 @noindent
8565 since @code{"deb"} is the default for @code{STYLE}.
8566
8567 Analogously,
8568 @smallexample
8569 gnatmake -P/common/build.gpr -XSTYLE=rel
8570 @end smallexample
8571
8572 @noindent
8573 is equivalent to the @command{gnatmake} invocation using the project file
8574 @file{release.gpr} in the earlier example.
8575
8576
8577 @node Importing Other Projects
8578 @subsection Importing Other Projects
8579
8580 @noindent
8581 A compilation unit in a source file in one project may depend on compilation
8582 units in source files in other projects.  To obtain this behavior, the
8583 dependent project must @emph{import} the projects containing the needed source
8584 files.  This effect is embodied in syntax similar to an Ada @code{with} clause,
8585 but the "with"ed entities are strings denoting project files.
8586
8587 As an example, suppose that the two projects @code{GUI_Proj} and
8588 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
8589 @file{comm_proj.gpr} in directories @file{/gui} and @file{/comm},
8590 respectively.  Assume that the source files for @code{GUI_Proj} are
8591 @file{gui.ads} and @file{gui.adb}, and that the source files for
8592 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, with each set of
8593 files located in its respective project file directory.  Diagrammatically:
8594
8595 @smallexample
8596 @group
8597 /gui
8598   gui_proj.gpr
8599   gui.ads
8600   gui.adb
8601 @end group
8602
8603 @group
8604 /comm
8605   comm_proj.gpr
8606   comm.ads
8607   comm.adb
8608 @end group
8609 @end smallexample
8610
8611 @noindent
8612 We want to develop an application in directory @file{/app} that "with"s the
8613 packages @code{GUI} and @code{Comm}, using the properties of the
8614 corresponding project files (e.g. the switch settings and object directory).
8615 Skeletal code for a main procedure might be something like the following:
8616
8617 @smallexample
8618 @group
8619 with GUI, Comm;
8620 procedure App_Main is
8621    ...
8622 begin
8623    ...
8624 end App_Main;
8625 @end group
8626 @end smallexample
8627
8628 @noindent
8629 Here is a project file, @file{app_proj.gpr}, that achieves the desired
8630 effect:
8631
8632 @smallexample
8633 @group
8634 with "/gui/gui_proj", "/comm/comm_proj";
8635 project App_Proj is
8636    for Main use ("app_main");
8637 end App_Proj;
8638 @end group
8639 @end smallexample
8640
8641 @noindent
8642 Building an executable is achieved through the command:
8643 @smallexample
8644 gnatmake -P/app/app_proj
8645 @end smallexample
8646 @noindent
8647 which will generate the @code{app_main} executable in the directory where
8648 @file{app_proj.gpr} resides.
8649
8650 If an imported project file uses the standard extension (@code{gpr}) then
8651 (as illustrated above) the @code{with} clause can omit the extension.
8652
8653 Our example specified an absolute path for each imported project file.
8654 Alternatively, you can omit the directory if either
8655 @itemize @bullet
8656 @item
8657 The imported project file is in the same directory as the importing project
8658 file, or
8659 @item
8660 You have defined an environment variable @code{ADA_PROJECT_PATH} that
8661 includes the directory containing the needed project file.
8662 @end itemize
8663
8664 @noindent
8665 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{/gui} and
8666 @file{/comm}, then our project file @file{app_proj.gpr} could be written as
8667 follows:
8668
8669 @smallexample
8670 @group
8671 with "gui_proj", "comm_proj";
8672 project App_Proj is
8673    for Main use ("app_main");
8674 end App_Proj;
8675 @end group
8676 @end smallexample
8677
8678 @noindent
8679 Importing other projects raises the possibility of ambiguities.  For
8680 example, the same unit might be present in different imported projects, or
8681 it might be present in both the importing project and an imported project.
8682 Both of these conditions are errors.  Note that in the current version of
8683 the Project Manager, it is illegal to have an ambiguous unit even if the
8684 unit is never referenced by the importing project.  This restriction may be
8685 relaxed in a future release.
8686
8687 @node Extending a Project
8688 @subsection Extending a Project
8689
8690 @noindent
8691 A common situation in large software systems is to have multiple
8692 implementations for a common interface; in Ada terms, multiple versions of a
8693 package body for the same specification.  For example, one implementation
8694 might be safe for use in tasking programs, while another might only be used
8695 in sequential applications.  This can be modeled in GNAT using the concept
8696 of @emph{project extension}.  If one project (the "child") @emph{extends}
8697 another project (the "parent") then by default all source files of the
8698 parent project are inherited by the child, but the child project can
8699 override any of the parent's source files with new versions, and can also
8700 add new files.  This facility is the project analog of extension in
8701 Object-Oriented Programming.  Project hierarchies are permitted (a child
8702 project may be the parent of yet another project), and a project that
8703 inherits one project can also import other projects.
8704
8705 As an example, suppose that directory @file{/seq} contains the project file
8706 @file{seq_proj.gpr} and the source files @file{pack.ads}, @file{pack.adb},
8707 and @file{proc.adb}:
8708
8709 @smallexample
8710 @group
8711 /seq
8712   pack.ads
8713   pack.adb
8714   proc.adb
8715   seq_proj.gpr
8716 @end group
8717 @end smallexample
8718
8719 @noindent
8720 Note that the project file can simply be empty (that is, no attribute or
8721 package is defined):
8722
8723 @smallexample
8724 @group
8725 project Seq_Proj is
8726 end Seq_Proj;
8727 @end group
8728 @end smallexample
8729
8730 @noindent
8731 implying that its source files are all the Ada source files in the project
8732 directory.
8733
8734 Suppose we want to supply an alternate version of @file{pack.adb}, in
8735 directory @file{/tasking}, but use the existing versions of @file{pack.ads}
8736 and @file{proc.adb}.  We can define a project @code{Tasking_Proj} that
8737 inherits @code{Seq_Proj}:
8738
8739 @smallexample
8740 @group
8741 /tasking
8742   pack.adb
8743   tasking_proj.gpr
8744 @end group
8745
8746 @group
8747 project Tasking_Proj extends "/seq/seq_proj" is
8748 end Tasking_Proj;
8749 @end group
8750 @end smallexample
8751
8752 @noindent
8753 The version of @file{pack.adb} used in a build depends on which project file
8754 is specified.
8755
8756 Note that we could have designed this using project import rather than
8757 project inheritance; a @code{base} project would contain the sources for
8758 @file{pack.ads} and @file{proc.adb}, a sequential project would import
8759 @code{base} and add @file{pack.adb}, and likewise a tasking project would
8760 import @code{base} and add a different version of @file{pack.adb}.  The
8761 choice depends on whether other sources in the original project need to be
8762 overridden.  If they do, then project extension is necessary, otherwise,
8763 importing is sufficient.
8764
8765
8766 @c ***********************
8767 @c * Project File Syntax *
8768 @c ***********************
8769
8770 @node Project File Syntax
8771 @section Project File Syntax
8772
8773 @menu
8774 * Basic Syntax::
8775 * Packages::
8776 * Expressions::
8777 * String Types::
8778 * Variables::
8779 * Attributes::
8780 * Associative Array Attributes::
8781 * case Constructions::
8782 @end menu
8783
8784 @noindent
8785 This section describes the structure of project files.
8786
8787 A project may be an @emph{independent project}, entirely defined by a single
8788 project file. Any Ada source file in an independent project depends only
8789 on the predefined library and other Ada source files in the same project.
8790
8791 @noindent
8792 A project may also @dfn{depend on} other projects, in either or both of the following ways:
8793 @itemize @bullet
8794 @item It may import any number of projects
8795 @item It may extend at most one other project
8796 @end itemize
8797
8798 @noindent
8799 The dependence relation is a directed acyclic graph (the subgraph reflecting
8800 the "extends" relation is a tree).
8801
8802 A project's @dfn{immediate sources} are the source files directly defined by
8803 that project, either implicitly by residing in the project file's directory,
8804 or explicitly through any of the source-related attributes described below.
8805 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
8806 of @var{proj} together with the immediate sources (unless overridden) of any
8807 project on which @var{proj} depends (either directly or indirectly).
8808
8809 @node Basic Syntax
8810 @subsection Basic Syntax
8811
8812 @noindent
8813 As seen in the earlier examples, project files have an Ada-like syntax.
8814 The minimal project file is:
8815 @smallexample
8816 @group
8817 project Empty is
8818
8819 end Empty;
8820 @end group
8821 @end smallexample
8822
8823 @noindent
8824 The identifier @code{Empty} is the name of the project.
8825 This project name must be present after the reserved
8826 word @code{end} at the end of the project file, followed by a semi-colon.
8827
8828 Any name in a project file, such as the project name or a variable name,
8829 has the same syntax as an Ada identifier.
8830
8831 The reserved words of project files are the Ada reserved words plus
8832 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
8833 reserved words currently used in project file syntax are:
8834
8835 @itemize @bullet
8836 @item
8837 @code{case}
8838 @item
8839 @code{end}
8840 @item
8841 @code{for}
8842 @item
8843 @code{is}
8844 @item
8845 @code{others}
8846 @item
8847 @code{package}
8848 @item
8849 @code{renames}
8850 @item
8851 @code{type}
8852 @item
8853 @code{use}
8854 @item
8855 @code{when}
8856 @item
8857 @code{with}
8858 @end itemize
8859
8860 @noindent
8861 Comments in project files have the same syntax as in Ada, two consecutives
8862 hyphens through the end of the line.
8863
8864 @node Packages
8865 @subsection Packages
8866
8867 @noindent
8868 A project file may contain @emph{packages}. The name of a package must be one
8869 of the identifiers (case insensitive) from a predefined list, and a package
8870 with a given name may only appear once in a project file. The predefined list
8871 includes the following packages:
8872
8873 @itemize @bullet
8874 @item
8875 @code{Naming}
8876 @item
8877 @code{Builder}
8878 @item
8879 @code{Compiler}
8880 @item
8881 @code{Binder}
8882 @item
8883 @code{Linker}
8884 @item
8885 @code{Finder}
8886 @item
8887 @code{Cross_Reference}
8888 @item
8889 @code{gnatls}
8890 @end itemize
8891
8892 @noindent
8893 (The complete list of the package names and their attributes can be found
8894 in file @file{prj-attr.adb}).
8895
8896 @noindent
8897 In its simplest form, a package may be empty:
8898
8899 @smallexample
8900 @group
8901 project Simple is
8902   package Builder is
8903   end Builder;
8904 end Simple;
8905 @end group
8906 @end smallexample
8907
8908 @noindent
8909 A package may contain @emph{attribute declarations},
8910 @emph{variable declarations} and @emph{case constructions}, as will be
8911 described below.
8912
8913 When there is ambiguity between a project name and a package name,
8914 the name always designates the project. To avoid possible confusion, it is
8915 always a good idea to avoid naming a project with one of the
8916 names allowed for packages or any name that starts with @code{gnat}.
8917
8918
8919 @node Expressions
8920 @subsection Expressions
8921
8922 @noindent
8923 An @emph{expression} is either a @emph{string expression} or a
8924 @emph{string list expression}.
8925
8926 A @emph{string expression} is either a @emph{simple string expression} or a
8927 @emph{compound string expression}.
8928
8929 A @emph{simple string expression} is one of the following:
8930 @itemize @bullet
8931 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
8932 @item A string-valued variable reference (see @ref{Variables})
8933 @item A string-valued attribute reference (see @ref{Attributes})
8934 @item An external reference (see @ref{External References in Project Files})
8935 @end itemize
8936
8937 @noindent
8938 A @emph{compound string expression} is a concatenation of string expressions,
8939 using @code{"&"}
8940 @smallexample
8941        Path & "/" & File_Name & ".ads"
8942 @end smallexample
8943
8944 @noindent
8945 A @emph{string list expression} is either a
8946 @emph{simple string list expression} or a
8947 @emph{compound string list expression}.
8948
8949 A @emph{simple string list expression} is one of the following:
8950 @itemize @bullet
8951 @item A parenthesized list of zero or more string expressions, separated by commas
8952 @smallexample
8953    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
8954    Empty_List := ();
8955 @end smallexample
8956 @item A string list-valued variable reference
8957 @item A string list-valued attribute reference
8958 @end itemize
8959
8960 @noindent
8961 A @emph{compound string list expression} is the concatenation (using
8962 @code{"&"}) of a simple string list expression and an expression.  Note that
8963 each term in a compound string list expression, except the first, may be
8964 either a string expression or a string list expression.
8965
8966 @smallexample
8967 @group
8968    File_Name_List := () & File_Name; --  One string in this list
8969    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
8970    --  Two strings
8971    Big_List := File_Name_List & Extended_File_Name_List;
8972    --  Concatenation of two string lists: three strings
8973    Illegal_List := "gnat.adc" & Extended_File_Name_List;
8974    --  Illegal: must start with a string list
8975 @end group
8976 @end smallexample
8977
8978
8979 @node String Types
8980 @subsection String Types
8981
8982 @noindent
8983 The value of a variable may be restricted to a list of string literals.
8984 The restricted list of string literals is given in a
8985 @emph{string type declaration}.
8986
8987 Here is an example of a string type declaration:
8988
8989 @smallexample
8990    type OS is ("NT, "nt", "Unix", "Linux", "other OS");
8991 @end smallexample
8992
8993 @noindent
8994 Variables of a string type are called @emph{typed variables}; all other
8995 variables are called @emph{untyped variables}. Typed variables are
8996 particularly useful in @code{case} constructions
8997 (see @ref{case Constructions}).
8998
8999 A string type declaration starts with the reserved word @code{type}, followed
9000 by the name of the string type (case-insensitive), followed by the reserved
9001 word @code{is}, followed by a parenthesized list of one or more string literals
9002 separated by commas, followed by a semicolon.
9003
9004 The string literals in the list are case sensitive and must all be different.
9005 They may include any graphic characters allowed in Ada, including spaces.
9006
9007 A string type may only be declared at the project level, not inside a package.
9008
9009 A string type may be referenced by its name if it has been declared in the same
9010 project file, or by its project name, followed by a dot,
9011 followed by the string type name.
9012
9013
9014 @node Variables
9015 @subsection Variables
9016
9017 @noindent
9018 A variable may be declared at the project file level, or in a package.
9019 Here are some examples of variable declarations:
9020
9021 @smallexample
9022 @group
9023    This_OS : OS := external ("OS"); --  a typed variable declaration
9024    That_OS := "Linux";              --  an untyped variable declaration
9025 @end group
9026 @end smallexample
9027
9028 @noindent
9029 A @emph{typed variable declaration} includes the variable name, followed by a colon,
9030 followed by the name of a string type, followed by @code{:=}, followed by
9031 a simple string expression.
9032
9033 An @emph{untyped variable declaration} includes the variable name,
9034 followed by @code{:=}, followed by an expression.  Note that, despite the
9035 terminology, this form of "declaration" resembles more an assignment
9036 than a declaration in Ada.  It is a declaration in several senses:
9037 @itemize @bullet
9038 @item
9039 The variable name does not need to be defined previously
9040 @item
9041 The declaration establishes the @emph{kind} (string versus string list) of the
9042 variable, and later declarations of the same variable need to be consistent
9043 with this
9044 @end itemize
9045
9046 @noindent
9047 A string variable declaration (typed or untyped) declares a variable
9048 whose value is a string. This variable may be used as a string expression.
9049 @smallexample
9050    File_Name       := "readme.txt";
9051    Saved_File_Name := File_Name & ".saved";
9052 @end smallexample
9053
9054 @noindent
9055 A string list variable declaration declares a variable whose value is a list
9056 of strings. The list may contain any number (zero or more) of strings.
9057
9058 @smallexample
9059    Empty_List := ();
9060    List_With_One_Element := ("-gnaty");
9061    List_With_Two_Elements := List_With_One_Element & "-gnatg";
9062    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
9063                  "pack2.ada", "util_.ada", "util.ada");
9064 @end smallexample
9065
9066 @noindent
9067 The same typed variable may not be declared more than once at project level, and it may not be declared more than once in any package; it is in effect a constant or a readonly variable.
9068
9069 The same untyped variable may be declared several times.
9070 In this case, the new value replaces the old one,
9071 and any subsequent reference to the variable uses the new value.
9072 However, as noted above, if a variable has been declared as a string, all subsequent
9073 declarations must give it a string value. Similarly, if a variable has
9074 been declared as a string list, all subsequent declarations
9075 must give it a string list value.
9076
9077 A @emph{variable reference} may take several forms:
9078
9079 @itemize @bullet
9080 @item The simple variable name, for a variable in the current package (if any) or in the current project
9081 @item A context name, followed by a dot, followed by the variable name.
9082 @end itemize
9083
9084 @noindent
9085 A @emph{context} may be one of the following:
9086
9087 @itemize @bullet
9088 @item The name of an existing package in the current project
9089 @item The name of an imported project of the current project
9090 @item The name of an ancestor project (i.e., a project extended by the current project, either directly or indirectly)
9091 @item An imported/parent project name, followed by a dot, followed by a package name
9092 @end itemize
9093
9094 @noindent
9095 A variable reference may be used in an expression.
9096
9097
9098 @node Attributes
9099 @subsection Attributes
9100
9101 @noindent
9102 A project (and its packages) may have @emph{attributes} that define the project's properties.
9103 Some attributes have values that are strings;
9104 others have values that are string lists.
9105
9106 There are two categories of attributes: @emph{simple attributes} and @emph{associative arrays}
9107 (see @ref{Associative Array Attributes}).
9108
9109 The names of the attributes are restricted; there is a list of project
9110 attributes, and a list of package attributes for each package.
9111 The names are not case sensitive.
9112
9113 The project attributes are as follows (all are simple attributes):
9114
9115 @multitable @columnfractions .4 .3
9116 @item @emph{Attribute Name}
9117 @tab @emph{Value}
9118 @item @code{Source_Files}
9119 @tab string list
9120 @item @code{Source_Dirs}
9121 @tab string list
9122 @item @code{Source_List_File}
9123 @tab string
9124 @item @code{Object_Dir}
9125 @tab string
9126 @item @code{Exec_Dir}
9127 @tab string
9128 @item @code{Main}
9129 @tab string list
9130 @item @code{Languages}
9131 @tab string list
9132 @item @code{Library_Dir}
9133 @tab string
9134 @item @code{Library_Name}
9135 @tab string
9136 @item @code{Library_Kind}
9137 @tab string
9138 @item @code{Library_Elaboration}
9139 @tab string
9140 @item @code{Library_Version}
9141 @tab string
9142 @end multitable
9143
9144 @noindent
9145 The attributes for package @code{Naming} are as follows
9146 (see @ref{Naming Schemes}):
9147
9148 @multitable @columnfractions .4 .2 .2 .2
9149 @item Attribute Name @tab Category @tab Index @tab Value
9150 @item @code{Specification_Suffix}
9151 @tab associative array
9152 @tab language name
9153 @tab string
9154 @item @code{Implementation_Suffix}
9155 @tab associative array
9156 @tab language name
9157 @tab string
9158 @item @code{Separate_Suffix}
9159 @tab simple attribute
9160 @tab n/a
9161 @tab string
9162 @item @code{Casing}
9163 @tab simple attribute
9164 @tab n/a
9165 @tab string
9166 @item @code{Dot_Replacement}
9167 @tab simple attribute
9168 @tab n/a
9169 @tab string
9170 @item @code{Specification}
9171 @tab associative array
9172 @tab Ada unit name
9173 @tab string
9174 @item @code{Implementation}
9175 @tab associative array
9176 @tab Ada unit name
9177 @tab string
9178 @item @code{Specification_Exceptions}
9179 @tab associative array
9180 @tab language name
9181 @tab string list
9182 @item @code{Implementation_Exceptions}
9183 @tab associative array
9184 @tab language name
9185 @tab string list
9186 @end multitable
9187
9188 @noindent
9189 The attributes for package @code{Builder}, @code{Compiler}, @code{Binder},
9190 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
9191 are as follows (see @ref{Switches and Project Files}).
9192
9193 @multitable @columnfractions .4 .2 .2 .2
9194 @item Attribute Name @tab Category @tab Index @tab Value
9195 @item @code{Default_Switches}
9196 @tab associative array
9197 @tab language name
9198 @tab string list
9199 @item @code{Switches}
9200 @tab associative array
9201 @tab file name
9202 @tab string list
9203 @end multitable
9204
9205 @noindent
9206 In addition, package @code{Builder} has a single string attribute
9207 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
9208 string attribute @code{Global_Configuration_Pragmas}.
9209
9210 @noindent
9211 The attribute for package @code{Glide} are not documented: they are for
9212 internal use only.
9213
9214 @noindent
9215 Each simple attribute has a default value: the empty string (for string-valued
9216 attributes) and the empty list (for string list-valued attributes).
9217
9218 Similar to variable declarations, an attribute declaration defines a new value
9219 for an attribute.
9220
9221 Examples of simple attribute declarations:
9222
9223 @smallexample
9224    for Object_Dir use "objects";
9225    for Source_Dirs use ("units", "test/drivers");
9226 @end smallexample
9227
9228 @noindent
9229 A @dfn{simple attribute declaration} starts with the reserved word @code{for},
9230 followed by the name of the attribute, followed by the reserved word
9231 @code{use}, followed by an expression (whose kind depends on the attribute),
9232 followed by a semicolon.
9233
9234 Attributes may be referenced in expressions.
9235 The general form for such a reference is @code{<entity>'<attribute>}:
9236 the entity for which the attribute is defined,
9237 followed by an apostrophe, followed by the name of the attribute.
9238 For associative array attributes, a litteral string between parentheses
9239 need to be supplied as index.
9240
9241 Examples are:
9242
9243 @smallexample
9244   project'Object_Dir
9245   Naming'Dot_Replacement
9246   Imported_Project'Source_Dirs
9247   Imported_Project.Naming'Casing
9248   Builder'Default_Switches("Ada")
9249 @end smallexample
9250
9251 @noindent
9252 The entity may be:
9253 @itemize @bullet
9254 @item @code{project} for an attribute of the current project
9255 @item The name of an existing package of the current project
9256 @item The name of an imported project
9257 @item The name of a parent project (extended by the current project)
9258 @item An imported/parent project name, followed by a dot,
9259       followed by a package name
9260 @end itemize
9261
9262 @noindent
9263 Example:
9264 @smallexample
9265 @group
9266    project Prj is
9267      for Source_Dirs use project'Source_Dirs & "units";
9268      for Source_Dirs use project'Source_Dirs & "test/drivers"
9269    end Prj;
9270 @end group
9271 @end smallexample
9272
9273 @noindent
9274 In the first attribute declaration, initially the attribute @code{Source_Dirs}
9275 has the default value: an empty string list. After this declaration,
9276 @code{Source_Dirs} is a string list of one element: "units".
9277 After the second attribute declaration @code{Source_Dirs} is a string list of
9278 two elements: "units" and "test/drivers".
9279
9280 Note: this example is for illustration only. In practice,
9281 the project file would contain only one attribute declaration:
9282
9283 @smallexample
9284    for Source_Dirs use ("units", "test/drivers");
9285 @end smallexample
9286
9287
9288 @node Associative Array Attributes
9289 @subsection Associative Array Attributes
9290
9291 @noindent
9292 Some attributes are defined as @emph{associative arrays}. An associative
9293 array may be regarded as a function that takes a string as a parameter
9294 and delivers a string or string list value as its result.
9295
9296 Here are some examples of associative array attribute declarations:
9297
9298 @smallexample
9299    for Implementation ("main") use "Main.ada";
9300    for Switches ("main.ada") use ("-v", "-gnatv");
9301    for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g";
9302 @end smallexample
9303
9304 @noindent
9305 Like untyped variables and simple attributes, associative array attributes may be declared several times. Each declaration supplies a new value for the
9306 attribute, replacing the previous setting.
9307
9308
9309 @node case Constructions
9310 @subsection @code{case} Constructions
9311
9312 @noindent
9313 A @code{case} construction is used in a project file to effect conditional
9314 behavior.
9315 Here is a typical example:
9316
9317 @smallexample
9318 @group
9319 project MyProj is
9320    type OS_Type is ("Linux", "Unix", "NT", "VMS");
9321
9322    OS : OS_Type := external ("OS", "Linux");
9323 @end group
9324
9325 @group
9326    package Compiler is
9327      case OS is
9328        when "Linux" | "Unix" =>
9329          for Default_Switches ("Ada") use ("-gnath");
9330        when "NT" =>
9331          for Default_Switches ("Ada") use ("-gnatP");
9332        when others =>
9333      end case;
9334    end Compiler;
9335 end MyProj;
9336 @end group
9337 @end smallexample
9338
9339 @noindent
9340 The syntax of a @code{case} construction is based on the Ada case statement
9341 (although there is no @code{null} construction for empty alternatives).
9342
9343 Following the reserved word @code{case} there is the case variable (a typed
9344 string variable), the reserved word @code{is}, and then a sequence of one or
9345 more alternatives.
9346 Each alternative comprises the reserved word @code{when}, either a list of
9347 literal strings separated by the @code{"|"} character or the reserved word
9348 @code{others},  and the @code{"=>"} token.
9349 Each literal string must belong to the string type that is the type of the
9350 case variable.
9351 An @code{others} alternative, if present, must occur last.
9352 The @code{end case;} sequence terminates the case construction.
9353
9354 After each @code{=>}, there are zero or more constructions.  The only
9355 constructions allowed in a case construction are other case constructions and
9356 attribute declarations. String type declarations, variable declarations and
9357 package declarations are not allowed.
9358
9359 The value of the case variable is often given by an external reference
9360 (see @ref{External References in Project Files}).
9361
9362
9363 @c ****************************************
9364 @c * Objects and Sources in Project Files *
9365 @c ****************************************
9366
9367 @node Objects and Sources in Project Files
9368 @section Objects and Sources in Project Files
9369
9370 @menu
9371 * Object Directory::
9372 * Exec Directory::
9373 * Source Directories::
9374 * Source File Names::
9375 @end menu
9376
9377 @noindent
9378 Each project has exactly one object directory and one or more source
9379 directories. The source directories must contain at least one source file,
9380 unless  the project file explicitly specifies that no source files are present
9381 (see @ref{Source File Names}).
9382
9383
9384 @node Object Directory
9385 @subsection Object Directory
9386
9387 @noindent
9388 The object directory for a project is the directory containing the compiler's
9389 output (such as @file{ALI} files and object files) for the project's immediate
9390 sources. Note that for inherited sources (when extending a parent project) the
9391 parent project's object directory is used.
9392
9393 The object directory is given by the value of the attribute @code{Object_Dir}
9394 in the project file.
9395
9396 @smallexample
9397    for Object_Dir use "objects";
9398 @end smallexample
9399
9400 @noindent
9401 The attribute @var{Object_Dir} has a string value, the path name of the object
9402 directory. The path name may be absolute or relative to the directory of the
9403 project file. This directory must already exist, and be readable and writable.
9404
9405 By default, when the attribute @code{Object_Dir} is not given an explicit value
9406 or when its value is the empty string, the object directory is the same as the
9407 directory containing the project file.
9408
9409
9410 @node Exec Directory
9411 @subsection Exec Directory
9412
9413 @noindent
9414 The exec directory for a project is the directory containing the executables
9415 for the project's main subprograms.
9416
9417 The exec directory is given by the value of the attribute @code{Exec_Dir}
9418 in the project file.
9419
9420 @smallexample
9421    for Exec_Dir use "executables";
9422 @end smallexample
9423
9424 @noindent
9425 The attribute @var{Exec_Dir} has a string value, the path name of the exec
9426 directory. The path name may be absolute or relative to the directory of the
9427 project file. This directory must already exist, and be writable.
9428
9429 By default, when the attribute @code{Exec_Dir} is not given an explicit value
9430 or when its value is the empty string, the exec directory is the same as the
9431 object directory of the project file.
9432
9433
9434 @node Source Directories
9435 @subsection Source Directories
9436
9437 @noindent
9438 The source directories of a project are specified by the project file
9439 attribute @code{Source_Dirs}.
9440
9441 This attribute's value is a string list. If the attribute is not given an
9442 explicit value, then there is only one source directory, the one where the
9443 project file resides.
9444
9445 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
9446 as in
9447
9448 @smallexample
9449     for Source_Dirs use ();
9450 @end smallexample
9451
9452 @noindent
9453 indicates that the project contains no source files.
9454
9455 Otherwise, each string in the string list designates one or more
9456 source directories.
9457
9458 @smallexample
9459    for Source_Dirs use ("sources", "test/drivers");
9460 @end smallexample
9461
9462 @noindent
9463 If a string in the list ends with @code{"/**"},  then the directory whose path
9464 name precedes the two asterisks, as well as all its subdirectories
9465 (recursively), are source directories.
9466
9467 @smallexample
9468    for Source_Dirs use ("/system/sources/**");
9469 @end smallexample
9470
9471 @noindent
9472 Here the directory @code{/system/sources} and all of its subdirectories
9473 (recursively) are source directories.
9474
9475 To specify that the source directories are the directory of the project file
9476 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
9477 @smallexample
9478    for Source_Dirs use ("./**");
9479 @end smallexample
9480
9481 @noindent
9482 Each of the source directories must exist and be readable.
9483
9484
9485 @node Source File Names
9486 @subsection Source File Names
9487
9488 @noindent
9489 In a project that contains source files, their names may be specified by the
9490 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
9491 (a string). Source file names never include any directory information.
9492
9493 If the attribute @code{Source_Files} is given an explicit value, then each
9494 element of the list is a source file name.
9495
9496 @smallexample
9497    for Source_Files use ("main.adb");
9498    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
9499 @end smallexample
9500
9501 @noindent
9502 If the attribute @code{Source_Files} is not given an explicit value,
9503 but the attribute @code{Source_List_File} is given a string value,
9504 then the source file names are contained in the text file whose path name
9505 (absolute or relative to the directory of the project file) is the
9506 value of the attribute @code{Source_List_File}.
9507
9508 Each line in the file that is not empty or is not a comment
9509 contains a source file name. A comment line starts with two hyphens.
9510
9511 @smallexample
9512    for Source_List_File use "source_list.txt";
9513 @end smallexample
9514
9515 @noindent
9516 By default, if neither the attribute @code{Source_Files} nor the attribute
9517 @code{Source_List_File} is given an explicit value, then each file in the
9518 source directories that conforms to the project's naming scheme
9519 (see @ref{Naming Schemes}) is an immediate source of the project.
9520
9521 A warning is issued if both attributes @code{Source_Files} and
9522 @code{Source_List_File} are given explicit values. In this case, the attribute
9523 @code{Source_Files} prevails.
9524
9525 Each source file name must be the name of one and only one existing source file
9526 in one of the source directories.
9527
9528 A @code{Source_Files} attribute defined with an empty list as its value
9529 indicates that there are no source files in the project.
9530
9531 Except for projects that are clearly specified as containing no Ada source
9532 files (@code{Source_Dirs} or @code{Source_Files} specified as an empty list,
9533 or @code{Languages} specified without @code{"Ada"} in the list)
9534 @smallexample
9535    for Source_Dirs use ();
9536    for Source_Files use ();
9537    for Languages use ("C", "C++");
9538 @end smallexample
9539
9540 @noindent
9541 a project must contain at least one immediate source.
9542
9543 Projects with no source files are useful as template packages
9544 (see @ref{Packages in Project Files}) for other projects; in particular to
9545 define a package @code{Naming} (see @ref{Naming Schemes}).
9546
9547
9548 @c ****************************
9549 @c * Importing Projects *
9550 @c ****************************
9551
9552 @node  Importing Projects
9553 @section Importing Projects
9554
9555 @noindent
9556 An immediate source of a project P may depend on source files that
9557 are neither immediate sources of P nor in the predefined library.
9558 To get this effect, P must @emph{import} the projects that contain the needed
9559 source files.
9560
9561 @smallexample
9562 @group
9563   with "project1", "utilities.gpr";
9564   with "/namings/apex.gpr";
9565   project Main is
9566     ...
9567 @end group
9568 @end smallexample
9569
9570 @noindent
9571 As can be seen in this example, the syntax for importing projects is similar
9572 to the syntax for importing compilation units in Ada. However, project files
9573 use literal strings instead of names, and the @code{with} clause identifies
9574 project files rather than packages.
9575
9576 Each literal string is the file name or path name (absolute or relative) of a
9577 project file. If a string is simply a file name, with no path, then its
9578 location is determined by the @emph{project path}:
9579
9580 @itemize @bullet
9581 @item
9582 If the environment variable @env{ADA_PROJECT_PATH} exists, then the project
9583 path includes all the directories in this environment variable, plus the
9584 directory of the project file.
9585
9586 @item
9587 If the environment variable @env{ADA_PROJECT_PATH} does not exist,
9588 then the project path contains only one directory, namely the one where
9589 the project file is located.
9590 @end itemize
9591
9592 @noindent
9593 If a relative pathname is used as in
9594
9595 @smallexample
9596   with "tests/proj";
9597 @end smallexample
9598
9599 @noindent
9600 then the path is relative to the directory where the importing project file is
9601 located. Any symbolic link will be fully resolved in the directory
9602 of the importing project file before the imported project file is looked up.
9603
9604 When the @code{with}'ed project file name does not have an extension,
9605 the default is @file{.gpr}. If a file with this extension is not found, then
9606 the file name as specified in the @code{with} clause (no extension) will be
9607 used. In the above example, if a file @code{project1.gpr} is found, then it
9608 will be used; otherwise, if a file @code{project1} exists then it will be used;
9609 if neither file exists, this is an error.
9610
9611 A warning is issued if the name of the project file does not match the
9612 name of the project; this check is case insensitive.
9613
9614 Any source file that is an immediate source of the imported project can be
9615 used by the immediate sources of the importing project, and recursively. Thus
9616 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
9617 sources of @code{A} may depend on the immediate sources of @code{C}, even if
9618 @code{A} does not import @code{C} explicitly. However, this is not recommended,
9619 because if and when @code{B} ceases to import @code{C}, some sources in
9620 @code{A} will no longer compile.
9621
9622 A side effect of this capability is that cyclic dependences are not permitted:
9623 if @code{A} imports @code{B} (directly or indirectly) then @code{B} is not
9624 allowed to import @code{A}.
9625
9626
9627 @c *********************
9628 @c * Project Extension *
9629 @c *********************
9630
9631 @node Project Extension
9632 @section Project Extension
9633
9634 @noindent
9635 During development of a large system, it is sometimes necessary to use
9636 modified versions of some of the source files without changing the original
9637 sources. This can be achieved through a facility known as
9638 @emph{project extension}.
9639
9640 @smallexample
9641    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
9642 @end smallexample
9643
9644 @noindent
9645 The project file for the project being extended (the @emph{parent}) is
9646 identified by the literal string that follows the reserved word @code{extends},
9647 which itself follows the name of the extending project (the @emph{child}).
9648
9649 By default, a child project inherits all the sources of its parent.
9650 However, inherited sources can be overridden: a unit with the same name as one
9651 in the parent will hide the original unit.
9652 Inherited sources are considered to be sources (but not immediate sources)
9653 of the child project; see @ref{Project File Syntax}.
9654
9655 An inherited source file retains any switches specified in the parent project.
9656
9657 For example if the project @code{Utilities} contains the specification and the
9658 body of an Ada package @code{Util_IO}, then the project
9659 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
9660 The original body of @code{Util_IO} will not be considered in program builds.
9661 However, the package specification will still be found in the project
9662 @code{Utilities}.
9663
9664 A child project can have only one parent but it may import any number of other
9665 projects.
9666
9667 A project is not allowed to import directly or indirectly at the same time a
9668 child project and any of its ancestors.
9669
9670
9671 @c ****************************************
9672 @c * External References in Project Files *
9673 @c ****************************************
9674
9675 @node  External References in Project Files
9676 @section External References in Project Files
9677
9678 @noindent
9679 A project file may contain references to external variables; such references
9680 are called @emph{external references}.
9681
9682 An external variable is either defined as part of the environment (an
9683 environment variable in Unix, for example) or else specified on the command
9684 line via the @option{-X@emph{vbl}=@emph{value}} switch. If both, then the
9685 command line value is used.
9686
9687 An external reference is denoted by the built-in function
9688 @code{external}, which returns a string value.  This function has two forms:
9689 @itemize @bullet
9690 @item @code{external (external_variable_name)}
9691 @item @code{external (external_variable_name, default_value)}
9692 @end itemize
9693
9694 @noindent
9695 Each parameter must be a string literal.  For example:
9696
9697 @smallexample
9698    external ("USER")
9699    external ("OS", "Linux")
9700 @end smallexample
9701
9702 @noindent
9703 In the form with one parameter, the function returns the value of
9704 the external variable given as parameter. If this name is not present in the
9705 environment, then the returned value is an empty string.
9706
9707 In the form with two string parameters, the second parameter is
9708 the value returned when the variable given as the first parameter is not
9709 present in the environment. In the example above, if @code{"OS"} is not
9710 the name of an environment variable and is not passed on the command line,
9711 then the returned value will be @code{"Linux"}.
9712
9713 An external reference may be part of a string expression or of a string
9714 list expression, to define variables or attributes.
9715
9716 @smallexample
9717 @group
9718    type Mode_Type is ("Debug", "Release");
9719    Mode : Mode_Type := external ("MODE");
9720    case Mode is
9721      when "Debug" =>
9722         ...
9723 @end group
9724 @end smallexample
9725
9726
9727 @c *****************************
9728 @c * Packages in Project Files *
9729 @c *****************************
9730
9731 @node  Packages in Project Files
9732 @section Packages in Project Files
9733
9734 @noindent
9735 The @emph{package} is the project file feature that defines the settings for
9736 project-aware tools.
9737 For each such tool you can declare a corresponding package; the names for these
9738 packages are preset (see @ref{Packages}) but are not case sensitive.
9739 A package may contain variable declarations, attribute declarations, and case
9740 constructions.
9741
9742 @smallexample
9743 @group
9744    project Proj is
9745       package Builder is  -- used by gnatmake
9746          for Default_Switches ("Ada") use ("-v", "-g");
9747       end Builder;
9748    end Proj;
9749 @end group
9750 @end smallexample
9751
9752 @noindent
9753 A package declaration starts with the reserved word @code{package},
9754 followed by the package name (case insensitive), followed by the reserved word
9755 @code{is}. It ends with the reserved word @code{end}, followed by the package
9756 name, finally followed by a semi-colon.
9757
9758 Most of the packages have an attribute @code{Default_Switches}.
9759 This attribute is an associative array, and its value is a string list.
9760 The index of the associative array is the name of a programming language (case
9761 insensitive). This attribute indicates the switch or switches to be used
9762 with the corresponding tool.
9763
9764 Some packages also have another attribute, @code{Switches}, an associative
9765 array whose value is a string list. The index is the name of a source file.
9766 This attribute indicates the switch or switches to be used by the corresponding
9767 tool when dealing with this specific file.
9768
9769 Further information on these switch-related attributes is found in
9770 @ref{Switches and Project Files}.
9771
9772 A package may be declared as a @emph{renaming} of another package; e.g., from
9773 the project file for an imported project.
9774
9775 @smallexample
9776 @group
9777   with "/global/apex.gpr";
9778   project Example is
9779     package Naming renames Apex.Naming;
9780     ...
9781   end Example;
9782 @end group
9783 @end smallexample
9784
9785 @noindent
9786 Packages that are renamed in other project files often come from project files
9787 that have no sources: they are just used as templates. Any modification in the
9788 template will be reflected automatically in all the project files that rename
9789 a package from the template.
9790
9791 In addition to the tool-oriented packages, you can also declare a package
9792 named @code{Naming} to establish specialized source file naming conventions
9793 (see @ref{Naming Schemes}).
9794
9795
9796 @c ************************************
9797 @c * Variables from Imported Projects *
9798 @c ************************************
9799
9800 @node Variables from Imported Projects
9801 @section Variables from Imported Projects
9802
9803 @noindent
9804 An attribute or variable defined in an imported or parent project can
9805 be used in expressions in the importing / extending project.
9806 Such an attribute or variable is prefixed with the name of the project
9807 and (if relevant) the name of package where it is defined.
9808
9809 @smallexample
9810 @group
9811   with "imported";
9812   project Main extends "base" is
9813      Var1 := Imported.Var;
9814      Var2 := Base.Var & ".new";
9815 @end group
9816
9817 @group
9818      package Builder is
9819         for Default_Switches ("Ada") use Imported.Builder.Ada_Switches &
9820                          "-gnatg" & "-v";
9821      end Builder;
9822 @end group
9823
9824 @group
9825      package Compiler is
9826         for Default_Switches ("Ada") use Base.Compiler.Ada_Switches;
9827      end Compiler;
9828   end Main;
9829 @end group
9830 @end smallexample
9831
9832 @noindent
9833 In this example:
9834
9835 @itemize @bullet
9836 @item
9837 @code{Var1} is a copy of the variable @code{Var} defined in the project file
9838 @file{"imported.gpr"}
9839 @item
9840 the value of @code{Var2} is a copy of the value of variable @code{Var}
9841 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
9842 @item
9843 attribute @code{Default_Switches ("Ada")} in package @code{Builder}
9844 is a string list that includes in its value a copy of variable
9845 @code{Ada_Switches} defined in the @code{Builder} package in project file
9846 @file{imported.gpr} plus two new elements: @option{"-gnatg"} and @option{"-v"};
9847 @item
9848 attribute @code{Default_Switches ("Ada")} in package @code{Compiler}
9849 is a copy of the variable @code{Ada_Switches} defined in the @code{Compiler}
9850 package in project file @file{base.gpr}, the project being extended.
9851 @end itemize
9852
9853
9854 @c ******************
9855 @c * Naming Schemes *
9856 @c ******************
9857
9858 @node  Naming Schemes
9859 @section Naming Schemes
9860
9861 @noindent
9862 Sometimes an Ada software system is ported from a foreign compilation
9863 environment to GNAT, with file names that do not use the default GNAT
9864 conventions. Instead of changing all the file names (which for a variety of
9865 reasons might not be possible), you can define the relevant file naming scheme
9866 in the @code{Naming} package in your project file.  For example, the following
9867 package models the Apex file naming rules:
9868
9869 @smallexample
9870 @group
9871   package Naming is
9872     for Casing                        use "lowercase";
9873     for Dot_Replacement               use ".";
9874     for Specification_Suffix ("Ada")  use ".1.ada";
9875     for Implementation_Suffix ("Ada") use ".2.ada";
9876   end Naming;
9877 @end group
9878 @end smallexample
9879
9880 @noindent
9881 You can define the following attributes in package @code{Naming}:
9882
9883 @table @code
9884
9885 @item @var{Casing}
9886 This must be a string with one of the three values @code{"lowercase"},
9887 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
9888
9889 @noindent
9890 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
9891
9892 @item @var{Dot_Replacement}
9893 This must be a string whose value satisfies the following conditions:
9894
9895 @itemize @bullet
9896 @item It must not be empty
9897 @item It cannot start or end with an alphanumeric character
9898 @item It cannot be a single underscore
9899 @item It cannot start with an underscore followed by an alphanumeric
9900 @item It cannot contain a dot @code{'.'} except if it the entire string is @code{"."}
9901 @end itemize
9902
9903 @noindent
9904 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
9905
9906 @item @var{Specification_Suffix}
9907 This is an associative array (indexed by the programming language name, case
9908 insensitive) whose value is a string that must satisfy the following
9909 conditions:
9910
9911 @itemize @bullet
9912 @item It must not be empty
9913 @item It cannot start with an alphanumeric character
9914 @item It cannot start with an underscore followed by an alphanumeric character
9915 @end itemize
9916 @noindent
9917 If @code{Specification_Suffix ("Ada")} is not specified, then the default is
9918 @code{".ads"}.
9919
9920 @item @var{Implementation_Suffix}
9921 This is an associative array (indexed by the programming language name, case
9922 insensitive) whose value is a string that must satisfy the following
9923 conditions:
9924
9925 @itemize @bullet
9926 @item It must not be empty
9927 @item It cannot start with an alphanumeric character
9928 @item It cannot start with an underscore followed by an alphanumeric character
9929 @item It cannot be a suffix of @code{Specification_Suffix}
9930 @end itemize
9931 @noindent
9932 If @code{Implementation_Suffix ("Ada")} is not specified, then the default is
9933 @code{".adb"}.
9934
9935 @item @var{Separate_Suffix}
9936 This must be a string whose value satisfies the same conditions as
9937 @code{Implementation_Suffix}.
9938
9939 @noindent
9940 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
9941 value as @code{Implementation_Suffix ("Ada")}.
9942
9943 @item @var{Specification}
9944 @noindent
9945 You can use the @code{Specification} attribute, an associative array, to define
9946 the source file name for an individual Ada compilation unit's spec. The array
9947 index must be a string literal that identifies the Ada unit (case insensitive).
9948 The value of this attribute must be a string that identifies the file that
9949 contains this unit's spec (case sensitive or insensitive depending on the
9950 operating system).
9951
9952 @smallexample
9953    for Specification ("MyPack.MyChild") use "mypack.mychild.spec";
9954 @end smallexample
9955
9956 @item @var{Implementation}
9957
9958 You can use the @code{Implementation} attribute, an associative array, to
9959 define the source file name for an individual Ada compilation unit's body
9960 (possibly a subunit).  The array index must be a string literal that identifies
9961 the Ada unit (case insensitive).  The value of this attribute must be a string
9962 that identifies the file that contains this unit's body or subunit (case
9963 sensitive or insensitive depending on the operating system).
9964
9965 @smallexample
9966    for Implementation ("MyPack.MyChild") use "mypack.mychild.body";
9967 @end smallexample
9968 @end table
9969
9970
9971 @c ********************
9972 @c * Library Projects *
9973 @c ********************
9974
9975 @node Library Projects
9976 @section Library Projects
9977
9978 @noindent
9979 @emph{Library projects} are projects whose object code is placed in a library.
9980 (Note that this facility is not yet supported on all platforms)
9981
9982 To create a library project, you need to define in its project file
9983 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
9984 Additionally, you may define the library-related attributes
9985 @code{Library_Kind}, @code{Library_Version} and @code{Library_Elaboration}.
9986
9987 The @code{Library_Name} attribute has a string value that must start with a
9988 letter and include only letters and digits.
9989
9990 The @code{Library_Dir} attribute has a string value that designates the path
9991 (absolute or relative) of the directory where the library will reside.
9992 It must designate an existing directory, and this directory needs to be
9993 different from the project's object directory. It also needs to be writable.
9994
9995 If both @code{Library_Name} and @code{Library_Dir} are specified and
9996 are legal, then the project file defines a library project.  The optional
9997 library-related attributes are checked only for such project files.
9998
9999 The @code{Library_Kind} attribute has a string value that must be one of the
10000 following (case insensitive): @code{"static"}, @code{"dynamic"} or
10001 @code{"relocatable"}. If this attribute is not specified, the library is a
10002 static library. Otherwise, the library may be dynamic or relocatable.
10003 Depending on the operating system, there may or may not be a distinction
10004 between dynamic and relocatable libraries. For example, on Unix there is no
10005 such distinction.
10006
10007 The @code{Library_Version} attribute has a string value whose interpretation
10008 is platform dependent. On Unix, it is used only for dynamic/relocatable
10009 libraries as the internal name of the library (the @code{"soname"}). If the
10010 library file name (built from the @code{Library_Name}) is different from the
10011 @code{Library_Version}, then the library file will be a symbolic link to the
10012 actual file whose name will be @code{Library_Version}.
10013
10014 Example (on Unix):
10015
10016 @smallexample
10017 @group
10018 project Plib is
10019
10020    Version := "1";
10021
10022    for Library_Dir use "lib_dir";
10023    for Library_Name use "dummy";
10024    for Library_Kind use "relocatable";
10025    for Library_Version use "libdummy.so." & Version;
10026
10027 end Plib;
10028 @end group
10029 @end smallexample
10030
10031 @noindent
10032 Directory @file{lib_dir} will contain the internal library file whose name
10033 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
10034 @file{libdummy.so.1}.
10035
10036 When @command{gnatmake} detects that a project file (not the main project file)
10037 is a library project file, it will check all immediate sources of the project
10038 and rebuild the library if any of the sources have been recompiled.
10039 All @file{ALI} files will also be copied from the object directory to the
10040 library directory. To build executables, @command{gnatmake} will use the
10041 library rather than the individual object files.
10042
10043
10044 @c *************************************
10045 @c * Switches Related to Project Files *
10046 @c *************************************
10047 @node Switches Related to Project Files
10048 @section Switches Related to Project Files
10049
10050 @noindent
10051 The following switches are used by GNAT tools that support project files:
10052
10053 @table @code
10054
10055 @item @option{-P@var{project}}
10056 Indicates the name of a project file. This project file will be parsed with
10057 the verbosity indicated by @option{-vP@emph{x}}, if any, and using the external
10058 references indicated by @option{-X} switches, if any.
10059
10060 @noindent
10061 There must be only one @option{-P} switch on the command line.
10062
10063 @noindent
10064 Since the Project Manager parses the project file only after all the switches
10065 on the command line are checked, the order of the switches @option{-P},
10066 @option{-Vp@emph{x}} or @option{-X} is not significant.
10067
10068 @item @option{-X@var{name=value}}
10069 Indicates that external variable @var{name} has the value @var{value}.
10070 The Project Manager will use this value for occurrences of
10071 @code{external(name)} when parsing the project file.
10072
10073 @noindent
10074 If @var{name} or @var{value} includes a space, then @var{name=value} should be
10075 put between quotes.
10076 @smallexample
10077   -XOS=NT
10078   -X"user=John Doe"
10079 @end smallexample
10080
10081 @noindent
10082 Several @option{-X} switches can be used simultaneously.
10083 If several @option{-X} switches specify the same @var{name}, only the last one
10084 is used.
10085
10086 @noindent
10087 An external variable specified with a @option{-X} switch takes precedence
10088 over the value of the same name in the environment.
10089
10090 @item @option{-vP@emph{x}}
10091 Indicates the verbosity of the parsing of GNAT project files.
10092 @option{-vP0} means Default (no output for syntactically correct project
10093 files);
10094 @option{-vP1} means Medium;
10095 @option{-vP2} means High.
10096 @noindent
10097 The default is Default.
10098 @noindent
10099 If several @option{-vP@emph{x}} switches are present, only the last one is
10100 used.
10101
10102 @end table
10103
10104
10105 @c **********************************
10106 @c * Tools Supporting Project Files *
10107 @c **********************************
10108
10109 @node  Tools Supporting Project Files
10110 @section Tools Supporting Project Files
10111
10112 @menu
10113 * gnatmake and Project Files::
10114 * The GNAT Driver and Project Files::
10115 * Glide and Project Files::
10116 @end menu
10117
10118 @node gnatmake and Project Files
10119 @subsection gnatmake and Project Files
10120
10121 @noindent
10122 This section covers two topics related to @command{gnatmake} and project files:
10123 defining switches for @command{gnatmake} and for the tools that it invokes;
10124 and the use of the @code{Main} attribute.
10125
10126 @menu
10127 * Switches and Project Files::
10128 * Project Files and Main Subprograms::
10129 @end menu
10130
10131 @node Switches and Project Files
10132 @subsubsection Switches and Project Files
10133
10134 @noindent
10135 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
10136 @code{Linker}, you can specify a @code{Default_Switches} attribute, a
10137 @code{Switches} attribute, or both; as their names imply, these switch-related
10138 attributes affect which switches are used for which files when
10139 @command{gnatmake} is invoked.  As will be explained below, these
10140 package-contributed switches precede the switches passed on the
10141 @command{gnatmake} command line.
10142
10143 The @code{Default_Switches} attribute is an associative array indexed by
10144 language name (case insensitive) and returning a string list.  For example:
10145
10146 @smallexample
10147 @group
10148 package Compiler is
10149   for Default_Switches ("Ada") use ("-gnaty", "-v");
10150 end Compiler;
10151 @end group
10152 @end smallexample
10153
10154 @noindent
10155 The @code{Switches} attribute is also an associative array, indexed by a file
10156 name (which may or may not be case sensitive, depending on the operating
10157 system) and returning a string list.  For example:
10158
10159 @smallexample
10160 @group
10161 package Builder is
10162    for Switches ("main1.adb") use ("-O2");
10163    for Switches ("main2.adb") use ("-g");
10164 end Builder;
10165 @end group
10166 @end smallexample
10167
10168 @noindent
10169 For the @code{Builder} package, the file names should designate source files
10170 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
10171 file names should designate @file{ALI} or source files for main subprograms.
10172 In each case just the file name (without explicit extension) is acceptable.
10173
10174 For each tool used in a program build (@command{gnatmake}, the compiler, the
10175 binder, and the linker), its corresponding package @dfn{contributes} a set of
10176 switches for each file on which the tool is invoked, based on the
10177 switch-related attributes defined in the package. In particular, the switches
10178 that each of these packages contributes for a given file @var{f} comprise:
10179
10180 @itemize @bullet
10181 @item
10182 the value of attribute @code{Switches (@var{f})}, if it is specified in the
10183 package for the given file,
10184 @item
10185 otherwise, the value of @code{Default_Switches ("Ada")}, if it is specified in
10186 the package.
10187 @end itemize
10188
10189 @noindent
10190 If neither of these attributes is defined in the package, then the package does
10191 not contribute any switches for the given file.
10192
10193 When @command{gnatmake} is invoked on a file, the switches comprise two sets,
10194 in the following order: those contributed for the file by the @code{Builder}
10195 package; and the switches passed on the command line.
10196
10197 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
10198 the switches passed to the tool comprise three sets, in the following order:
10199
10200 @enumerate
10201 @item
10202 the applicable switches contributed for the file by the @code{Builder} package
10203 in the project file supplied on the command line;
10204
10205 @item
10206 those contributed for the file by the package (in the relevant project file --
10207 see below) corresponding to the tool; and
10208
10209 @item
10210 the applicable switches passed on the command line.
10211 @end enumerate
10212
10213 @noindent
10214 The term @emph{applicable switches} reflects the fact that @command{gnatmake}
10215 switches may or may not be passed to individual tools, depending on the
10216 individual switch.
10217
10218 @command{gnatmake} may invoke the compiler on source files from different
10219 projects. The Project Manager will use the appropriate project file to
10220 determine the @code{Compiler} package for each source file being compiled.
10221 Likewise for the @code{Binder} and @code{Linker} packages.
10222
10223 As an example, consider the following package in a project file:
10224
10225 @smallexample
10226 @group
10227 project Proj1 is
10228    package Compiler is
10229       for Default_Switches ("Ada") use ("-g");
10230       for Switches ("a.adb") use ("-O1");
10231       for Switches ("b.adb") use ("-O2", "-gnaty");
10232    end Compiler;
10233 end Proj1;
10234 @end group
10235 @end smallexample
10236
10237 @noindent
10238 If @command{gnatmake} is invoked with this project file, and it needs to
10239 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
10240 @file{a.adb} will be compiled with the switch @option{-O1}, @file{b.adb}
10241 with switches @option{-O2} and @option{-gnaty}, and @file{c.adb} with
10242 @option{-g}.
10243
10244 Another example illustrates the ordering of the switches contributed by
10245 different packages:
10246
10247 @smallexample
10248 @group
10249 project Proj2 is
10250    package Builder is
10251       for Switches ("main.adb") use ("-g", "-O1", "-f");
10252    end Builder;
10253 @end group
10254
10255 @group
10256    package Compiler is
10257       for Switches ("main.adb") use ("-O2");
10258    end Compiler;
10259 end Proj2;
10260 @end group
10261 @end smallexample
10262
10263 @noindent
10264 If you issue the command:
10265
10266 @smallexample
10267     gnatmake -PProj2 -O0 main
10268 @end smallexample
10269
10270 @noindent
10271 then the compiler will be invoked on @file{main.adb} with the following sequence of switches
10272
10273 @smallexample
10274    -g -O1 -O2 -O0
10275 @end smallexample
10276
10277 with the last @option{-O} switch having precedence over the earlier ones;
10278 several other switches (such as @option{-c}) are added implicitly.
10279
10280 The switches @option{-g} and @option{-O1} are contributed by package
10281 @code{Builder},  @option{-O2} is contributed by the package @code{Compiler}
10282 and @option{-O0} comes from the command line.
10283
10284 The @option{-g} switch will also be passed in the invocation of
10285 @command{gnatlink.}
10286
10287 A final example illustrates switch contributions from packages in different
10288 project files:
10289
10290 @smallexample
10291 @group
10292 project Proj3 is
10293    for Source_Files use ("pack.ads", "pack.adb");
10294    package Compiler is
10295       for Default_Switches ("Ada") use ("-gnata");
10296    end Compiler;
10297 end Proj3;
10298 @end group
10299
10300 @group
10301 with "Proj3";
10302 project Proj4 is
10303    for Source_Files use ("foo_main.adb", "bar_main.adb");
10304    package Builder is
10305       for Switches ("foo_main.adb") use ("-s", "-g");
10306    end Builder;
10307 end Proj4;
10308 @end group
10309
10310 @group
10311 -- Ada source file:
10312 with Pack;
10313 procedure Foo_Main is
10314    ...
10315 end Foo_Main;
10316 @end group
10317 @end smallexample
10318
10319 If the command is
10320 @smallexample
10321 gnatmake -PProj4 foo_main.adb -cargs -gnato
10322 @end smallexample
10323
10324 @noindent
10325 then the switches passed to the compiler for @file{foo_main.adb} are
10326 @option{-g} (contributed by the package @code{Proj4.Builder}) and
10327 @option{-gnato} (passed on the command line).
10328 When the imported package @code{Pack} is compiled, the switches used are
10329 @option{-g} from @code{Proj4.Builder}, @option{-gnata} (contributed from
10330 package @code{Proj3.Compiler}, and @option{-gnato} from the command line.
10331
10332
10333 @node Project Files and Main Subprograms
10334 @subsubsection Project Files and Main Subprograms
10335
10336 @noindent
10337 When using a project file, you can invoke @command{gnatmake}
10338 with several main subprograms, by specifying their source files on the command
10339 line.  Each of these needs to be an immediate source file of the project.
10340
10341 @smallexample
10342     gnatmake -Pprj main1 main2 main3
10343 @end smallexample
10344
10345 @noindent
10346 When using a project file, you can also invoke @command{gnatmake} without
10347 explicitly specifying any main, and the effect depends on whether you have
10348 defined the @code{Main} attribute.  This attribute has a string list value,
10349 where each element in the list is the name of a source file (the file
10350 extension is optional) containing a main subprogram.
10351
10352 If the @code{Main} attribute is defined in a project file as a non-empty
10353 string list and the switch @option{-u} is not used on the command line, then
10354 invoking @command{gnatmake} with this project file but without any main on the
10355 command line is equivalent to invoking @command{gnatmake} with all the file
10356 names in the @code{Main} attribute on the command line.
10357
10358 Example:
10359 @smallexample
10360 @group
10361    project Prj is
10362       for Main use ("main1", "main2", "main3");
10363    end Prj;
10364 @end group
10365 @end smallexample
10366
10367 @noindent
10368 With this project file, @code{"gnatmake -Pprj"} is equivalent to
10369 @code{"gnatmake -Pprj main1 main2 main3"}.
10370
10371 When the project attribute @code{Main} is not specified, or is specified
10372 as an empty string list, or when the switch @option{-u} is used on the command
10373 line, then invoking @command{gnatmake} with no main on the command line will
10374 result in all immediate sources of the project file being checked, and
10375 potentially recompiled. Depending on the presence of the switch @option{-u},
10376 sources from other project files on which the immediate sources of the main
10377 project file depend are also checked and potentially recompiled. In other
10378 words, the @option{-u} switch is applied to all of the immediate sources of themain project file.
10379
10380
10381 @node The GNAT Driver and Project Files
10382 @subsection The GNAT Driver and Project Files
10383
10384 @noindent
10385 A number of GNAT tools, other than @command{gnatmake} are project-aware:
10386 @command{gnatbind}, @command{gnatfind}, @command{gnatlink}, @command{gnatls}
10387 and @command{gnatxref}. However, none of these tools can be invoked directly
10388 with a project file switch (@code{-P}). They need to be invoke through the
10389 @command{gnat} driver.
10390
10391 The @command{gnat} driver is a front-end that accepts a number of commands and
10392 call the corresponding tool. It has been designed initially for VMS to convert
10393 VMS style qualifiers to Unix style switches, but it is now available to all
10394 the GNAT supported platforms.
10395
10396 On non VMS platforms, the @command{gnat} driver accepts the following commands
10397 (case insensitive):
10398
10399 @itemize @bullet
10400 @item
10401 BIND to invoke @command{gnatbind}
10402 @item
10403 CHOP to invoke @command{gnatchop}
10404 @item
10405 COMP or COMPILE to invoke the compiler
10406 @item
10407 ELIM to invoke @command{gnatelim}
10408 @item
10409 FIND to invoke @command{gnatfind}
10410 @item
10411 KR or KRUNCH to invoke @command{gnatkr}
10412 @item
10413 LINK to invoke @command{gnatlink}
10414 @item
10415 LS or LIST to invoke @command{gnatls}
10416 @item
10417 MAKE to invoke @command{gnatmake}
10418 @item
10419 NAME to invoke @command{gnatname}
10420 @item
10421 PREP or PREPROCESS to invoke @command{gnatprep}
10422 @item
10423 PSTA or STANDARD to invoke @command{gnatpsta}
10424 @item
10425 STUB to invoke @command{gnatstub}
10426 @item
10427 XREF to invoke @command{gnatxref}
10428 @end itemize
10429
10430 @noindent
10431 Note that the compiler is invoked using the command @command{gnatmake -f -u}.
10432
10433 @noindent
10434 Following the command, you may put switches and arguments for the invoked
10435 tool.
10436
10437 @smallexample
10438   gnat bind -C main.ali
10439   gnat ls -a main
10440   gnat chop foo.txt
10441 @end smallexample
10442
10443 @noindent
10444 In addition, for command BIND, FIND, LS or LIST, LINK and XREF, the project
10445 file related switches (@code{-P}, @code{-X} and @code{-vPx}) may be used in
10446 addition to the switches of the invoking tool.
10447
10448 @noindent
10449 For each of these command, there is possibly a package in the main project that
10450 corresponds to the invoked tool.
10451
10452 @itemize @bullet
10453 @item
10454 package @code{Binder} for command BIND (invoking @code{gnatbind})
10455
10456 @item
10457 package @code{Finder} for command FIND (invoking @code{gnatfind})
10458
10459 @item
10460 package @code{Gnatls} for command LS or LIST (invoking @code{gnatls})
10461
10462 @item
10463 package @code{Linker} for command LINK (invoking @code{gnatlink})
10464
10465 @item
10466 package @code{Cross_Reference} for command XREF (invoking @code{gnatlink})
10467
10468 @end itemize
10469
10470 @noindent
10471 Package @code{Gnatls} has a unique attribute @code{Switches}, a simple variable
10472 with a string list value. It contains switches for the invocation of
10473 @code{gnatls}.
10474
10475 @smallexample
10476 @group
10477 project Proj1 is
10478    package gnatls is
10479       for Switches use ("-a", "-v");
10480    end gnatls;
10481 end Proj1;
10482 @end group
10483 @end smallexample
10484
10485 @noindent
10486 All other packages contains a switch @code{Default_Switches}, an associative
10487 array, indexed by the programming language (case insensitive) and having a
10488 string list value. @code{Default_Switches ("Ada")} contains the switches for
10489 the invocation of the tool corresponding to the package.
10490
10491 @smallexample
10492 @group
10493 project Proj is
10494
10495    for Source_Dirs use ("./**");
10496
10497    package gnatls is
10498       for Switches use ("-a", "-v");
10499    end gnatls;
10500 @end group
10501 @group
10502
10503    package Binder is
10504       for Default_Switches ("Ada") use ("-C", "-e");
10505    end Binder;
10506 @end group
10507 @group
10508
10509    package Linker is
10510       for Default_Switches ("Ada") use ("-C");
10511    end Linker;
10512 @end group
10513 @group
10514
10515    package Finder is
10516       for Default_Switches ("Ada") use ("-a", "-f");
10517    end Finder;
10518 @end group
10519 @group
10520
10521    package Cross_Reference is
10522       for Default_Switches ("Ada") use ("-a", "-f", "-d", "-u");
10523    end Cross_Reference;
10524 end Proj;
10525 @end group
10526 @end smallexample
10527
10528 @noindent
10529 With the above project file, commands such as
10530
10531 @smallexample
10532    gnat ls -Pproj main
10533    gnat xref -Pproj main
10534    gnat bind -Pproj main.ali
10535 @end smallexample
10536
10537 @noindent
10538 will set up the environment properly and invoke the tool with the switches
10539 found in the package corresponding to the tool.
10540
10541
10542 @node Glide and Project Files
10543 @subsection Glide and Project Files
10544
10545 @noindent
10546 Glide will automatically recognize the @file{.gpr} extension for
10547 project files, and will
10548 convert them to its own internal format automatically. However, it
10549 doesn't provide a syntax-oriented editor for modifying these
10550 files.
10551 The project file will be loaded as text when you select the menu item
10552 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
10553 You can edit this text and save the @file{gpr} file;
10554 when you next select this project file in Glide it
10555 will be automatically reloaded.
10556
10557
10558
10559 @node An Extended Example
10560 @section An Extended Example
10561
10562 @noindent
10563 Suppose that we have two programs, @var{prog1} and @var{prog2}, with the sources
10564 in the respective directories. We would like to build them with a single
10565 @command{gnatmake} command, and we would like to place their object files into
10566 @file{.build} subdirectories of the source directories. Furthermore, we would
10567 like to have to have two separate subdirectories in @file{.build}  --
10568 @file{release} and @file{debug} -- which will contain the object files compiled with
10569 different set of compilation flags.
10570
10571 In other words, we have the following structure:
10572
10573 @smallexample
10574 @group
10575    main
10576      |- prog1
10577      |    |- .build
10578      |         | debug
10579      |         | release
10580      |- prog2
10581           |- .build
10582                | debug
10583                | release
10584 @end group
10585 @end smallexample
10586
10587 @noindent
10588 Here are the project files that we need to create in a directory @file{main}
10589 to maintain this structure:
10590
10591 @enumerate
10592
10593 @item We create a @code{Common} project with a package @code{Compiler} that
10594 specifies the compilation switches:
10595
10596 @smallexample
10597 File "common.gpr":
10598 @group
10599 @b{project} Common @b{is}
10600
10601    @b{for} Source_Dirs @b{use} (); -- No source files
10602 @end group
10603
10604 @group
10605    @b{type} Build_Type @b{is} ("release", "debug");
10606    Build : Build_Type := External ("BUILD", "debug");
10607 @end group
10608 @group
10609    @b{package} Compiler @b{is}
10610       @b{case} Build @b{is}
10611          @b{when} "release" =>
10612            @b{for} Default_Switches ("Ada") @b{use} ("-O2");
10613          @b{when} "debug"   =>
10614            @b{for} Default_Switches ("Ada") @b{use} ("-g");
10615       @b{end case};
10616    @b{end} Compiler;
10617
10618 @b{end} Common;
10619 @end group
10620 @end smallexample
10621
10622 @item We create separate projects for the two programs:
10623
10624 @smallexample
10625 @group
10626 File "prog1.gpr":
10627
10628 @b{with} "common";
10629 @b{project} Prog1 @b{is}
10630
10631     @b{for} Source_Dirs @b{use} ("prog1");
10632     @b{for} Object_Dir  @b{use} "prog1/.build/" & Common.Build;
10633
10634     @b{package} Compiler @b{renames} Common.Compiler;
10635
10636 @b{end} Prog1;
10637 @end group
10638 @end smallexample
10639
10640 @smallexample
10641 @group
10642 File "prog2.gpr":
10643
10644 @b{with} "common";
10645 @b{project} Prog2 @b{is}
10646
10647     @b{for} Source_Dirs @b{use} ("prog2");
10648     @b{for} Object_Dir  @b{use} "prog2/.build/" & Common.Build;
10649
10650     @b{package} Compiler @b{renames} Common.Compiler;
10651
10652 @end group
10653 @b{end} Prog2;
10654 @end smallexample
10655
10656 @item We create a wrapping project @var{Main}:
10657
10658 @smallexample
10659 @group
10660 File "main.gpr":
10661
10662 @b{with} "common";
10663 @b{with} "prog1";
10664 @b{with} "prog2";
10665 @b{project} Main @b{is}
10666
10667    @b{package} Compiler @b{renames} Common.Compiler;
10668
10669 @b{end} Main;
10670 @end group
10671 @end smallexample
10672
10673 @item Finally we need to create a dummy procedure that @code{with}s (either
10674 explicitly or implicitly) all the sources of our two programs.
10675
10676 @end enumerate
10677
10678 @noindent
10679 Now we can build the programs using the command
10680
10681 @smallexample
10682    gnatmake -Pmain dummy
10683 @end smallexample
10684
10685 @noindent
10686 for the Debug mode, or
10687
10688 @smallexample
10689    gnatmake -Pmain -XBUILD=release
10690 @end smallexample
10691
10692 @noindent
10693 for the Release mode.
10694
10695
10696 @c ********************************
10697 @c * Project File Complete Syntax *
10698 @c ********************************
10699
10700 @node Project File Complete Syntax
10701 @section Project File Complete Syntax
10702
10703 @smallexample
10704 project ::=
10705   context_clause project_declaration
10706
10707 context_clause ::=
10708   @{with_clause@}
10709
10710 with_clause ::=
10711   @b{with} literal_string @{ , literal_string @} ;
10712
10713 project_declaration ::=
10714   @b{project} <project_>simple_name [ @b{extends} literal_string ] @b{is}
10715     @{declarative_item@}
10716   @b{end} <project_>simple_name;
10717
10718 declarative_item ::=
10719   package_declaration |
10720   typed_string_declaration |
10721   other_declarative_item
10722
10723 package_declaration ::=
10724   @b{package} <package_>simple_name package_completion
10725
10726 package_completion ::=
10727   package_body | package_renaming
10728
10729 package body ::=
10730   @b{is}
10731     @{other_declarative_item@}
10732   @b{end} <package_>simple_name ;
10733
10734 package_renaming ::==
10735   @b{renames} <project_>simple_name.<package_>simple_name ;
10736
10737 typed_string_declaration ::=
10738   @b{type} <typed_string_>_simple_name @b{is}
10739    ( literal_string @{, literal_string@} );
10740
10741 other_declarative_item ::=
10742   attribute_declaration |
10743   typed_variable_declaration |
10744   variable_declaration |
10745   case_construction
10746
10747 attribute_declaration ::=
10748   @b{for} attribute @b{use} expression ;
10749
10750 attribute ::=
10751   <simple_attribute_>simple_name |
10752   <associative_array_attribute_>simple_name ( literal_string )
10753
10754 typed_variable_declaration ::=
10755   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
10756
10757 variable_declaration ::=
10758   <variable_>simple_name := expression;
10759
10760 expression ::=
10761   term @{& term@}
10762
10763 term ::=
10764   literal_string |
10765   string_list |
10766   <variable_>name |
10767   external_value |
10768   attribute_reference
10769
10770 literal_string ::=
10771   (same as Ada)
10772
10773 string_list ::=
10774   ( <string_>expression @{ , <string_>expression @} )
10775
10776 external_value ::=
10777   @b{external} ( literal_string [, literal_string] )
10778
10779 attribute_reference ::=
10780   attribute_parent ' <simple_attribute_>simple_name [ ( literal_string ) ]
10781
10782 attribute_parent ::=
10783   @b{project} |
10784   <project_or_package>simple_name |
10785   <project_>simple_name . <package_>simple_name
10786
10787 case_construction ::=
10788   @b{case} <typed_variable_>name @b{is}
10789     @{case_item@}
10790   @b{end case} ;
10791
10792 case_item ::=
10793   @b{when} discrete_choice_list => @{case_construction | attribute_declaration@}
10794
10795 discrete_choice_list ::=
10796   literal_string @{| literal_string@}
10797
10798 name ::=
10799   simple_name @{. simple_name@}
10800
10801 simple_name ::=
10802   identifier (same as Ada)
10803
10804 @end smallexample
10805
10806
10807 @node Elaboration Order Handling in GNAT
10808 @chapter Elaboration Order Handling in GNAT
10809 @cindex Order of elaboration
10810 @cindex Elaboration control
10811
10812 @menu
10813 * Elaboration Code in Ada 95::
10814 * Checking the Elaboration Order in Ada 95::
10815 * Controlling the Elaboration Order in Ada 95::
10816 * Controlling Elaboration in GNAT - Internal Calls::
10817 * Controlling Elaboration in GNAT - External Calls::
10818 * Default Behavior in GNAT - Ensuring Safety::
10819 * Elaboration Issues for Library Tasks::
10820 * Mixing Elaboration Models::
10821 * What to Do If the Default Elaboration Behavior Fails::
10822 * Elaboration for Access-to-Subprogram Values::
10823 * Summary of Procedures for Elaboration Control::
10824 * Other Elaboration Order Considerations::
10825 @end menu
10826
10827 @noindent
10828 This chapter describes the handling of elaboration code in Ada 95 and
10829 in GNAT, and discusses how the order of elaboration of program units can
10830 be controlled in GNAT, either automatically or with explicit programming
10831 features.
10832
10833 @node Elaboration Code in Ada 95
10834 @section Elaboration Code in Ada 95
10835
10836 @noindent
10837 Ada 95 provides rather general mechanisms for executing code at elaboration
10838 time, that is to say before the main program starts executing. Such code arises
10839 in three contexts:
10840
10841 @table @asis
10842 @item Initializers for variables.
10843 Variables declared at the library level, in package specs or bodies, can
10844 require initialization that is performed at elaboration time, as in:
10845 @smallexample
10846 @cartouche
10847 Sqrt_Half : Float := Sqrt (0.5);
10848 @end cartouche
10849 @end smallexample
10850
10851 @item Package initialization code
10852 Code in a @code{BEGIN-END} section at the outer level of a package body is
10853 executed as part of the package body elaboration code.
10854
10855 @item Library level task allocators
10856 Tasks that are declared using task allocators at the library level
10857 start executing immediately and hence can execute at elaboration time.
10858 @end table
10859
10860 @noindent
10861 Subprogram calls are possible in any of these contexts, which means that
10862 any arbitrary part of the program may be executed as part of the elaboration
10863 code. It is even possible to write a program which does all its work at
10864 elaboration time, with a null main program, although stylistically this
10865 would usually be considered an inappropriate way to structure
10866 a program.
10867
10868 An important concern arises in the context of elaboration code:
10869 we have to be sure that it is executed in an appropriate order. What we
10870 have is a series of elaboration code sections, potentially one section
10871 for each unit in the program. It is important that these execute
10872 in the correct order. Correctness here means that, taking the above
10873 example of the declaration of @code{Sqrt_Half},
10874 if some other piece of
10875 elaboration code references @code{Sqrt_Half},
10876 then it must run after the
10877 section of elaboration code that contains the declaration of
10878 @code{Sqrt_Half}.
10879
10880 There would never be any order of elaboration problem if we made a rule
10881 that whenever you @code{with} a unit, you must elaborate both the spec and body
10882 of that unit before elaborating the unit doing the @code{with}'ing:
10883
10884 @smallexample
10885 @group
10886 @cartouche
10887 @b{with} Unit_1;
10888 @b{package} Unit_2 @b{is} ...
10889 @end cartouche
10890 @end group
10891 @end smallexample
10892
10893 @noindent
10894 would require that both the body and spec of @code{Unit_1} be elaborated
10895 before the spec of @code{Unit_2}. However, a rule like that would be far too
10896 restrictive. In particular, it would make it impossible to have routines
10897 in separate packages that were mutually recursive.
10898
10899 You might think that a clever enough compiler could look at the actual
10900 elaboration code and determine an appropriate correct order of elaboration,
10901 but in the general case, this is not possible. Consider the following
10902 example.
10903
10904 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
10905 that references
10906 the variable @code{Sqrt_1}, which is declared in the elaboration code
10907 of the body of @code{Unit_1}:
10908
10909 @smallexample
10910 @cartouche
10911 Sqrt_1 : Float := Sqrt (0.1);
10912 @end cartouche
10913 @end smallexample
10914
10915 @noindent
10916 The elaboration code of the body of @code{Unit_1} also contains:
10917
10918 @smallexample
10919 @group
10920 @cartouche
10921 @b{if} expression_1 = 1 @b{then}
10922    Q := Unit_2.Func_2;
10923 @b{end if};
10924 @end cartouche
10925 @end group
10926 @end smallexample
10927
10928 @noindent
10929 @code{Unit_2} is exactly parallel,
10930 it has a procedure @code{Func_2} that references
10931 the variable @code{Sqrt_2}, which is declared in the elaboration code of
10932 the body @code{Unit_2}:
10933
10934 @smallexample
10935 @cartouche
10936 Sqrt_2 : Float := Sqrt (0.1);
10937 @end cartouche
10938 @end smallexample
10939
10940 @noindent
10941 The elaboration code of the body of @code{Unit_2} also contains:
10942
10943 @smallexample
10944 @group
10945 @cartouche
10946 @b{if} expression_2 = 2 @b{then}
10947    Q := Unit_1.Func_1;
10948 @b{end if};
10949 @end cartouche
10950 @end group
10951 @end smallexample
10952
10953 @noindent
10954 Now the question is, which of the following orders of elaboration is
10955 acceptable:
10956
10957 @smallexample
10958 @group
10959 Spec of Unit_1
10960 Spec of Unit_2
10961 Body of Unit_1
10962 Body of Unit_2
10963 @end group
10964 @end smallexample
10965
10966 @noindent
10967 or
10968
10969 @smallexample
10970 @group
10971 Spec of Unit_2
10972 Spec of Unit_1
10973 Body of Unit_2
10974 Body of Unit_1
10975 @end group
10976 @end smallexample
10977
10978 @noindent
10979 If you carefully analyze the flow here, you will see that you cannot tell
10980 at compile time the answer to this question.
10981 If @code{expression_1} is not equal to 1,
10982 and @code{expression_2} is not equal to 2,
10983 then either order is acceptable, because neither of the function calls is
10984 executed. If both tests evaluate to true, then neither order is acceptable
10985 and in fact there is no correct order.
10986
10987 If one of the two expressions is true, and the other is false, then one
10988 of the above orders is correct, and the other is incorrect. For example,
10989 if @code{expression_1} = 1 and @code{expression_2} /= 2,
10990 then the call to @code{Func_2}
10991 will occur, but not the call to @code{Func_1.}
10992 This means that it is essential
10993 to elaborate the body of @code{Unit_1} before
10994 the body of @code{Unit_2}, so the first
10995 order of elaboration is correct and the second is wrong.
10996
10997 By making @code{expression_1} and @code{expression_2}
10998 depend on input data, or perhaps
10999 the time of day, we can make it impossible for the compiler or binder
11000 to figure out which of these expressions will be true, and hence it
11001 is impossible to guarantee a safe order of elaboration at run time.
11002
11003 @node Checking the Elaboration Order in Ada 95
11004 @section Checking the Elaboration Order in Ada 95
11005
11006 @noindent
11007 In some languages that involve the same kind of elaboration problems,
11008 e.g. Java and C++, the programmer is expected to worry about these
11009 ordering problems himself, and it is common to
11010 write a program in which an incorrect elaboration order  gives
11011 surprising results, because it references variables before they
11012 are initialized.
11013 Ada 95 is designed to be a safe language, and a programmer-beware approach is
11014 clearly not sufficient. Consequently, the language provides three lines
11015 of defense:
11016
11017 @table @asis
11018 @item Standard rules
11019 Some standard rules restrict the possible choice of elaboration
11020 order. In particular, if you @code{with} a unit, then its spec is always
11021 elaborated before the unit doing the @code{with}. Similarly, a parent
11022 spec is always elaborated before the child spec, and finally
11023 a spec is always elaborated before its corresponding body.
11024
11025 @item Dynamic elaboration checks
11026 @cindex Elaboration checks
11027 @cindex Checks, elaboration
11028 Dynamic checks are made at run time, so that if some entity is accessed
11029 before it is elaborated (typically  by means of a subprogram call)
11030 then the exception (@code{Program_Error}) is raised.
11031
11032 @item Elaboration control
11033 Facilities are provided for the programmer to specify the desired order
11034 of elaboration.
11035 @end table
11036
11037 Let's look at these facilities in more detail. First, the rules for
11038 dynamic checking. One possible rule would be simply to say that the
11039 exception is raised if you access a variable which has not yet been
11040 elaborated. The trouble with this approach is that it could require
11041 expensive checks on every variable reference. Instead Ada 95 has two
11042 rules which are a little more restrictive, but easier to check, and
11043 easier to state:
11044
11045 @table @asis
11046 @item Restrictions on calls
11047 A subprogram can only be called at elaboration time if its body
11048 has been elaborated. The rules for elaboration given above guarantee
11049 that the spec of the subprogram has been elaborated before the
11050 call, but not the body. If this rule is violated, then the
11051 exception @code{Program_Error} is raised.
11052
11053 @item Restrictions on instantiations
11054 A generic unit can only be instantiated if the body of the generic
11055 unit has been elaborated. Again, the rules for elaboration given above
11056 guarantee that the spec of the generic unit has been elaborated
11057 before the instantiation, but not the body. If this rule is
11058 violated, then the exception @code{Program_Error} is raised.
11059 @end table
11060
11061 @noindent
11062 The idea is that if the body has been elaborated, then any variables
11063 it references must have been elaborated; by checking for the body being
11064 elaborated we guarantee that none of its references causes any
11065 trouble. As we noted above, this is a little too restrictive, because a
11066 subprogram that has no non-local references in its body may in fact be safe
11067 to call. However, it really would be unsafe to rely on this, because
11068 it would mean that the caller was aware of details of the implementation
11069 in the body. This goes against the basic tenets of Ada.
11070
11071 A plausible implementation can be described as follows.
11072 A Boolean variable is associated with each subprogram
11073 and each generic unit. This variable is initialized to False, and is set to
11074 True at the point body is elaborated. Every call or instantiation checks the
11075 variable, and raises @code{Program_Error} if the variable is False.
11076
11077 Note that one might think that it would be good enough to have one Boolean
11078 variable for each package, but that would not deal with cases of trying
11079 to call a body in the same package as the call
11080 that has not been elaborated yet.
11081 Of course a compiler may be able to do enough analysis to optimize away
11082 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
11083 does such optimizations, but still the easiest conceptual model is to
11084 think of there being one variable per subprogram.
11085
11086 @node Controlling the Elaboration Order in Ada 95
11087 @section Controlling the Elaboration Order in Ada 95
11088
11089 @noindent
11090 In the previous section we discussed the rules in Ada 95 which ensure
11091 that @code{Program_Error} is raised if an incorrect elaboration order is
11092 chosen. This prevents erroneous executions, but we need mechanisms to
11093 specify a correct execution and avoid the exception altogether.
11094 To achieve this, Ada 95 provides a number of features for controlling
11095 the order of elaboration. We discuss these features in this section.
11096
11097 First, there are several ways of indicating to the compiler that a given
11098 unit has no elaboration problems:
11099
11100 @table @asis
11101 @item packages that do not require a body
11102 In Ada 95, a library package that does not require a body does not permit
11103 a body. This means that if we have a such a package, as in:
11104
11105 @smallexample
11106 @group
11107 @cartouche
11108 @b{package} Definitions @b{is}
11109    @b{generic}
11110       @b{type} m @b{is new} integer;
11111    @b{package} Subp @b{is}
11112       @b{type} a @b{is array} (1 .. 10) @b{of} m;
11113       @b{type} b @b{is array} (1 .. 20) @b{of} m;
11114    @b{end} Subp;
11115 @b{end} Definitions;
11116 @end cartouche
11117 @end group
11118 @end smallexample
11119
11120 @noindent
11121 A package that @code{with}'s @code{Definitions} may safely instantiate
11122 @code{Definitions.Subp} because the compiler can determine that there
11123 definitely is no package body to worry about in this case
11124
11125 @item pragma Pure
11126 @cindex pragma Pure
11127 @findex Pure
11128 Places sufficient restrictions on a unit to guarantee that
11129 no call to any subprogram in the unit can result in an
11130 elaboration problem. This means that the compiler does not need
11131 to worry about the point of elaboration of such units, and in
11132 particular, does not need to check any calls to any subprograms
11133 in this unit.
11134
11135 @item pragma Preelaborate
11136 @findex Preelaborate
11137 @cindex pragma Preelaborate
11138 This pragma places slightly less stringent restrictions on a unit than
11139 does pragma Pure,
11140 but these restrictions are still sufficient to ensure that there
11141 are no elaboration problems with any calls to the unit.
11142
11143 @item pragma Elaborate_Body
11144 @findex Elaborate_Body
11145 @cindex pragma Elaborate_Body
11146 This pragma requires that the body of a unit be elaborated immediately
11147 after its spec. Suppose a unit @code{A} has such a pragma,
11148 and unit @code{B} does
11149 a @code{with} of unit @code{A}. Recall that the standard rules require
11150 the spec of unit @code{A}
11151 to be elaborated before the @code{with}'ing unit; given the pragma in
11152 @code{A}, we also know that the body of @code{A}
11153 will be elaborated before @code{B}, so
11154 that calls to @code{A} are safe and do not need a check.
11155 @end table
11156
11157 @noindent
11158 Note that,
11159 unlike pragma @code{Pure} and pragma @code{Preelaborate},
11160 the use of
11161 @code{Elaborate_Body} does not guarantee that the program is
11162 free of elaboration problems, because it may not be possible
11163 to satisfy the requested elaboration order.
11164 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
11165 If a programmer
11166 marks @code{Unit_1} as @code{Elaborate_Body},
11167 and not @code{Unit_2,} then the order of
11168 elaboration will be:
11169
11170 @smallexample
11171 @group
11172 Spec of Unit_2
11173 Spec of Unit_1
11174 Body of Unit_1
11175 Body of Unit_2
11176 @end group
11177 @end smallexample
11178
11179 @noindent
11180 Now that means that the call to @code{Func_1} in @code{Unit_2}
11181 need not be checked,
11182 it must be safe. But the call to @code{Func_2} in
11183 @code{Unit_1} may still fail if
11184 @code{Expression_1} is equal to 1,
11185 and the programmer must still take
11186 responsibility for this not being the case.
11187
11188 If all units carry a pragma @code{Elaborate_Body}, then all problems are
11189 eliminated, except for calls entirely within a body, which are
11190 in any case fully under programmer control. However, using the pragma
11191 everywhere is not always possible.
11192 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
11193 we marked both of them as having pragma @code{Elaborate_Body}, then
11194 clearly there would be no possible elaboration order.
11195
11196 The above pragmas allow a server to guarantee safe use by clients, and
11197 clearly this is the preferable approach. Consequently a good rule in
11198 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
11199 and if this is not possible,
11200 mark them as @code{Elaborate_Body} if possible.
11201 As we have seen, there are situations where neither of these
11202 three pragmas can be used.
11203 So we also provide methods for clients to control the
11204 order of elaboration of the servers on which they depend:
11205
11206 @table @asis
11207 @item pragma Elaborate (unit)
11208 @findex Elaborate
11209 @cindex pragma Elaborate
11210 This pragma is placed in the context clause, after a @code{with} clause,
11211 and it requires that the body of the named unit be elaborated before
11212 the unit in which the pragma occurs. The idea is to use this pragma
11213 if the current unit calls at elaboration time, directly or indirectly,
11214 some subprogram in the named unit.
11215
11216 @item pragma Elaborate_All (unit)
11217 @findex Elaborate_All
11218 @cindex pragma Elaborate_All
11219 This is a stronger version of the Elaborate pragma. Consider the
11220 following example:
11221
11222 @smallexample
11223 Unit A @code{with}'s unit B and calls B.Func in elab code
11224 Unit B @code{with}'s unit C, and B.Func calls C.Func
11225 @end smallexample
11226
11227 @noindent
11228 Now if we put a pragma @code{Elaborate (B)}
11229 in unit @code{A}, this ensures that the
11230 body of @code{B} is elaborated before the call, but not the
11231 body of @code{C}, so
11232 the call to @code{C.Func} could still cause @code{Program_Error} to
11233 be raised.
11234
11235 The effect of a pragma @code{Elaborate_All} is stronger, it requires
11236 not only that the body of the named unit be elaborated before the
11237 unit doing the @code{with}, but also the bodies of all units that the
11238 named unit uses, following @code{with} links transitively. For example,
11239 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
11240 then it requires
11241 not only that the body of @code{B} be elaborated before @code{A},
11242 but also the
11243 body of @code{C}, because @code{B} @code{with}'s @code{C}.
11244 @end table
11245
11246 @noindent
11247 We are now in a position to give a usage rule in Ada 95 for avoiding
11248 elaboration problems, at least if dynamic dispatching and access to
11249 subprogram values are not used. We will handle these cases separately
11250 later.
11251
11252 The rule is simple. If a unit has elaboration code that can directly or
11253 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
11254 a generic unit in a @code{with}'ed unit,
11255 then if the @code{with}'ed unit does not have
11256 pragma @code{Pure} or @code{Preelaborate}, then the client should have
11257 a pragma @code{Elaborate_All}
11258 for the @code{with}'ed unit. By following this rule a client is
11259 assured that calls can be made without risk of an exception.
11260 If this rule is not followed, then a program may be in one of four
11261 states:
11262
11263 @table @asis
11264 @item No order exists
11265 No order of elaboration exists which follows the rules, taking into
11266 account any @code{Elaborate}, @code{Elaborate_All},
11267 or @code{Elaborate_Body} pragmas. In
11268 this case, an Ada 95 compiler must diagnose the situation at bind
11269 time, and refuse to build an executable program.
11270
11271 @item One or more orders exist, all incorrect
11272 One or more acceptable elaboration orders exists, and all of them
11273 generate an elaboration order problem. In this case, the binder
11274 can build an executable program, but @code{Program_Error} will be raised
11275 when the program is run.
11276
11277 @item Several orders exist, some right, some incorrect
11278 One or more acceptable elaboration orders exists, and some of them
11279 work, and some do not. The programmer has not controlled
11280 the order of elaboration, so the binder may or may not pick one of
11281 the correct orders, and the program may or may not raise an
11282 exception when it is run. This is the worst case, because it means
11283 that the program may fail when moved to another compiler, or even
11284 another version of the same compiler.
11285
11286 @item One or more orders exists, all correct
11287 One ore more acceptable elaboration orders exist, and all of them
11288 work. In this case the program runs successfully. This state of
11289 affairs can be guaranteed by following the rule we gave above, but
11290 may be true even if the rule is not followed.
11291 @end table
11292
11293 @noindent
11294 Note that one additional advantage of following our Elaborate_All rule
11295 is that the program continues to stay in the ideal (all orders OK) state
11296 even if maintenance
11297 changes some bodies of some subprograms. Conversely, if a program that does
11298 not follow this rule happens to be safe at some point, this state of affairs
11299 may deteriorate silently as a result of maintenance changes.
11300
11301 You may have noticed that the above discussion did not mention
11302 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
11303 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
11304 code in the body makes calls to some other unit, so it is still necessary
11305 to use @code{Elaborate_All} on such units.
11306
11307 @node Controlling Elaboration in GNAT - Internal Calls
11308 @section Controlling Elaboration in GNAT - Internal Calls
11309
11310 @noindent
11311 In the case of internal calls, i.e. calls within a single package, the
11312 programmer has full control over the order of elaboration, and it is up
11313 to the programmer to elaborate declarations in an appropriate order. For
11314 example writing:
11315
11316 @smallexample
11317 @group
11318 @cartouche
11319 @b{function} One @b{return} Float;
11320
11321 Q : Float := One;
11322
11323 @b{function} One @b{return} Float @b{is}
11324 @b{begin}
11325      return 1.0;
11326 @b{end} One;
11327 @end cartouche
11328 @end group
11329 @end smallexample
11330
11331 @noindent
11332 will obviously raise @code{Program_Error} at run time, because function
11333 One will be called before its body is elaborated. In this case GNAT will
11334 generate a warning that the call will raise @code{Program_Error}:
11335
11336 @smallexample
11337 @group
11338 @cartouche
11339  1. procedure y is
11340  2.    function One return Float;
11341  3.
11342  4.    Q : Float := One;
11343                     |
11344     >>> warning: cannot call "One" before body is elaborated
11345     >>> warning: Program_Error will be raised at run time
11346
11347  5.
11348  6.    function One return Float is
11349  7.    begin
11350  8.         return 1.0;
11351  9.    end One;
11352 10.
11353 11. begin
11354 12.    null;
11355 13. end;
11356 @end cartouche
11357 @end group
11358 @end smallexample
11359
11360 @noindent
11361 Note that in this particular case, it is likely that the call is safe, because
11362 the function @code{One} does not access any global variables.
11363 Nevertheless in Ada 95, we do not want the validity of the check to depend on
11364 the contents of the body (think about the separate compilation case), so this
11365 is still wrong, as we discussed in the previous sections.
11366
11367 The error is easily corrected by rearranging the declarations so that the
11368 body of One appears before the declaration containing the call
11369 (note that in Ada 95,
11370 declarations can appear in any order, so there is no restriction that
11371 would prevent this reordering, and if we write:
11372
11373 @smallexample
11374 @group
11375 @cartouche
11376 @b{function} One @b{return} Float;
11377
11378 @b{function} One @b{return} Float @b{is}
11379 @b{begin}
11380      return 1.0;
11381 @b{end} One;
11382
11383 Q : Float := One;
11384 @end cartouche
11385 @end group
11386 @end smallexample
11387
11388 @noindent
11389 then all is well, no warning is generated, and no
11390 @code{Program_Error} exception
11391 will be raised.
11392 Things are more complicated when a chain of subprograms is executed:
11393
11394 @smallexample
11395 @group
11396 @cartouche
11397 @b{function} A @b{return} Integer;
11398 @b{function} B @b{return} Integer;
11399 @b{function} C @b{return} Integer;
11400
11401 @b{function} B @b{return} Integer @b{is begin return} A; @b{end};
11402 @b{function} C @b{return} Integer @b{is begin return} B; @b{end};
11403
11404 X : Integer := C;
11405
11406 @b{function} A @b{return} Integer @b{is begin return} 1; @b{end};
11407 @end cartouche
11408 @end group
11409 @end smallexample
11410
11411 @noindent
11412 Now the call to @code{C}
11413 at elaboration time in the declaration of @code{X} is correct, because
11414 the body of @code{C} is already elaborated,
11415 and the call to @code{B} within the body of
11416 @code{C} is correct, but the call
11417 to @code{A} within the body of @code{B} is incorrect, because the body
11418 of @code{A} has not been elaborated, so @code{Program_Error}
11419 will be raised on the call to @code{A}.
11420 In this case GNAT will generate a
11421 warning that @code{Program_Error} may be
11422 raised at the point of the call. Let's look at the warning:
11423
11424 @smallexample
11425 @group
11426 @cartouche
11427  1. procedure x is
11428  2.    function A return Integer;
11429  3.    function B return Integer;
11430  4.    function C return Integer;
11431  5.
11432  6.    function B return Integer is begin return A; end;
11433                                                     |
11434     >>> warning: call to "A" before body is elaborated may
11435                  raise Program_Error
11436     >>> warning: "B" called at line 7
11437     >>> warning: "C" called at line 9
11438
11439  7.    function C return Integer is begin return B; end;
11440  8.
11441  9.    X : Integer := C;
11442 10.
11443 11.    function A return Integer is begin return 1; end;
11444 12.
11445 13. begin
11446 14.    null;
11447 15. end;
11448 @end cartouche
11449 @end group
11450 @end smallexample
11451
11452 @noindent
11453 Note that the message here says "may raise", instead of the direct case,
11454 where the message says "will be raised". That's because whether
11455 @code{A} is
11456 actually called depends in general on run-time flow of control.
11457 For example, if the body of @code{B} said
11458
11459 @smallexample
11460 @group
11461 @cartouche
11462 @b{function} B @b{return} Integer @b{is}
11463 @b{begin}
11464    @b{if} some-condition-depending-on-input-data @b{then}
11465       @b{return} A;
11466    @b{else}
11467       @b{return} 1;
11468    @b{end if};
11469 @b{end} B;
11470 @end cartouche
11471 @end group
11472 @end smallexample
11473
11474 @noindent
11475 then we could not know until run time whether the incorrect call to A would
11476 actually occur, so @code{Program_Error} might
11477 or might not be raised. It is possible for a compiler to
11478 do a better job of analyzing bodies, to
11479 determine whether or not @code{Program_Error}
11480 might be raised, but it certainly
11481 couldn't do a perfect job (that would require solving the halting problem
11482 and is provably impossible), and because this is a warning anyway, it does
11483 not seem worth the effort to do the analysis. Cases in which it
11484 would be relevant are rare.
11485
11486 In practice, warnings of either of the forms given
11487 above will usually correspond to
11488 real errors, and should be examined carefully and eliminated.
11489 In the rare case where a warning is bogus, it can be suppressed by any of
11490 the following methods:
11491
11492 @itemize @bullet
11493 @item
11494 Compile with the @option{-gnatws} switch set
11495
11496 @item
11497 Suppress @code{Elaboration_Checks} for the called subprogram
11498
11499 @item
11500 Use pragma @code{Warnings_Off} to turn warnings off for the call
11501 @end itemize
11502
11503 @noindent
11504 For the internal elaboration check case,
11505 GNAT by default generates the
11506 necessary run-time checks to ensure
11507 that @code{Program_Error} is raised if any
11508 call fails an elaboration check. Of course this can only happen if a
11509 warning has been issued as described above. The use of pragma
11510 @code{Suppress (Elaboration_Checks)} may (but is not guaranteed to) suppress
11511 some of these checks, meaning that it may be possible (but is not
11512 guaranteed) for a program to be able to call a subprogram whose body
11513 is not yet elaborated, without raising a @code{Program_Error} exception.
11514
11515 @node Controlling Elaboration in GNAT - External Calls
11516 @section Controlling Elaboration in GNAT - External Calls
11517
11518 @noindent
11519 The previous section discussed the case in which the execution of a
11520 particular thread of elaboration code occurred entirely within a
11521 single unit. This is the easy case to handle, because a programmer
11522 has direct and total control over the order of elaboration, and
11523 furthermore, checks need only be generated in cases which are rare
11524 and which the compiler can easily detect.
11525 The situation is more complex when separate compilation is taken into account.
11526 Consider the following:
11527
11528 @smallexample
11529 @cartouche
11530 @group
11531 @b{package} Math @b{is}
11532    @b{function} Sqrt (Arg : Float) @b{return} Float;
11533 @b{end} Math;
11534
11535 @b{package body} Math @b{is}
11536    @b{function} Sqrt (Arg : Float) @b{return} Float @b{is}
11537    @b{begin}
11538          ...
11539    @b{end} Sqrt;
11540 @b{end} Math;
11541 @end group
11542 @group
11543 @b{with} Math;
11544 @b{package} Stuff @b{is}
11545    X : Float := Math.Sqrt (0.5);
11546 @b{end} Stuff;
11547
11548 @b{with} Stuff;
11549 @b{procedure} Main @b{is}
11550 @b{begin}
11551    ...
11552 @b{end} Main;
11553 @end group
11554 @end cartouche
11555 @end smallexample
11556
11557 @noindent
11558 where @code{Main} is the main program. When this program is executed, the
11559 elaboration code must first be executed, and one of the jobs of the
11560 binder is to determine the order in which the units of a program are
11561 to be elaborated. In this case we have four units: the spec and body
11562 of @code{Math},
11563 the spec of @code{Stuff} and the body of @code{Main}).
11564 In what order should the four separate sections of elaboration code
11565 be executed?
11566
11567 There are some restrictions in the order of elaboration that the binder
11568 can choose. In particular, if unit U has a @code{with}
11569 for a package @code{X}, then you
11570 are assured that the spec of @code{X}
11571 is elaborated before U , but you are
11572 not assured that the body of @code{X}
11573 is elaborated before U.
11574 This means that in the above case, the binder is allowed to choose the
11575 order:
11576
11577 @smallexample
11578 spec of Math
11579 spec of Stuff
11580 body of Math
11581 body of Main
11582 @end smallexample
11583
11584 @noindent
11585 but that's not good, because now the call to @code{Math.Sqrt}
11586 that happens during
11587 the elaboration of the @code{Stuff}
11588 spec happens before the body of @code{Math.Sqrt} is
11589 elaborated, and hence causes @code{Program_Error} exception to be raised.
11590 At first glance, one might say that the binder is misbehaving, because
11591 obviously you want to elaborate the body of something you @code{with}
11592 first, but
11593 that is not a general rule that can be followed in all cases. Consider
11594
11595 @smallexample
11596 @group
11597 @cartouche
11598 @b{package} X @b{is} ...
11599
11600 @b{package} Y @b{is} ...
11601
11602 @b{with} X;
11603 @b{package body} Y @b{is} ...
11604
11605 @b{with} Y;
11606 @b{package body} X @b{is} ...
11607 @end cartouche
11608 @end group
11609 @end smallexample
11610
11611 @noindent
11612 This is a common arrangement, and, apart from the order of elaboration
11613 problems that might arise in connection with elaboration code, this works fine.
11614 A rule that says that you must first elaborate the body of anything you
11615 @code{with} cannot work in this case:
11616 the body of @code{X} @code{with}'s @code{Y},
11617 which means you would have to
11618 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
11619 which means
11620 you have to elaborate the body of @code{X} first, but ... and we have a
11621 loop that cannot be broken.
11622
11623 It is true that the binder can in many cases guess an order of elaboration
11624 that is unlikely to cause a @code{Program_Error}
11625 exception to be raised, and it tries to do so (in the
11626 above example of @code{Math/Stuff/Spec}, the GNAT binder will
11627 by default
11628 elaborate the body of @code{Math} right after its spec, so all will be well).
11629
11630 However, a program that blindly relies on the binder to be helpful can
11631 get into trouble, as we discussed in the previous sections, so
11632 GNAT
11633 provides a number of facilities for assisting the programmer in
11634 developing programs that are robust with respect to elaboration order.
11635
11636 @node Default Behavior in GNAT - Ensuring Safety
11637 @section Default Behavior in GNAT - Ensuring Safety
11638
11639 @noindent
11640 The default behavior in GNAT ensures elaboration safety. In its
11641 default mode GNAT implements the
11642 rule we previously described as the right approach. Let's restate it:
11643
11644 @itemize
11645 @item
11646 @emph{If a unit has elaboration code that can directly or indirectly make a
11647 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
11648 in a @code{with}'ed unit, then if the @code{with}'ed unit
11649 does not have pragma @code{Pure} or
11650 @code{Preelaborate}, then the client should have an
11651 @code{Elaborate_All} for the @code{with}'ed unit.}
11652 @end itemize
11653
11654 @noindent
11655 By following this rule a client
11656 is assured that calls and instantiations can be made without risk of an exception.
11657
11658 In this mode GNAT traces all calls that are potentially made from
11659 elaboration code, and puts in any missing implicit @code{Elaborate_All}
11660 pragmas.
11661 The advantage of this approach is that no elaboration problems
11662 are possible if the binder can find an elaboration order that is
11663 consistent with these implicit @code{Elaborate_All} pragmas. The
11664 disadvantage of this approach is that no such order may exist.
11665
11666 If the binder does not generate any diagnostics, then it means that it
11667 has found an elaboration order that is guaranteed to be safe. However,
11668 the binder may still be relying on implicitly generated
11669 @code{Elaborate_All} pragmas so portability to other compilers than
11670 GNAT is not guaranteed.
11671
11672 If it is important to guarantee portability, then the compilations should
11673 use the
11674 @option{-gnatwl}
11675 (warn on elaboration problems) switch. This will cause warning messages
11676 to be generated indicating the missing @code{Elaborate_All} pragmas.
11677 Consider the following source program:
11678
11679 @smallexample
11680 @group
11681 @cartouche
11682 @b{with} k;
11683 @b{package} j @b{is}
11684   m : integer := k.r;
11685 @b{end};
11686 @end cartouche
11687 @end group
11688 @end smallexample
11689
11690 @noindent
11691 where it is clear that there
11692 should be a pragma @code{Elaborate_All}
11693 for unit @code{k}. An implicit pragma will be generated, and it is
11694 likely that the binder will be able to honor it. However,
11695 it is safer to include the pragma explicitly in the source. If this
11696 unit is compiled with the
11697 @option{-gnatwl}
11698 switch, then the compiler outputs a warning:
11699
11700 @smallexample
11701 @group
11702 @cartouche
11703 1. with k;
11704 2. package j is
11705 3.   m : integer := k.r;
11706                      |
11707    >>> warning: call to "r" may raise Program_Error
11708    >>> warning: missing pragma Elaborate_All for "k"
11709
11710 4. end;
11711 @end cartouche
11712 @end group
11713 @end smallexample
11714
11715 @noindent
11716 and these warnings can be used as a guide for supplying manually
11717 the missing pragmas.
11718
11719 This default mode is more restrictive than the Ada Reference
11720 Manual, and it is possible to construct programs which will compile
11721 using the dynamic model described there, but will run into a
11722 circularity using the safer static model we have described.
11723
11724 Of course any Ada compiler must be able to operate in a mode
11725 consistent with the requirements of the Ada Reference Manual,
11726 and in particular must have the capability of implementing the
11727 standard dynamic model of elaboration with run-time checks.
11728
11729 In GNAT, this standard mode can be achieved either by the use of
11730 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
11731 command, or by the use of the configuration pragma:
11732
11733 @smallexample
11734 pragma Elaboration_Checks (RM);
11735 @end smallexample
11736
11737 @noindent
11738 Either approach will cause the unit affected to be compiled using the
11739 standard dynamic run-time elaboration checks described in the Ada
11740 Reference Manual. The static model is generally preferable, since it
11741 is clearly safer to rely on compile and link time checks rather than
11742 run-time checks. However, in the case of legacy code, it may be
11743 difficult to meet the requirements of the static model. This
11744 issue is further discussed in
11745 @ref{What to Do If the Default Elaboration Behavior Fails}.
11746
11747 Note that the static model provides a strict subset of the allowed
11748 behavior and programs of the Ada Reference Manual, so if you do
11749 adhere to the static model and no circularities exist,
11750 then you are assured that your program will
11751 work using the dynamic model.
11752
11753 @node Elaboration Issues for Library Tasks
11754 @section Elaboration Issues for Library Tasks
11755 @cindex Library tasks, elaboration issues
11756 @cindex Elaboration of library tasks
11757
11758 @noindent
11759 In this section we examine special elaboration issues that arise for
11760 programs that declare library level tasks.
11761
11762 Generally the model of execution of an Ada program is that all units are
11763 elaborated, and then execution of the program starts. However, the
11764 declaration of library tasks definitely does not fit this model. The
11765 reason for this is that library tasks start as soon as they are declared
11766 (more precisely, as soon as the statement part of the enclosing package
11767 body is reached), that is to say before elaboration
11768 of the program is complete. This means that if such a task calls a
11769 subprogram, or an entry in another task, the callee may or may not be
11770 elaborated yet, and in the standard
11771 Reference Manual model of dynamic elaboration checks, you can even
11772 get timing dependent Program_Error exceptions, since there can be
11773 a race between the elaboration code and the task code.
11774
11775 The static model of elaboration in GNAT seeks to avoid all such
11776 dynamic behavior, by being conservative, and the conservative
11777 approach in this particular case is to assume that all the code
11778 in a task body is potentially executed at elaboration time if
11779 a task is declared at the library level.
11780
11781 This can definitely result in unexpected circularities. Consider
11782 the following example
11783
11784 @smallexample
11785 package Decls is
11786   task Lib_Task is
11787      entry Start;
11788   end Lib_Task;
11789
11790   type My_Int is new Integer;
11791
11792   function Ident (M : My_Int) return My_Int;
11793 end Decls;
11794
11795 with Utils;
11796 package body Decls is
11797   task body Lib_Task is
11798   begin
11799      accept Start;
11800      Utils.Put_Val (2);
11801   end Lib_Task;
11802
11803   function Ident (M : My_Int) return My_Int is
11804   begin
11805      return M;
11806   end Ident;
11807 end Decls;
11808
11809 with Decls;
11810 package Utils is
11811   procedure Put_Val (Arg : Decls.My_Int);
11812 end Utils;
11813
11814 with Text_IO;
11815 package body Utils is
11816   procedure Put_Val (Arg : Decls.My_Int) is
11817   begin
11818      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
11819   end Put_Val;
11820 end Utils;
11821
11822 with Decls;
11823 procedure Main is
11824 begin
11825    Decls.Lib_Task.Start;
11826 end;
11827 @end smallexample
11828
11829 @noindent
11830 If the above example is compiled in the default static elaboration
11831 mode, then a circularity occurs. The circularity comes from the call
11832 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
11833 this call occurs in elaboration code, we need an implicit pragma
11834 @code{Elaborate_All} for @code{Utils}. This means that not only must
11835 the spec and body of @code{Utils} be elaborated before the body
11836 of @code{Decls}, but also the spec and body of any unit that is
11837 @code{with'ed} by the body of @code{Utils} must also be elaborated before
11838 the body of @code{Decls}. This is the transitive implication of
11839 pragma @code{Elaborate_All} and it makes sense, because in general
11840 the body of @code{Put_Val} might have a call to something in a
11841 @code{with'ed} unit.
11842
11843 In this case, the body of Utils (actually its spec) @code{with's}
11844 @code{Decls}. Unfortunately this means that the body of @code{Decls}
11845 must be elaborated before itself, in case there is a call from the
11846 body of @code{Utils}.
11847
11848 Here is the exact chain of events we are worrying about:
11849
11850 @enumerate
11851 @item
11852 In the body of @code{Decls} a call is made from within the body of a library
11853 task to a subprogram in the package @code{Utils}. Since this call may
11854 occur at elaboration time (given that the task is activated at elaboration
11855 time), we have to assume the worst, i.e. that the
11856 call does happen at elaboration time.
11857
11858 @item
11859 This means that the body and spec of @code{Util} must be elaborated before
11860 the body of @code{Decls} so that this call does not cause an access before
11861 elaboration.
11862
11863 @item
11864 Within the body of @code{Util}, specifically within the body of
11865 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
11866 by this package.
11867
11868 @item
11869 One such @code{with}'ed package is package @code{Decls}, so there
11870 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
11871 In fact there is such a call in this example, but we would have to
11872 assume that there was such a call even if it were not there, since
11873 we are not supposed to write the body of @code{Decls} knowing what
11874 is in the body of @code{Utils}; certainly in the case of the
11875 static elaboration model, the compiler does not know what is in
11876 other bodies and must assume the worst.
11877
11878 @item
11879 This means that the spec and body of @code{Decls} must also be
11880 elaborated before we elaborate the unit containing the call, but
11881 that unit is @code{Decls}! This means that the body of @code{Decls}
11882 must be elaborated before itself, and that's a circularity.
11883 @end enumerate
11884
11885 @noindent
11886 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
11887 the body of @code{Decls} you will get a true Ada Reference Manual
11888 circularity that makes the program illegal.
11889
11890 In practice, we have found that problems with the static model of
11891 elaboration in existing code often arise from library tasks, so
11892 we must address this particular situation.
11893
11894 Note that if we compile and run the program above, using the dynamic model of
11895 elaboration (that is to say use the @option{-gnatE} switch),
11896 then it compiles, binds,
11897 links, and runs, printing the expected result of 2. Therefore in some sense
11898 the circularity here is only apparent, and we need to capture
11899 the properties of this program that  distinguish it from other library-level
11900 tasks that have real elaboration problems.
11901
11902 We have four possible answers to this question:
11903
11904 @itemize @bullet
11905
11906 @item
11907 Use the dynamic model of elaboration.
11908
11909 If we use the @option{-gnatE} switch, then as noted above, the program works.
11910 Why is this? If we examine the task body, it is apparent that the task cannot
11911 proceed past the
11912 @code{accept} statement until after elaboration has been completed, because
11913 the corresponding entry call comes from the main program, not earlier.
11914 This is why the dynamic model works here. But that's really giving
11915 up on a precise analysis, and we prefer to take this approach only if we cannot
11916 solve the
11917 problem in any other manner. So let us examine two ways to reorganize
11918 the program to avoid the potential elaboration problem.
11919
11920 @item
11921 Split library tasks into separate packages.
11922
11923 Write separate packages, so that library tasks are isolated from
11924 other declarations as much as possible. Let us look at a variation on
11925 the above program.
11926
11927 @smallexample
11928 package Decls1 is
11929   task Lib_Task is
11930      entry Start;
11931   end Lib_Task;
11932 end Decls1;
11933
11934 with Utils;
11935 package body Decls1 is
11936   task body Lib_Task is
11937   begin
11938      accept Start;
11939      Utils.Put_Val (2);
11940   end Lib_Task;
11941 end Decls1;
11942
11943 package Decls2 is
11944   type My_Int is new Integer;
11945   function Ident (M : My_Int) return My_Int;
11946 end Decls2;
11947
11948 with Utils;
11949 package body Decls2 is
11950   function Ident (M : My_Int) return My_Int is
11951   begin
11952      return M;
11953   end Ident;
11954 end Decls2;
11955
11956 with Decls2;
11957 package Utils is
11958   procedure Put_Val (Arg : Decls2.My_Int);
11959 end Utils;
11960
11961 with Text_IO;
11962 package body Utils is
11963   procedure Put_Val (Arg : Decls2.My_Int) is
11964   begin
11965      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
11966   end Put_Val;
11967 end Utils;
11968
11969 with Decls1;
11970 procedure Main is
11971 begin
11972    Decls1.Lib_Task.Start;
11973 end;
11974 @end smallexample
11975
11976 @noindent
11977 All we have done is to split @code{Decls} into two packages, one
11978 containing the library task, and one containing everything else. Now
11979 there is no cycle, and the program compiles, binds, links and executes
11980 using the default static model of elaboration.
11981
11982 @item
11983 Declare separate task types.
11984
11985 A significant part of the problem arises because of the use of the
11986 single task declaration form. This means that the elaboration of
11987 the task type, and the elaboration of the task itself (i.e. the
11988 creation of the task) happen at the same time. A good rule
11989 of style in Ada 95 is to always create explicit task types. By
11990 following the additional step of placing task objects in separate
11991 packages from the task type declaration, many elaboration problems
11992 are avoided. Here is another modified example of the example program:
11993
11994 @smallexample
11995 package Decls is
11996   task type Lib_Task_Type is
11997      entry Start;
11998   end Lib_Task_Type;
11999
12000   type My_Int is new Integer;
12001
12002   function Ident (M : My_Int) return My_Int;
12003 end Decls;
12004
12005 with Utils;
12006 package body Decls is
12007   task body Lib_Task_Type is
12008   begin
12009      accept Start;
12010      Utils.Put_Val (2);
12011   end Lib_Task_Type;
12012
12013   function Ident (M : My_Int) return My_Int is
12014   begin
12015      return M;
12016   end Ident;
12017 end Decls;
12018
12019 with Decls;
12020 package Utils is
12021   procedure Put_Val (Arg : Decls.My_Int);
12022 end Utils;
12023
12024 with Text_IO;
12025 package body Utils is
12026   procedure Put_Val (Arg : Decls.My_Int) is
12027   begin
12028      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
12029   end Put_Val;
12030 end Utils;
12031
12032 with Decls;
12033 package Declst is
12034    Lib_Task : Decls.Lib_Task_Type;
12035 end Declst;
12036
12037 with Declst;
12038 procedure Main is
12039 begin
12040    Declst.Lib_Task.Start;
12041 end;
12042 @end smallexample
12043
12044 @noindent
12045 What we have done here is to replace the @code{task} declaration in
12046 package @code{Decls} with a @code{task type} declaration. Then we
12047 introduce a separate package @code{Declst} to contain the actual
12048 task object. This separates the elaboration issues for
12049 the @code{task type}
12050 declaration, which causes no trouble, from the elaboration issues
12051 of the task object, which is also unproblematic, since it is now independent
12052 of the elaboration of  @code{Utils}.
12053 This separation of concerns also corresponds to
12054 a generally sound engineering principle of separating declarations
12055 from instances. This version of the program also compiles, binds, links,
12056 and executes, generating the expected output.
12057
12058 @item
12059 Use No_Entry_Calls_In_Elaboration_Code restriction.
12060 @cindex No_Entry_Calls_In_Elaboration_Code
12061
12062 The previous two approaches described how a program can be restructured
12063 to avoid the special problems caused by library task bodies. in practice,
12064 however, such restructuring may be difficult to apply to existing legacy code,
12065 so we must consider solutions that do not require massive rewriting.
12066
12067 Let us consider more carefully why our original sample program works
12068 under the dynamic model of elaboration. The reason is that the code
12069 in the task body blocks immediately on the @code{accept}
12070 statement. Now of course there is nothing to prohibit elaboration
12071 code from making entry calls (for example from another library level task),
12072 so we cannot tell in isolation that
12073 the task will not execute the accept statement  during elaboration.
12074
12075 However, in practice it is very unusual to see elaboration code
12076 make any entry calls, and the pattern of tasks starting
12077 at elaboration time and then immediately blocking on @code{accept} or
12078 @code{select} statements is very common. What this means is that
12079 the compiler is being too pessimistic when it analyzes the
12080 whole package body as though it might be executed at elaboration
12081 time.
12082
12083 If we know that the elaboration code contains no entry calls, (a very safe
12084 assumption most of the time, that could almost be made the default
12085 behavior), then we can compile all units of the program under control
12086 of the following configuration pragma:
12087
12088 @smallexample
12089 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
12090 @end smallexample
12091
12092 @noindent
12093 This pragma can be placed in the @file{gnat.adc} file in the usual
12094 manner. If we take our original unmodified program and compile it
12095 in the presence of a @file{gnat.adc} containing the above pragma,
12096 then once again, we can compile, bind, link, and execute, obtaining
12097 the expected result. In the presence of this pragma, the compiler does
12098 not trace calls in a task body, that appear after the first @code{accept}
12099 or @code{select} statement, and therefore does not report a potential
12100 circularity in the original program.
12101
12102 The compiler will check to the extent it can that the above
12103 restriction is not violated, but it is not always possible to do a
12104 complete check at compile time, so it is important to use this
12105 pragma only if the stated restriction is in fact met, that is to say
12106 no task receives an entry call before elaboration of all units is completed.
12107
12108 @end itemize
12109
12110 @node Mixing Elaboration Models
12111 @section Mixing Elaboration Models
12112 @noindent
12113 So far, we have assumed that the entire program is either compiled
12114 using the dynamic model or static model, ensuring consistency. It
12115 is possible to mix the two models, but rules have to be followed
12116 if this mixing is done to ensure that elaboration checks are not
12117 omitted.
12118
12119 The basic rule is that @emph{a unit compiled with the static model cannot
12120 be @code{with'ed} by a unit compiled with the dynamic model}. The
12121 reason for this is that in the static model, a unit assumes that
12122 its clients guarantee to use (the equivalent of) pragma
12123 @code{Elaborate_All} so that no elaboration checks are required
12124 in inner subprograms, and this assumption is violated if the
12125 client is compiled with dynamic checks.
12126
12127 The precise rule is as follows. A unit that is compiled with dynamic
12128 checks can only @code{with} a unit that meets at least one of the
12129 following criteria:
12130
12131 @itemize @bullet
12132
12133 @item
12134 The @code{with'ed} unit is itself compiled with dynamic elaboration
12135 checks (that is with the @option{-gnatE} switch.
12136
12137 @item
12138 The @code{with'ed} unit is an internal GNAT implementation unit from
12139 the System, Interfaces, Ada, or GNAT hierarchies.
12140
12141 @item
12142 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
12143
12144 @item
12145 The @code{with'ing} unit (that is the client) has an explicit pragma
12146 @code{Elaborate_All} for the @code{with'ed} unit.
12147
12148 @end itemize
12149
12150 @noindent
12151 If this rule is violated, that is if a unit with dynamic elaboration
12152 checks @code{with's} a unit that does not meet one of the above four
12153 criteria, then the binder (@code{gnatbind}) will issue a warning
12154 similar to that in the following example:
12155
12156 @smallexample
12157 warning: "x.ads" has dynamic elaboration checks and with's
12158 warning:   "y.ads" which has static elaboration checks
12159 @end smallexample
12160
12161 @noindent
12162 These warnings indicate that the rule has been violated, and that as a result
12163 elaboration checks may be missed in the resulting executable file.
12164 This warning may be suppressed using the @code{-ws} binder switch
12165 in the usual manner.
12166
12167 One useful application of this mixing rule is in the case of a subsystem
12168 which does not itself @code{with} units from the remainder of the
12169 application. In this case, the entire subsystem can be compiled with
12170 dynamic checks to resolve a circularity in the subsystem, while
12171 allowing the main application that uses this subsystem to be compiled
12172 using the more reliable default static model.
12173
12174 @node What to Do If the Default Elaboration Behavior Fails
12175 @section What to Do If the Default Elaboration Behavior Fails
12176
12177 @noindent
12178 If the binder cannot find an acceptable order, it outputs detailed
12179 diagnostics. For example:
12180 @smallexample
12181 @group
12182 @iftex
12183 @leftskip=0cm
12184 @end iftex
12185 error: elaboration circularity detected
12186 info:   "proc (body)" must be elaborated before "pack (body)"
12187 info:     reason: Elaborate_All probably needed in unit "pack (body)"
12188 info:     recompile "pack (body)" with -gnatwl
12189 info:                             for full details
12190 info:       "proc (body)"
12191 info:         is needed by its spec:
12192 info:       "proc (spec)"
12193 info:         which is withed by:
12194 info:       "pack (body)"
12195 info:  "pack (body)" must be elaborated before "proc (body)"
12196 info:     reason: pragma Elaborate in unit "proc (body)"
12197 @end group
12198
12199 @end smallexample
12200
12201 @noindent
12202 In this case we have a cycle that the binder cannot break. On the one
12203 hand, there is an explicit pragma Elaborate in @code{proc} for
12204 @code{pack}. This means that the body of @code{pack} must be elaborated
12205 before the body of @code{proc}. On the other hand, there is elaboration
12206 code in @code{pack} that calls a subprogram in @code{proc}. This means
12207 that for maximum safety, there should really be a pragma
12208 Elaborate_All in @code{pack} for @code{proc} which would require that
12209 the body of @code{proc} be elaborated before the body of
12210 @code{pack}. Clearly both requirements cannot be satisfied.
12211 Faced with a circularity of this kind, you have three different options.
12212
12213 @table @asis
12214 @item Fix the program
12215 The most desirable option from the point of view of long-term maintenance
12216 is to rearrange the program so that the elaboration problems are avoided.
12217 One useful technique is to place the elaboration code into separate
12218 child packages. Another is to move some of the initialization code to
12219 explicitly called subprograms, where the program controls the order
12220 of initialization explicitly. Although this is the most desirable option,
12221 it may be impractical and involve too much modification, especially in
12222 the case of complex legacy code.
12223
12224 @item Perform dynamic checks
12225 If the compilations are done using the
12226 @option{-gnatE}
12227 (dynamic elaboration check) switch, then GNAT behaves in
12228 a quite different manner. Dynamic checks are generated for all calls
12229 that could possibly result in raising an exception. With this switch,
12230 the compiler does not generate implicit @code{Elaborate_All} pragmas.
12231 The behavior then is exactly as specified in the Ada 95 Reference Manual.
12232 The binder will generate an executable program that may or may not
12233 raise @code{Program_Error}, and then it is the programmer's job to ensure
12234 that it does not raise an exception. Note that it is important to
12235 compile all units with the switch, it cannot be used selectively.
12236
12237 @item Suppress checks
12238 The drawback of dynamic checks is that they generate a
12239 significant overhead at run time, both in space and time. If you
12240 are absolutely sure that your program cannot raise any elaboration
12241 exceptions, and you still want to use the dynamic elaboration model,
12242 then you can use the configuration pragma
12243 @code{Suppress (Elaboration_Checks)} to suppress all such checks. For
12244 example this pragma could be placed in the @file{gnat.adc} file.
12245
12246 @item Suppress checks selectively
12247 When you know that certain calls in elaboration code cannot possibly
12248 lead to an elaboration error, and the binder nevertheless generates warnings
12249 on those calls and inserts Elaborate_All pragmas that lead to elaboration
12250 circularities, it is possible to remove those warnings locally and obtain
12251 a program that will bind. Clearly this can be unsafe, and it is the
12252 responsibility of the programmer to make sure that the resulting program has
12253 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
12254 be used with different granularity to suppress warnings and break
12255 elaboration circularities:
12256
12257 @itemize @bullet
12258 @item
12259 Place the pragma that names the called subprogram in the declarative part
12260 that contains the call.
12261
12262 @item
12263 Place the pragma in the declarative part, without naming an entity. This
12264 disables warnings on all calls in the corresponding  declarative region.
12265
12266 @item
12267 Place the pragma in the package spec that declares the called subprogram,
12268 and name the subprogram. This disables warnings on all elaboration calls to
12269 that subprogram.
12270
12271 @item
12272 Place the pragma in the package spec that declares the called subprogram,
12273 without naming any entity. This disables warnings on all elaboration calls to
12274 all subprograms declared in this spec.
12275 @end itemize
12276
12277 @noindent
12278 These four cases are listed in order of decreasing safety, and therefore
12279 require increasing programmer care in their application. Consider the
12280 following program:
12281 @smallexample
12282
12283 package Pack1 is
12284   function F1 return Integer;
12285   X1 : Integer;
12286 end Pack1;
12287
12288 package Pack2 is
12289   function F2 return Integer;
12290   function Pure (x : integer) return integer;
12291   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
12292   --  pragma Suppress (Elaboration_Check);              -- (4)
12293 end Pack2;
12294
12295 with Pack2;
12296 package body Pack1 is
12297   function F1 return Integer is
12298   begin
12299     return 100;
12300   end F1;
12301   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
12302 begin
12303   declare
12304     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
12305     --  pragma Suppress(Elaboration_Check);             -- (2)
12306   begin
12307     X1 := Pack2.F2 + 1;                --  Elab. call (2)
12308   end;
12309 end Pack1;
12310
12311 with Pack1;
12312 package body Pack2 is
12313   function F2 return Integer is
12314   begin
12315      return Pack1.F1;
12316   end F2;
12317   function Pure (x : integer) return integer is
12318   begin
12319      return x ** 3 - 3 * x;
12320   end;
12321 end Pack2;
12322
12323 with Pack1, Ada.Text_IO;
12324 procedure Proc3 is
12325 begin
12326   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
12327 end Proc3;
12328 @end smallexample
12329 In the absence of any pragmas, an attempt to bind this program produces
12330 the following diagnostics:
12331 @smallexample
12332 @group
12333 @iftex
12334 @leftskip=.5cm
12335 @end iftex
12336 error: elaboration circularity detected
12337 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
12338 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
12339 info:       recompile "pack1 (body)" with -gnatwl for full details
12340 info:          "pack1 (body)"
12341 info:             must be elaborated along with its spec:
12342 info:          "pack1 (spec)"
12343 info:             which is withed by:
12344 info:          "pack2 (body)"
12345 info:             which must be elaborated along with its spec:
12346 info:          "pack2 (spec)"
12347 info:             which is withed by:
12348 info:          "pack1 (body)"
12349 @end group
12350 @end smallexample
12351 The sources of the circularity are the two calls to @code{Pack2.Pure} and
12352 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
12353 F2 is safe, even though F2 calls F1, because the call appears after the
12354 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
12355 remove the warning on the call. It is also possible to use pragma (2)
12356 because there are no other potentially unsafe calls in the block.
12357
12358 @noindent
12359 The call to @code{Pure} is safe because this function does not depend on the
12360 state of @code{Pack2}. Therefore any call to this function is safe, and it
12361 is correct to place pragma (3) in the corresponding package spec.
12362
12363 @noindent
12364 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
12365 warnings on all calls to functions declared therein. Note that this is not
12366 necessarily safe, and requires more detailed examination of the subprogram
12367 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
12368 be already elaborated.
12369 @end table
12370
12371 @noindent
12372 It is hard to generalize on which of these four approaches should be
12373 taken. Obviously if it is possible to fix the program so that the default
12374 treatment works, this is preferable, but this may not always be practical.
12375 It is certainly simple enough to use
12376 @option{-gnatE}
12377 but the danger in this case is that, even if the GNAT binder
12378 finds a correct elaboration order, it may not always do so,
12379 and certainly a binder from another Ada compiler might not. A
12380 combination of testing and analysis (for which the warnings generated
12381 with the
12382 @option{-gnatwl}
12383 switch can be useful) must be used to ensure that the program is free
12384 of errors. One switch that is useful in this testing is the
12385 @code{-p (pessimistic elaboration order)}
12386 switch for
12387 @code{gnatbind}.
12388 Normally the binder tries to find an order that has the best chance of
12389 of avoiding elaboration problems. With this switch, the binder
12390 plays a devil's advocate role, and tries to choose the order that
12391 has the best chance of failing. If your program works even with this
12392 switch, then it has a better chance of being error free, but this is still
12393 not a guarantee.
12394
12395 For an example of this approach in action, consider the C-tests (executable
12396 tests) from the ACVC suite. If these are compiled and run with the default
12397 treatment, then all but one of them succeed without generating any error
12398 diagnostics from the binder. However, there is one test that fails, and
12399 this is not surprising, because the whole point of this test is to ensure
12400 that the compiler can handle cases where it is impossible to determine
12401 a correct order statically, and it checks that an exception is indeed
12402 raised at run time.
12403
12404 This one test must be compiled and run using the
12405 @option{-gnatE}
12406 switch, and then it passes. Alternatively, the entire suite can
12407 be run using this switch. It is never wrong to run with the dynamic
12408 elaboration switch if your code is correct, and we assume that the
12409 C-tests are indeed correct (it is less efficient, but efficiency is
12410 not a factor in running the ACVC tests.)
12411
12412 @node Elaboration for Access-to-Subprogram Values
12413 @section Elaboration for Access-to-Subprogram Values
12414 @cindex Access-to-subprogram
12415
12416 @noindent
12417 The introduction of access-to-subprogram types in Ada 95 complicates
12418 the handling of elaboration. The trouble is that it becomes
12419 impossible to tell at compile time which procedure
12420 is being called. This means that it is not possible for the binder
12421 to analyze the elaboration requirements in this case.
12422
12423 If at the point at which the access value is created
12424 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
12425 the body of the subprogram is
12426 known to have been elaborated, then the access value is safe, and its use
12427 does not require a check. This may be achieved by appropriate arrangement
12428 of the order of declarations if the subprogram is in the current unit,
12429 or, if the subprogram is in another unit, by using pragma
12430 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
12431 on the referenced unit.
12432
12433 If the referenced body is not known to have been elaborated at the point
12434 the access value is created, then any use of the access value must do a
12435 dynamic check, and this dynamic check will fail and raise a
12436 @code{Program_Error} exception if the body has not been elaborated yet.
12437 GNAT will generate the necessary checks, and in addition, if the
12438 @option{-gnatwl}
12439 switch is set, will generate warnings that such checks are required.
12440
12441 The use of dynamic dispatching for tagged types similarly generates
12442 a requirement for dynamic checks, and premature calls to any primitive
12443 operation of a tagged type before the body of the operation has been elaborated,
12444 will result in the raising of @code{Program_Error}.
12445
12446 @node Summary of Procedures for Elaboration Control
12447 @section Summary of Procedures for Elaboration Control
12448 @cindex Elaboration control
12449
12450 @noindent
12451 First, compile your program with the default options, using none of
12452 the special elaboration control switches. If the binder successfully
12453 binds your program, then you can be confident that, apart from issues
12454 raised by the use of access-to-subprogram types and dynamic dispatching,
12455 the program is free of elaboration errors. If it is important that the
12456 program be portable, then use the
12457 @option{-gnatwl}
12458 switch to generate warnings about missing @code{Elaborate_All}
12459 pragmas, and supply the missing pragmas.
12460
12461 If the program fails to bind using the default static elaboration
12462 handling, then you can fix the program to eliminate the binder
12463 message, or recompile the entire program with the
12464 @option{-gnatE} switch to generate dynamic elaboration checks,
12465 and, if you are sure there really are no elaboration problems,
12466 use a global pragma @code{Suppress (Elaboration_Checks)}.
12467
12468 @node Other Elaboration Order Considerations
12469 @section Other Elaboration Order Considerations
12470 @noindent
12471 This section has been entirely concerned with the issue of finding a valid
12472 elaboration order, as defined by the Ada Reference Manual. In a case
12473 where several elaboration orders are valid, the task is to find one
12474 of the possible valid elaboration orders (and the static model in GNAT
12475 will ensure that this is achieved).
12476
12477 The purpose of the elaboration rules in the Ada Reference Manual is to
12478 make sure that no entity is accessed before it has been elaborated. For
12479 a subprogram, this means that the spec and body must have been elaborated
12480 before the subprogram is called. For an object, this means that the object
12481 must have been elaborated before its value is read or written. A violation
12482 of either of these two requirements is an access before elaboration order,
12483 and this section has been all about avoiding such errors.
12484
12485 In the case where more than one order of elaboration is possible, in the
12486 sense that access before elaboration errors are avoided, then any one of
12487 the orders is "correct" in the sense that it meets the requirements of
12488 the Ada Reference Manual, and no such error occurs.
12489
12490 However, it may be the case for a given program, that there are
12491 constraints on the order of elaboration that come not from consideration
12492 of avoiding elaboration errors, but rather from extra-lingual logic
12493 requirements. Consider this example:
12494
12495 @smallexample
12496 with Init_Constants;
12497 package Constants is
12498    X : Integer := 0;
12499    Y : Integer := 0;
12500 end Constants;
12501
12502 package Init_Constants is
12503    procedure Calc;
12504 end Init_Constants;
12505
12506 with Constants;
12507 package body Init_Constants is
12508    procedure Calc is begin null; end;
12509 begin
12510    Constants.X := 3;
12511    Constants.Y := 4;
12512 end Init_Constants;
12513
12514 with Constants;
12515 package Calc is
12516    Z : Integer := Constants.X + Constants.Y;
12517 end Calc;
12518
12519 with Calc;
12520 with Text_IO; use Text_IO;
12521 procedure Main is
12522 begin
12523    Put_Line (Calc.Z'Img);
12524 end Main;
12525 @end smallexample
12526
12527 @noindent
12528 In this example, there is more than one valid order of elaboration. For
12529 example both the following are correct orders:
12530
12531 @smallexample
12532 Init_Constants spec
12533 Constants spec
12534 Calc spec
12535 Main body
12536 Init_Constants body
12537
12538   and
12539
12540 Init_Constants spec
12541 Init_Constants body
12542 Constants spec
12543 Calc spec
12544 Main body
12545 @end smallexample
12546
12547 @noindent
12548 There is no language rule to prefer one or the other, both are correct
12549 from an order of elaboration point of view. But the programmatic effects
12550 of the two orders are very different. In the first, the elaboration routine
12551 of @code{Calc} initializes @code{Z} to zero, and then the main program
12552 runs with this value of zero. But in the second order, the elaboration
12553 routine of @code{Calc} runs after the body of Init_Constants has set
12554 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
12555 runs.
12556
12557 One could perhaps by applying pretty clever non-artificial intelligence
12558 to the situation guess that it is more likely that the second order of
12559 elaboration is the one desired, but there is no formal linguistic reason
12560 to prefer one over the other. In fact in this particular case, GNAT will
12561 prefer the second order, because of the rule that bodies are elaborated
12562 as soon as possible, but it's just luck that this is what was wanted
12563 (if indeed the second order was preferred).
12564
12565 If the program cares about the order of elaboration routines in a case like
12566 this, it is important to specify the order required. In this particular
12567 case, that could have been achieved by adding to the spec of Calc:
12568
12569 @smallexample
12570 pragma Elaborate_All (Constants);
12571 @end smallexample
12572
12573 @noindent
12574 which requires that the body (if any) and spec of @code{Constants},
12575 as well as the body and spec of any unit @code{with}'ed by
12576 @code{Constants} be elaborated before @code{Calc} is elaborated.
12577
12578 Clearly no automatic method can always guess which alternative you require,
12579 and if you are working with legacy code that had constraints of this kind
12580 which were not properly specified by adding @code{Elaborate} or
12581 @code{Elaborate_All} pragmas, then indeed it is possible that two different
12582 compilers can choose different orders.
12583
12584 The @code{gnatbind}
12585 @code{-p} switch may be useful in smoking
12586 out problems. This switch causes bodies to be elaborated as late as possible
12587 instead of as early as possible. In the example above, it would have forced
12588 the choice of the first elaboration order. If you get different results
12589 when using this switch, and particularly if one set of results is right,
12590 and one is wrong as far as you are concerned, it shows that you have some
12591 missing @code{Elaborate} pragmas. For the example above, we have the
12592 following output:
12593
12594 @smallexample
12595 gnatmake -f -q main
12596 main
12597  7
12598 gnatmake -f -q main -bargs -p
12599 main
12600  0
12601 @end smallexample
12602
12603 @noindent
12604 It is of course quite unlikely that both these results are correct, so
12605 it is up to you in a case like this to investigate the source of the
12606 difference, by looking at the two elaboration orders that are chosen,
12607 and figuring out which is correct, and then adding the necessary
12608 @code{Elaborate_All} pragmas to ensure the desired order.
12609
12610 @node The Cross-Referencing Tools gnatxref and gnatfind
12611 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12612 @findex gnatxref
12613 @findex gnatfind
12614
12615 @noindent
12616 The compiler generates cross-referencing information (unless
12617 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12618 This information indicates where in the source each entity is declared and
12619 referenced. Note that entities in package Standard are not included, but
12620 entities in all other predefined units are included in the output.
12621
12622 Before using any of these two tools, you need to compile successfully your
12623 application, so that GNAT gets a chance to generate the cross-referencing
12624 information.
12625
12626 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12627 information to provide the user with the capability to easily locate the
12628 declaration and references to an entity. These tools are quite similar,
12629 the difference being that @code{gnatfind} is intended for locating
12630 definitions and/or references to a specified entity or entities, whereas
12631 @code{gnatxref} is oriented to generating a full report of all
12632 cross-references.
12633
12634 To use these tools, you must not compile your application using the
12635 @option{-gnatx} switch on the @file{gnatmake} command line (@inforef{The
12636 GNAT Make Program gnatmake,,gnat_ug}). Otherwise, cross-referencing
12637 information will not be generated.
12638
12639 @menu
12640 * gnatxref Switches::
12641 * gnatfind Switches::
12642 * Project Files for gnatxref and gnatfind::
12643 * Regular Expressions in gnatfind and gnatxref::
12644 * Examples of gnatxref Usage::
12645 * Examples of gnatfind Usage::
12646 @end menu
12647
12648 @node gnatxref Switches
12649 @section @code{gnatxref} Switches
12650
12651 @noindent
12652 The command lines for @code{gnatxref} is:
12653 @smallexample
12654 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
12655 @end smallexample
12656
12657 @noindent
12658 where
12659
12660 @table @code
12661 @item sourcefile1, sourcefile2
12662 identifies the source files for which a report is to be generated. The
12663 'with'ed units will be processed too. You must provide at least one file.
12664
12665 These file names are considered to be regular expressions, so for instance
12666 specifying 'source*.adb' is the same as giving every file in the current
12667 directory whose name starts with 'source' and whose extension is 'adb'.
12668
12669 @end table
12670
12671 @noindent
12672 The switches can be :
12673 @table @code
12674 @item -a
12675 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12676 the read-only files found in the library search path. Otherwise, these files
12677 will be ignored. This option can be used to protect Gnat sources or your own
12678 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12679 much faster, and their output much smaller.
12680
12681 @item -aIDIR
12682 When looking for source files also look in directory DIR. The order in which
12683 source file search is undertaken is the same as for @file{gnatmake}.
12684
12685 @item -aODIR
12686 When searching for library and object files, look in directory
12687 DIR. The order in which library files are searched is the same as for
12688 @file{gnatmake}.
12689
12690 @item -nostdinc
12691 Do not look for sources in the system default directory.
12692
12693 @item -nostdlib
12694 Do not look for library files in the system default directory.
12695
12696 @item --RTS=@var{rts-path}
12697 @cindex @code{--RTS} (@code{gnatxref})
12698 Specifies the default location of the runtime library. Same meaning as the
12699 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
12700
12701 @item -d
12702 If this switch is set @code{gnatxref} will output the parent type
12703 reference for each matching derived types.
12704
12705 @item -f
12706 If this switch is set, the output file names will be preceded by their
12707 directory (if the file was found in the search path). If this switch is
12708 not set, the directory will not be printed.
12709
12710 @item -g
12711 If this switch is set, information is output only for library-level
12712 entities, ignoring local entities. The use of this switch may accelerate
12713 @code{gnatfind} and @code{gnatxref}.
12714
12715 @item -IDIR
12716 Equivalent to @samp{-aODIR -aIDIR}.
12717
12718 @item -pFILE
12719 Specify a project file to use @xref{Project Files}.
12720 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12721 project file in the current directory.
12722
12723 If a project file is either specified or found by the tools, then the content
12724 of the source directory and object directory lines are added as if they
12725 had been specified respectively by @samp{-aI}
12726 and @samp{-aO}.
12727 @item -u
12728 Output only unused symbols. This may be really useful if you give your
12729 main compilation unit on the command line, as @code{gnatxref} will then
12730 display every unused entity and 'with'ed package.
12731
12732 @item -v
12733 Instead of producing the default output, @code{gnatxref} will generate a
12734 @file{tags} file that can be used by vi. For examples how to use this
12735 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
12736 to the standard output, thus you will have to redirect it to a file.
12737
12738 @end table
12739
12740 All these switches may be in any order on the command line, and may even
12741 appear after the file names. They need not be separated by spaces, thus
12742 you can say @samp{gnatxref -ag} instead of
12743 @samp{gnatxref -a -g}.
12744
12745 @node gnatfind Switches
12746 @section @code{gnatfind} Switches
12747
12748 @noindent
12749 The command line for @code{gnatfind} is:
12750
12751 @smallexample
12752 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
12753       [file1 file2 ...]
12754 @end smallexample
12755
12756 @noindent
12757 where
12758
12759 @table @code
12760 @item pattern
12761 An entity will be output only if it matches the regular expression found
12762 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
12763
12764 Omitting the pattern is equivalent to specifying @samp{*}, which
12765 will match any entity. Note that if you do not provide a pattern, you
12766 have to provide both a sourcefile and a line.
12767
12768 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12769 for matching purposes. At the current time there is no support for
12770 8-bit codes other than Latin-1, or for wide characters in identifiers.
12771
12772 @item sourcefile
12773 @code{gnatfind} will look for references, bodies or declarations
12774 of symbols referenced in @file{sourcefile}, at line @samp{line}
12775 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
12776 for syntax examples.
12777
12778 @item line
12779 is a decimal integer identifying the line number containing
12780 the reference to the entity (or entities) to be located.
12781
12782 @item column
12783 is a decimal integer identifying the exact location on the
12784 line of the first character of the identifier for the
12785 entity reference. Columns are numbered from 1.
12786
12787 @item file1 file2 ...
12788 The search will be restricted to these files. If none are given, then
12789 the search will be done for every library file in the search path.
12790 These file must appear only after the pattern or sourcefile.
12791
12792 These file names are considered to be regular expressions, so for instance
12793 specifying 'source*.adb' is the same as giving every file in the current
12794 directory whose name starts with 'source' and whose extension is 'adb'.
12795
12796 Not that if you specify at least one file in this part, @code{gnatfind} may
12797 sometimes not be able to find the body of the subprograms...
12798
12799 @end table
12800
12801 At least one of 'sourcefile' or 'pattern' has to be present on
12802 the command line.
12803
12804 The following switches are available:
12805 @table @code
12806
12807 @item -a
12808 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12809 the read-only files found in the library search path. Otherwise, these files
12810 will be ignored. This option can be used to protect Gnat sources or your own
12811 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12812 much faster, and their output much smaller.
12813
12814 @item -aIDIR
12815 When looking for source files also look in directory DIR. The order in which
12816 source file search is undertaken is the same as for @file{gnatmake}.
12817
12818 @item -aODIR
12819 When searching for library and object files, look in directory
12820 DIR. The order in which library files are searched is the same as for
12821 @file{gnatmake}.
12822
12823 @item -nostdinc
12824 Do not look for sources in the system default directory.
12825
12826 @item -nostdlib
12827 Do not look for library files in the system default directory.
12828
12829 @item --RTS=@var{rts-path}
12830 @cindex @code{--RTS} (@code{gnatfind})
12831 Specifies the default location of the runtime library. Same meaning as the
12832 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
12833
12834 @item -d
12835 If this switch is set, then @code{gnatfind} will output the parent type
12836 reference for each matching derived types.
12837
12838 @item -e
12839 By default, @code{gnatfind} accept the simple regular expression set for
12840 @samp{pattern}. If this switch is set, then the pattern will be
12841 considered as full Unix-style regular expression.
12842
12843 @item -f
12844 If this switch is set, the output file names will be preceded by their
12845 directory (if the file was found in the search path). If this switch is
12846 not set, the directory will not be printed.
12847
12848 @item -g
12849 If this switch is set, information is output only for library-level
12850 entities, ignoring local entities. The use of this switch may accelerate
12851 @code{gnatfind} and @code{gnatxref}.
12852
12853 @item -IDIR
12854 Equivalent to @samp{-aODIR -aIDIR}.
12855
12856 @item -pFILE
12857 Specify a project file (@pxref{Project Files}) to use.
12858 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12859 project file in the current directory.
12860
12861 If a project file is either specified or found by the tools, then the content
12862 of the source directory and object directory lines are added as if they
12863 had been specified respectively by @samp{-aI} and
12864 @samp{-aO}.
12865
12866 @item -r
12867 By default, @code{gnatfind} will output only the information about the
12868 declaration, body or type completion of the entities. If this switch is
12869 set, the @code{gnatfind} will locate every reference to the entities in
12870 the files specified on the command line (or in every file in the search
12871 path if no file is given on the command line).
12872
12873 @item -s
12874 If this switch is set, then @code{gnatfind} will output the content
12875 of the Ada source file lines were the entity was found.
12876
12877 @item -t
12878 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12879 the specified type. It act like -d option but recursively from parent
12880 type to parent type. When this switch is set it is not possible to
12881 specify more than one file.
12882
12883 @end table
12884
12885 All these switches may be in any order on the command line, and may even
12886 appear after the file names. They need not be separated by spaces, thus
12887 you can say @samp{gnatxref -ag} instead of
12888 @samp{gnatxref -a -g}.
12889
12890 As stated previously, gnatfind will search in every directory in the
12891 search path. You can force it to look only in the current directory if
12892 you specify @code{*} at the end of the command line.
12893
12894
12895 @node Project Files for gnatxref and gnatfind
12896 @section Project Files for @command{gnatxref} and @command{gnatfind}
12897
12898 @noindent
12899 Project files allow a programmer to specify how to compile its
12900 application, where to find sources,... These files are used primarily by
12901 the Glide Ada mode, but they can also be used by the two tools
12902 @code{gnatxref} and @code{gnatfind}.
12903
12904 A project file name must end with @file{.adp}. If a single one is
12905 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12906 extract the information from it. If multiple project files are found, none of
12907 them is read, and you have to use the @samp{-p} switch to specify the one
12908 you want to use.
12909
12910 The following lines can be included, even though most of them have default
12911 values which can be used in most cases.
12912 The lines can be entered in any order in the file.
12913 Except for @samp{src_dir} and @samp{obj_dir}, you can only have one instance of
12914 each line. If you have multiple instances, only the last one is taken into
12915 account.
12916
12917 @table @code
12918 @item src_dir=DIR         [default: "./"]
12919 specifies a directory where to look for source files. Multiple src_dir lines
12920 can be specified and they will be searched in the order they
12921 are specified.
12922
12923 @item obj_dir=DIR         [default: "./"]
12924 specifies a directory where to look for object and library files. Multiple
12925 obj_dir lines can be specified and they will be searched in the order they
12926 are specified
12927
12928 @item comp_opt=SWITCHES   [default: ""]
12929 creates a variable which can be referred to subsequently by using
12930 the @samp{$@{comp_opt@}} notation. This is intended to store the default
12931 switches given to @file{gnatmake} and @file{gcc}.
12932
12933 @item bind_opt=SWITCHES   [default: ""]
12934 creates a variable which can be referred to subsequently by using
12935 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12936 switches given to @file{gnatbind}.
12937
12938 @item link_opt=SWITCHES   [default: ""]
12939 creates a variable which can be referred to subsequently by using
12940 the @samp{$@{link_opt@}} notation. This is intended to store the default
12941 switches given to @file{gnatlink}.
12942
12943 @item main=EXECUTABLE     [default: ""]
12944 specifies the name of the executable for the application. This variable can
12945 be referred to in the following lines by using the @samp{$@{main@}} notation.
12946
12947 @item comp_cmd=COMMAND    [default: "gcc -c -I$@{src_dir@} -g -gnatq"]
12948 specifies the command used to compile a single file in the application.
12949
12950 @item make_cmd=COMMAND    [default: "gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"]
12951 specifies the command used to recompile the whole application.
12952
12953 @item run_cmd=COMMAND     [default: "$@{main@}"]
12954 specifies the command used to run the application.
12955
12956 @item debug_cmd=COMMAND   [default: "gdb $@{main@}"]
12957 specifies the command used to debug the application
12958
12959 @end table
12960
12961 @code{gnatxref} and @code{gnatfind} only take into account the @samp{src_dir}
12962 and @samp{obj_dir} lines, and ignore the others.
12963
12964 @node Regular Expressions in gnatfind and gnatxref
12965 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12966
12967 @noindent
12968 As specified in the section about @code{gnatfind}, the pattern can be a
12969 regular expression. Actually, there are to set of regular expressions
12970 which are recognized by the program :
12971
12972 @table @code
12973 @item globbing patterns
12974 These are the most usual regular expression. They are the same that you
12975 generally used in a Unix shell command line, or in a DOS session.
12976
12977 Here is a more formal grammar :
12978 @smallexample
12979 @group
12980 @iftex
12981 @leftskip=.5cm
12982 @end iftex
12983 regexp ::= term
12984 term   ::= elmt            -- matches elmt
12985 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12986 term   ::= *               -- any string of 0 or more characters
12987 term   ::= ?               -- matches any character
12988 term   ::= [char @{char@}] -- matches any character listed
12989 term   ::= [char - char]   -- matches any character in range
12990 @end group
12991 @end smallexample
12992
12993 @item full regular expression
12994 The second set of regular expressions is much more powerful. This is the
12995 type of regular expressions recognized by utilities such a @file{grep}.
12996
12997 The following is the form of a regular expression, expressed in Ada
12998 reference manual style BNF is as follows
12999
13000 @smallexample
13001 @iftex
13002 @leftskip=.5cm
13003 @end iftex
13004 @group
13005 regexp ::= term @{| term@} -- alternation (term or term ...)
13006
13007 term ::= item @{item@}     -- concatenation (item then item)
13008
13009 item ::= elmt              -- match elmt
13010 item ::= elmt *            -- zero or more elmt's
13011 item ::= elmt +            -- one or more elmt's
13012 item ::= elmt ?            -- matches elmt or nothing
13013 @end group
13014 @group
13015 elmt ::= nschar            -- matches given character
13016 elmt ::= [nschar @{nschar@}]   -- matches any character listed
13017 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
13018 elmt ::= [char - char]     -- matches chars in given range
13019 elmt ::= \ char            -- matches given character
13020 elmt ::= .                 -- matches any single character
13021 elmt ::= ( regexp )        -- parens used for grouping
13022
13023 char ::= any character, including special characters
13024 nschar ::= any character except ()[].*+?^
13025 @end group
13026 @end smallexample
13027
13028 Following are a few examples :
13029
13030 @table @samp
13031 @item abcde|fghi
13032 will match any of the two strings 'abcde' and 'fghi'.
13033
13034 @item abc*d
13035 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
13036
13037 @item [a-z]+
13038 will match any string which has only lowercase characters in it (and at
13039 least one character
13040
13041 @end table
13042 @end table
13043
13044 @node Examples of gnatxref Usage
13045 @section Examples of @code{gnatxref} Usage
13046
13047 @subsection General Usage
13048
13049 @noindent
13050 For the following examples, we will consider the following units :
13051
13052 @smallexample
13053 @group
13054 @cartouche
13055 main.ads:
13056 1: @b{with} Bar;
13057 2: @b{package} Main @b{is}
13058 3:     @b{procedure} Foo (B : @b{in} Integer);
13059 4:     C : Integer;
13060 5: @b{private}
13061 6:     D : Integer;
13062 7: @b{end} Main;
13063
13064 main.adb:
13065 1: @b{package body} Main @b{is}
13066 2:     @b{procedure} Foo (B : @b{in} Integer) @b{is}
13067 3:     @b{begin}
13068 4:        C := B;
13069 5:        D := B;
13070 6:        Bar.Print (B);
13071 7:        Bar.Print (C);
13072 8:     @b{end} Foo;
13073 9: @b{end} Main;
13074
13075 bar.ads:
13076 1: @b{package} Bar @b{is}
13077 2:     @b{procedure} Print (B : Integer);
13078 3: @b{end} bar;
13079 @end cartouche
13080 @end group
13081 @end smallexample
13082
13083 @table @code
13084
13085 @noindent
13086 The first thing to do is to recompile your application (for instance, in
13087 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13088 the cross-referencing information.
13089 You can then issue any of the following commands:
13090
13091 @item gnatxref main.adb
13092 @code{gnatxref} generates cross-reference information for main.adb
13093 and every unit 'with'ed by main.adb.
13094
13095 The output would be:
13096 @smallexample
13097 @iftex
13098 @leftskip=0cm
13099 @end iftex
13100 B                                                      Type: Integer
13101   Decl: bar.ads           2:22
13102 B                                                      Type: Integer
13103   Decl: main.ads          3:20
13104   Body: main.adb          2:20
13105   Ref:  main.adb          4:13     5:13     6:19
13106 Bar                                                    Type: Unit
13107   Decl: bar.ads           1:9
13108   Ref:  main.adb          6:8      7:8
13109        main.ads           1:6
13110 C                                                      Type: Integer
13111   Decl: main.ads          4:5
13112   Modi: main.adb          4:8
13113   Ref:  main.adb          7:19
13114 D                                                      Type: Integer
13115   Decl: main.ads          6:5
13116   Modi: main.adb          5:8
13117 Foo                                                    Type: Unit
13118   Decl: main.ads          3:15
13119   Body: main.adb          2:15
13120 Main                                                    Type: Unit
13121   Decl: main.ads          2:9
13122   Body: main.adb          1:14
13123 Print                                                   Type: Unit
13124   Decl: bar.ads           2:15
13125   Ref:  main.adb          6:12     7:12
13126 @end smallexample
13127
13128 @noindent
13129 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13130 its body is in main.adb, line 1, column 14 and is not referenced any where.
13131
13132 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13133 it referenced in main.adb, line 6 column 12 and line 7 column 12.
13134
13135 @item gnatxref package1.adb package2.ads
13136 @code{gnatxref} will generates cross-reference information for
13137 package1.adb, package2.ads and any other package 'with'ed by any
13138 of these.
13139
13140 @end table
13141
13142 @subsection Using gnatxref with vi
13143
13144 @code{gnatxref} can generate a tags file output, which can be used
13145 directly from @file{vi}. Note that the standard version of @file{vi}
13146 will not work properly with overloaded symbols. Consider using another
13147 free implementation of @file{vi}, such as @file{vim}.
13148
13149 @smallexample
13150 $ gnatxref -v gnatfind.adb > tags
13151 @end smallexample
13152
13153 @noindent
13154 will generate the tags file for @code{gnatfind} itself (if the sources
13155 are in the search path!).
13156
13157 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
13158 (replacing @i{entity} by whatever you are looking for), and vi will
13159 display a new file with the corresponding declaration of entity.
13160
13161 @node Examples of gnatfind Usage
13162 @section Examples of @code{gnatfind} Usage
13163
13164 @table @code
13165
13166 @item gnatfind -f xyz:main.adb
13167 Find declarations for all entities xyz referenced at least once in
13168 main.adb. The references are search in every library file in the search
13169 path.
13170
13171 The directories will be printed as well (as the @samp{-f}
13172 switch is set)
13173
13174 The output will look like:
13175 @smallexample
13176 directory/main.ads:106:14: xyz <= declaration
13177 directory/main.adb:24:10: xyz <= body
13178 directory/foo.ads:45:23: xyz <= declaration
13179 @end smallexample
13180
13181 @noindent
13182 that is to say, one of the entities xyz found in main.adb is declared at
13183 line 12 of main.ads (and its body is in main.adb), and another one is
13184 declared at line 45 of foo.ads
13185
13186 @item gnatfind -fs xyz:main.adb
13187 This is the same command as the previous one, instead @code{gnatfind} will
13188 display the content of the Ada source file lines.
13189
13190 The output will look like:
13191
13192 @smallexample
13193 directory/main.ads:106:14: xyz <= declaration
13194    procedure xyz;
13195 directory/main.adb:24:10: xyz <= body
13196    procedure xyz is
13197 directory/foo.ads:45:23: xyz <= declaration
13198    xyz : Integer;
13199 @end smallexample
13200
13201 @noindent
13202 This can make it easier to find exactly the location your are looking
13203 for.
13204
13205 @item gnatfind -r "*x*":main.ads:123 foo.adb
13206 Find references to all entities containing an x that are
13207 referenced on line 123 of main.ads.
13208 The references will be searched only in main.adb and foo.adb.
13209
13210 @item gnatfind main.ads:123
13211 Find declarations and bodies for all entities that are referenced on
13212 line 123 of main.ads.
13213
13214 This is the same as @code{gnatfind "*":main.adb:123}.
13215
13216 @item gnatfind mydir/main.adb:123:45
13217 Find the declaration for the entity referenced at column 45 in
13218 line 123 of file main.adb in directory mydir. Note that it
13219 is usual to omit the identifier name when the column is given,
13220 since the column position identifies a unique reference.
13221
13222 The column has to be the beginning of the identifier, and should not
13223 point to any character in the middle of the identifier.
13224
13225 @end table
13226
13227 @node File Name Krunching Using gnatkr
13228 @chapter File Name Krunching Using @code{gnatkr}
13229 @findex gnatkr
13230
13231 @noindent
13232 This chapter discusses the method used by the compiler to shorten
13233 the default file names chosen for Ada units so that they do not
13234 exceed the maximum length permitted. It also describes the
13235 @code{gnatkr} utility that can be used to determine the result of
13236 applying this shortening.
13237 @menu
13238 * About gnatkr::
13239 * Using gnatkr::
13240 * Krunching Method::
13241 * Examples of gnatkr Usage::
13242 @end menu
13243
13244 @node About gnatkr
13245 @section About @code{gnatkr}
13246
13247 @noindent
13248 The default file naming rule in GNAT
13249 is that the file name must be derived from
13250 the unit name. The exact default rule is as follows:
13251 @itemize @bullet
13252 @item
13253 Take the unit name and replace all dots by hyphens.
13254 @item
13255 If such a replacement occurs in the
13256 second character position of a name, and the first character is
13257 a, g, s, or i then replace the dot by the character
13258 ~ (tilde)
13259 instead of a minus.
13260 @end itemize
13261 The reason for this exception is to avoid clashes
13262 with the standard names for children of System, Ada, Interfaces,
13263 and GNAT, which use the prefixes s- a- i- and g-
13264 respectively.
13265
13266 The @code{-gnatk@var{nn}}
13267 switch of the compiler activates a "krunching"
13268 circuit that limits file names to nn characters (where nn is a decimal
13269 integer). For example, using OpenVMS,
13270 where the maximum file name length is
13271 39, the value of nn is usually set to 39, but if you want to generate
13272 a set of files that would be usable if ported to a system with some
13273 different maximum file length, then a different value can be specified.
13274 The default value of 39 for OpenVMS need not be specified.
13275
13276 The @code{gnatkr} utility can be used to determine the krunched name for
13277 a given file, when krunched to a specified maximum length.
13278
13279 @node Using gnatkr
13280 @section Using @code{gnatkr}
13281
13282 @noindent
13283 The @code{gnatkr} command has the form
13284
13285 @smallexample
13286 $ gnatkr @var{name} [@var{length}]
13287 @end smallexample
13288
13289
13290 @noindent
13291 @var{name} can be an Ada name with dots or the GNAT name of the unit,
13292 where the dots representing child units or subunit are replaced by
13293 hyphens. The only confusion arises if a name ends in @code{.ads} or
13294 @code{.adb}. @code{gnatkr} takes this to be an extension if there are
13295 no other dots in the name and the whole name is in lowercase.
13296
13297 @var{length} represents the length of the krunched name. The default
13298 when no argument is given is 8 characters. A length of zero stands for
13299 unlimited, in other words do not chop except for system files which are
13300 always 8.
13301
13302 @noindent
13303 The output is the krunched name. The output has an extension only if the
13304 original argument was a file name with an extension.
13305
13306 @node Krunching Method
13307 @section Krunching Method
13308
13309 @noindent
13310 The initial file name is determined by the name of the unit that the file
13311 contains. The name is formed by taking the full expanded name of the
13312 unit and replacing the separating dots with hyphens and
13313 using lowercase
13314 for all letters, except that a hyphen in the second character position is
13315 replaced by a tilde if the first character is
13316 a, i, g, or s.
13317 The extension is @code{.ads} for a
13318 specification and @code{.adb} for a body.
13319 Krunching does not affect the extension, but the file name is shortened to
13320 the specified length by following these rules:
13321
13322 @itemize @bullet
13323 @item
13324 The name is divided into segments separated by hyphens, tildes or
13325 underscores and all hyphens, tildes, and underscores are
13326 eliminated. If this leaves the name short enough, we are done.
13327
13328 @item
13329 If the name is too long, the longest segment is located (left-most if there are two
13330 of equal length), and shortened by dropping its last character. This is
13331 repeated until the name is short enough.
13332
13333 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
13334 to fit the name into 8 characters as required by some operating systems.
13335
13336 @smallexample
13337 our-strings-wide_fixed 22
13338 our strings wide fixed 19
13339 our string  wide fixed 18
13340 our strin   wide fixed 17
13341 our stri    wide fixed 16
13342 our stri    wide fixe  15
13343 our str     wide fixe  14
13344 our str     wid  fixe  13
13345 our str     wid  fix   12
13346 ou  str     wid  fix   11
13347 ou  st      wid  fix   10
13348 ou  st      wi   fix   9
13349 ou  st      wi   fi    8
13350 Final file name: oustwifi.adb
13351 @end smallexample
13352
13353 @item
13354 The file names for all predefined units are always krunched to eight
13355 characters. The krunching of these predefined units uses the following
13356 special prefix replacements:
13357
13358 @table @file
13359 @item ada-
13360 replaced by @file{a-}
13361
13362 @item gnat-
13363 replaced by @file{g-}
13364
13365 @item interfaces-
13366 replaced by @file{i-}
13367
13368 @item system-
13369 replaced by @file{s-}
13370 @end table
13371
13372 These system files have a hyphen in the second character position. That
13373 is why normal user files replace such a character with a
13374 tilde, to
13375 avoid confusion with system file names.
13376
13377 As an example of this special rule, consider
13378 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
13379
13380 @smallexample
13381 ada-strings-wide_fixed 22
13382 a-  strings wide fixed 18
13383 a-  string  wide fixed 17
13384 a-  strin   wide fixed 16
13385 a-  stri    wide fixed 15
13386 a-  stri    wide fixe  14
13387 a-  str     wide fixe  13
13388 a-  str     wid  fixe  12
13389 a-  str     wid  fix   11
13390 a-  st      wid  fix   10
13391 a-  st      wi   fix   9
13392 a-  st      wi   fi    8
13393 Final file name: a-stwifi.adb
13394 @end smallexample
13395 @end itemize
13396
13397 Of course no file shortening algorithm can guarantee uniqueness over all
13398 possible unit names, and if file name krunching is used then it is your
13399 responsibility to ensure that no name clashes occur. The utility
13400 program @code{gnatkr} is supplied for conveniently determining the
13401 krunched name of a file.
13402
13403 @node Examples of gnatkr Usage
13404 @section Examples of @code{gnatkr} Usage
13405
13406 @smallexample
13407 @iftex
13408 @leftskip=0cm
13409 @end iftex
13410 $ gnatkr very_long_unit_name.ads      --> velounna.ads
13411 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
13412 $ gnatkr Grandparent.Parent.Child     --> grparchi
13413 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
13414 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
13415 @end smallexample
13416
13417 @node Preprocessing Using gnatprep
13418 @chapter Preprocessing Using @code{gnatprep}
13419 @findex gnatprep
13420
13421 @noindent
13422 The @code{gnatprep} utility provides
13423 a simple preprocessing capability for Ada programs.
13424 It is designed for use with GNAT, but is not dependent on any special
13425 features of GNAT.
13426
13427 @menu
13428 * Using gnatprep::
13429 * Switches for gnatprep::
13430 * Form of Definitions File::
13431 * Form of Input Text for gnatprep::
13432 @end menu
13433
13434 @node Using gnatprep
13435 @section Using @code{gnatprep}
13436
13437 @noindent
13438 To call @code{gnatprep} use
13439
13440 @smallexample
13441 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
13442 @end smallexample
13443
13444 @noindent
13445 where
13446 @table @code
13447 @item infile
13448 is the full name of the input file, which is an Ada source
13449 file containing preprocessor directives.
13450
13451 @item outfile
13452 is the full name of the output file, which is an Ada source
13453 in standard Ada form. When used with GNAT, this file name will
13454 normally have an ads or adb suffix.
13455
13456 @item deffile
13457 is the full name of a text file containing definitions of
13458 symbols to be referenced by the preprocessor. This argument is
13459 optional, and can be replaced by the use of the @code{-D} switch.
13460
13461 @item switches
13462 is an optional sequence of switches as described in the next section.
13463 @end table
13464
13465 @node Switches for gnatprep
13466 @section Switches for @code{gnatprep}
13467
13468 @table @code
13469
13470 @item -b
13471 Causes both preprocessor lines and the lines deleted by
13472 preprocessing to be replaced by blank lines in the output source file,
13473 preserving line numbers in the output file.
13474
13475 @item -c
13476 Causes both preprocessor lines and the lines deleted
13477 by preprocessing to be retained in the output source as comments marked
13478 with the special string "--! ". This option will result in line numbers
13479 being preserved in the output file.
13480
13481 @item -Dsymbol=value
13482 Defines a new symbol, associated with value. If no value is given on the
13483 command line, then symbol is considered to be @code{True}. This switch
13484 can be used in place of a definition file.
13485
13486
13487 @item -r
13488 Causes a @code{Source_Reference} pragma to be generated that
13489 references the original input file, so that error messages will use
13490 the file name of this original file. The use of this switch implies
13491 that preprocessor lines are not to be removed from the file, so its
13492 use will force @code{-b} mode if
13493 @code{-c}
13494 has not been specified explicitly.
13495
13496 Note that if the file to be preprocessed contains multiple units, then
13497 it will be necessary to @code{gnatchop} the output file from
13498 @code{gnatprep}. If a @code{Source_Reference} pragma is present
13499 in the preprocessed file, it will be respected by
13500 @code{gnatchop -r}
13501 so that the final chopped files will correctly refer to the original
13502 input source file for @code{gnatprep}.
13503
13504 @item -s
13505 Causes a sorted list of symbol names and values to be
13506 listed on the standard output file.
13507
13508 @item -u
13509 Causes undefined symbols to be treated as having the value FALSE in the context
13510 of a preprocessor test. In the absence of this option, an undefined symbol in
13511 a @code{#if} or @code{#elsif} test will be treated as an error.
13512
13513 @end table
13514
13515 @noindent
13516 Note: if neither @code{-b} nor @code{-c} is present,
13517 then preprocessor lines and
13518 deleted lines are completely removed from the output, unless -r is
13519 specified, in which case -b is assumed.
13520
13521 @node Form of Definitions File
13522 @section Form of Definitions File
13523
13524 @noindent
13525 The definitions file contains lines of the form
13526
13527 @smallexample
13528 symbol := value
13529 @end smallexample
13530
13531 @noindent
13532 where symbol is an identifier, following normal Ada (case-insensitive)
13533 rules for its syntax, and value is one of the following:
13534
13535 @itemize @bullet
13536 @item
13537 Empty, corresponding to a null substitution
13538 @item
13539 A string literal using normal Ada syntax
13540 @item
13541 Any sequence of characters from the set
13542 (letters, digits, period, underline).
13543 @end itemize
13544
13545 @noindent
13546 Comment lines may also appear in the definitions file, starting with
13547 the usual @code{--},
13548 and comments may be added to the definitions lines.
13549
13550 @node Form of Input Text for gnatprep
13551 @section Form of Input Text for @code{gnatprep}
13552
13553 @noindent
13554 The input text may contain preprocessor conditional inclusion lines,
13555 as well as general symbol substitution sequences.
13556
13557 The preprocessor conditional inclusion commands have the form
13558
13559 @smallexample
13560 @group
13561 @cartouche
13562 #if @i{expression} [then]
13563    lines
13564 #elsif @i{expression} [then]
13565    lines
13566 #elsif @i{expression} [then]
13567    lines
13568 ...
13569 #else
13570    lines
13571 #end if;
13572 @end cartouche
13573 @end group
13574 @end smallexample
13575
13576 @noindent
13577 In this example, @i{expression} is defined by the following grammar:
13578 @smallexample
13579 @i{expression} ::=  <symbol>
13580 @i{expression} ::=  <symbol> = "<value>"
13581 @i{expression} ::=  <symbol> = <symbol>
13582 @i{expression} ::=  <symbol> 'Defined
13583 @i{expression} ::=  not @i{expression}
13584 @i{expression} ::=  @i{expression} and @i{expression}
13585 @i{expression} ::=  @i{expression} or @i{expression}
13586 @i{expression} ::=  @i{expression} and then @i{expression}
13587 @i{expression} ::=  @i{expression} or else @i{expression}
13588 @i{expression} ::=  ( @i{expression} )
13589 @end smallexample
13590
13591 @noindent
13592 For the first test (@i{expression} ::= <symbol>) the symbol must have
13593 either the value true or false, that is to say the right-hand of the
13594 symbol definition must be one of the (case-insensitive) literals
13595 @code{True} or @code{False}. If the value is true, then the
13596 corresponding lines are included, and if the value is false, they are
13597 excluded.
13598
13599 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
13600 the symbol has been defined in the definition file or by a @code{-D}
13601 switch on the command line. Otherwise, the test is false.
13602
13603 The equality tests are case insensitive, as are all the preprocessor lines.
13604
13605 If the symbol referenced is not defined in the symbol definitions file,
13606 then the effect depends on whether or not switch @code{-u}
13607 is specified. If so, then the symbol is treated as if it had the value
13608 false and the test fails. If this switch is not specified, then
13609 it is an error to reference an undefined symbol. It is also an error to
13610 reference a symbol that is defined with a value other than @code{True}
13611 or @code{False}.
13612
13613 The use of the @code{not} operator inverts the sense of this logical test, so
13614 that the lines are included only if the symbol is not defined.
13615 The @code{then} keyword is optional as shown
13616
13617 The @code{#} must be the first non-blank character on a line, but
13618 otherwise the format is free form. Spaces or tabs may appear between
13619 the @code{#} and the keyword. The keywords and the symbols are case
13620 insensitive as in normal Ada code. Comments may be used on a
13621 preprocessor line, but other than that, no other tokens may appear on a
13622 preprocessor line. Any number of @code{elsif} clauses can be present,
13623 including none at all. The @code{else} is optional, as in Ada.
13624
13625 The @code{#} marking the start of a preprocessor line must be the first
13626 non-blank character on the line, i.e. it must be preceded only by
13627 spaces or horizontal tabs.
13628
13629 Symbol substitution outside of preprocessor lines is obtained by using
13630 the sequence
13631
13632 @smallexample
13633 $symbol
13634 @end smallexample
13635
13636 @noindent
13637 anywhere within a source line, except in a comment or within a
13638 string literal. The identifier
13639 following the @code{$} must match one of the symbols defined in the symbol
13640 definition file, and the result is to substitute the value of the
13641 symbol in place of @code{$symbol} in the output file.
13642
13643 Note that although the substitution of strings within a string literal
13644 is not possible, it is possible to have a symbol whose defined value is
13645 a string literal. So instead of setting XYZ to @code{hello} and writing:
13646
13647 @smallexample
13648 Header : String := "$XYZ";
13649 @end smallexample
13650
13651 @noindent
13652 you should set XYZ to @code{"hello"} and write:
13653
13654 @smallexample
13655 Header : String := $XYZ;
13656 @end smallexample
13657
13658 @noindent
13659 and then the substitution will occur as desired.
13660
13661
13662 @node The GNAT Library Browser gnatls
13663 @chapter The GNAT Library Browser @code{gnatls}
13664 @findex gnatls
13665 @cindex Library browser
13666
13667 @noindent
13668 @code{gnatls} is a tool that outputs information about compiled
13669 units. It gives the relationship between objects, unit names and source
13670 files. It can also be used to check the source dependencies of a unit
13671 as well as various characteristics.
13672
13673 @menu
13674 * Running gnatls::
13675 * Switches for gnatls::
13676 * Examples of gnatls Usage::
13677 @end menu
13678
13679 @node Running gnatls
13680 @section Running @code{gnatls}
13681
13682 @noindent
13683 The @code{gnatls} command has the form
13684
13685 @smallexample
13686 $ gnatls switches @var{object_or_ali_file}
13687 @end smallexample
13688
13689 @noindent
13690 The main argument is the list of object or @file{ali} files
13691 (@pxref{The Ada Library Information Files})
13692 for which information is requested.
13693
13694 In normal mode, without additional option, @code{gnatls} produces a
13695 four-column listing. Each line represents information for a specific
13696 object. The first column gives the full path of the object, the second
13697 column gives the name of the principal unit in this object, the third
13698 column gives the status of the source and the fourth column gives the
13699 full path of the source representing this unit.
13700 Here is a simple example of use:
13701
13702 @smallexample
13703 $ gnatls *.o
13704 ./demo1.o            demo1            DIF demo1.adb
13705 ./demo2.o            demo2             OK demo2.adb
13706 ./hello.o            h1                OK hello.adb
13707 ./instr-child.o      instr.child      MOK instr-child.adb
13708 ./instr.o            instr             OK instr.adb
13709 ./tef.o              tef              DIF tef.adb
13710 ./text_io_example.o  text_io_example   OK text_io_example.adb
13711 ./tgef.o             tgef             DIF tgef.adb
13712 @end smallexample
13713
13714 @noindent
13715 The first line can be interpreted as follows: the main unit which is
13716 contained in
13717 object file @file{demo1.o} is demo1, whose main source is in
13718 @file{demo1.adb}. Furthermore, the version of the source used for the
13719 compilation of demo1 has been modified (DIF). Each source file has a status
13720 qualifier which can be:
13721
13722 @table @code
13723 @item OK (unchanged)
13724 The version of the source file used for the compilation of the
13725 specified unit corresponds exactly to the actual source file.
13726
13727 @item MOK (slightly modified)
13728 The version of the source file used for the compilation of the
13729 specified unit differs from the actual source file but not enough to
13730 require recompilation. If you use gnatmake with the qualifier
13731 @code{-m (minimal recompilation)}, a file marked
13732 MOK will not be recompiled.
13733
13734 @item DIF (modified)
13735 No version of the source found on the path corresponds to the source
13736 used to build this object.
13737
13738 @item ??? (file not found)
13739 No source file was found for this unit.
13740
13741 @item HID (hidden,  unchanged version not first on PATH)
13742 The version of the source that corresponds exactly to the source used
13743 for compilation has been found on the path but it is hidden by another
13744 version of the same source that has been modified.
13745
13746 @end table
13747
13748 @node Switches for gnatls
13749 @section Switches for @code{gnatls}
13750
13751 @noindent
13752 @code{gnatls} recognizes the following switches:
13753
13754 @table @code
13755 @item -a
13756 @cindex @code{-a} (@code{gnatls})
13757 Consider all units, including those of the predefined Ada library.
13758 Especially useful with @code{-d}.
13759
13760 @item -d
13761 @cindex @code{-d} (@code{gnatls})
13762 List sources from which specified units depend on.
13763
13764 @item -h
13765 @cindex @code{-h} (@code{gnatls})
13766 Output the list of options.
13767
13768 @item -o
13769 @cindex @code{-o} (@code{gnatls})
13770 Only output information about object files.
13771
13772 @item -s
13773 @cindex @code{-s} (@code{gnatls})
13774 Only output information about source files.
13775
13776 @item -u
13777 @cindex @code{-u} (@code{gnatls})
13778 Only output information about compilation units.
13779
13780 @item -aO@var{dir}
13781 @itemx -aI@var{dir}
13782 @itemx -I@var{dir}
13783 @itemx  -I-
13784 @itemx -nostdinc
13785 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
13786 (see @ref{Switches for gnatmake}).
13787
13788 @item --RTS=@var{rts-path}
13789 @cindex @code{--RTS} (@code{gnatls})
13790 Specifies the default location of the runtime library. Same meaning as the
13791 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13792
13793 @item -v
13794 @cindex @code{-s} (@code{gnatls})
13795 Verbose mode. Output the complete source and object paths. Do not use
13796 the default column layout but instead use long format giving as much as
13797 information possible on each requested units, including special
13798 characteristics such as:
13799
13800 @table @code
13801 @item  Preelaborable
13802 The unit is preelaborable in the Ada 95 sense.
13803
13804 @item No_Elab_Code
13805 No elaboration code has been produced by the compiler for this unit.
13806
13807 @item Pure
13808 The unit is pure in the Ada 95 sense.
13809
13810 @item Elaborate_Body
13811 The unit contains a pragma Elaborate_Body.
13812
13813 @item Remote_Types
13814 The unit contains a pragma Remote_Types.
13815
13816 @item Shared_Passive
13817 The unit contains a pragma Shared_Passive.
13818
13819 @item Predefined
13820 This unit is part of the predefined environment and cannot be modified
13821 by the user.
13822
13823 @item Remote_Call_Interface
13824 The unit contains a pragma Remote_Call_Interface.
13825
13826 @end table
13827
13828 @end table
13829
13830 @node Examples of gnatls Usage
13831 @section Example of @code{gnatls} Usage
13832
13833 @noindent
13834 Example of using the verbose switch. Note how the source and
13835 object paths are affected by the -I switch.
13836
13837 @smallexample
13838 $ gnatls -v -I.. demo1.o
13839
13840 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
13841
13842 Source Search Path:
13843    <Current_Directory>
13844    ../
13845    /home/comar/local/adainclude/
13846
13847 Object Search Path:
13848    <Current_Directory>
13849    ../
13850    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
13851
13852 ./demo1.o
13853    Unit =>
13854      Name   => demo1
13855      Kind   => subprogram body
13856      Flags  => No_Elab_Code
13857      Source => demo1.adb    modified
13858 @end smallexample
13859
13860 @noindent
13861 The following is an example of use of the dependency list.
13862 Note the use of the -s switch
13863 which gives a straight list of source files. This can be useful for
13864 building specialized scripts.
13865
13866 @smallexample
13867 $ gnatls -d demo2.o
13868 ./demo2.o   demo2        OK demo2.adb
13869                          OK gen_list.ads
13870                          OK gen_list.adb
13871                          OK instr.ads
13872                          OK instr-child.ads
13873
13874 $ gnatls -d -s -a demo1.o
13875 demo1.adb
13876 /home/comar/local/adainclude/ada.ads
13877 /home/comar/local/adainclude/a-finali.ads
13878 /home/comar/local/adainclude/a-filico.ads
13879 /home/comar/local/adainclude/a-stream.ads
13880 /home/comar/local/adainclude/a-tags.ads
13881 gen_list.ads
13882 gen_list.adb
13883 /home/comar/local/adainclude/gnat.ads
13884 /home/comar/local/adainclude/g-io.ads
13885 instr.ads
13886 /home/comar/local/adainclude/system.ads
13887 /home/comar/local/adainclude/s-exctab.ads
13888 /home/comar/local/adainclude/s-finimp.ads
13889 /home/comar/local/adainclude/s-finroo.ads
13890 /home/comar/local/adainclude/s-secsta.ads
13891 /home/comar/local/adainclude/s-stalib.ads
13892 /home/comar/local/adainclude/s-stoele.ads
13893 /home/comar/local/adainclude/s-stratt.ads
13894 /home/comar/local/adainclude/s-tasoli.ads
13895 /home/comar/local/adainclude/s-unstyp.ads
13896 /home/comar/local/adainclude/unchconv.ads
13897 @end smallexample
13898
13899
13900 @node GNAT and Libraries
13901 @chapter GNAT and Libraries
13902 @cindex Library, building, installing
13903
13904 @noindent
13905 This chapter addresses some of the issues related to building and using
13906 a library with GNAT. It also shows how the GNAT run-time library can be
13907 recompiled.
13908
13909 @menu
13910 * Creating an Ada Library::
13911 * Installing an Ada Library::
13912 * Using an Ada Library::
13913 * Creating an Ada Library to be Used in a Non-Ada Context::
13914 * Rebuilding the GNAT Run-Time Library::
13915 @end menu
13916
13917 @node Creating an Ada Library
13918 @section Creating an Ada Library
13919
13920 @noindent
13921 In the GNAT environment, a library has two components:
13922 @itemize @bullet
13923 @item
13924 Source files.
13925 @item
13926 Compiled code and Ali files. See @ref{The Ada Library Information Files}.
13927 @end itemize
13928
13929 @noindent
13930 In order to use other packages @ref{The GNAT Compilation Model}
13931 requires a certain number of sources to be available to the compiler.
13932 The minimal set of
13933 sources required includes the specs of all the packages that make up the
13934 visible part of the library as well as all the sources upon which they
13935 depend. The bodies of all visible generic units must also be provided.
13936 @noindent
13937 Although it is not strictly mandatory, it is recommended that all sources
13938 needed to recompile the library be provided, so that the user can make
13939 full use of inter-unit inlining and source-level debugging. This can also
13940 make the situation easier for users that need to upgrade their compilation
13941 toolchain and thus need to recompile the library from sources.
13942
13943 @noindent
13944 The compiled code can be provided in different ways. The simplest way is
13945 to provide directly the set of objects produced by the compiler during
13946 the compilation of the library. It is also possible to group the objects
13947 into an archive using whatever commands are provided by the operating
13948 system. Finally, it is also possible to create a shared library (see
13949 option -shared in the GCC manual).
13950
13951 @noindent
13952 There are various possibilities for compiling the units that make up the
13953 library: for example with a Makefile @ref{Using the GNU make Utility},
13954 or with a conventional script.
13955 For simple libraries, it is also possible to create a
13956 dummy main program which depends upon all the packages that comprise the
13957 interface of the library. This dummy main program can then be given to
13958 gnatmake, in order to build all the necessary objects. Here is an example
13959 of such a dummy program and the generic commands used to build an
13960 archive or a shared library.
13961
13962 @smallexample
13963 @iftex
13964 @leftskip=.7cm
13965 @end iftex
13966 @b{with} My_Lib.Service1;
13967 @b{with} My_Lib.Service2;
13968 @b{with} My_Lib.Service3;
13969 @b{procedure} My_Lib_Dummy @b{is}
13970 @b{begin}
13971    @b{null};
13972 @b{end};
13973
13974 # compiling the library
13975 $ gnatmake -c my_lib_dummy.adb
13976
13977 # we don't need the dummy object itself
13978 $ rm my_lib_dummy.o my_lib_dummy.ali
13979
13980 # create an archive with the remaining objects
13981 $ ar rc libmy_lib.a *.o
13982 # some systems may require "ranlib" to be run as well
13983
13984 # or create a shared library
13985 $ gcc -shared -o libmy_lib.so *.o
13986 # some systems may require the code to have been compiled with -fPIC
13987 @end smallexample
13988
13989 @noindent
13990 When the objects are grouped in an archive or a shared library, the user
13991 needs to specify the desired library at link time, unless a pragma
13992 linker_options has been used in one of the sources:
13993 @smallexample
13994 @b{pragma} Linker_Options ("-lmy_lib");
13995 @end smallexample
13996
13997 @node Installing an Ada Library
13998 @section Installing an Ada Library
13999
14000 @noindent
14001 In the GNAT model, installing a library consists in copying into a specific
14002 location the files that make up this library. It is possible to install
14003 the sources in a different directory from the other files (ALI, objects,
14004 archives) since the source path and the object path can easily be
14005 specified separately.
14006
14007 @noindent
14008 For general purpose libraries, it is possible for the system
14009 administrator to put those libraries in the default compiler paths. To
14010 achieve this, he must specify their location in the configuration files
14011 "ada_source_path" and "ada_object_path" that must be located in the GNAT
14012 installation tree at the same place as the gcc spec file. The location of
14013 the gcc spec file can be determined as follows:
14014 @smallexample
14015 $ gcc -v
14016 @end smallexample
14017
14018 @noindent
14019 The configuration files mentioned above have simple format: each line in them
14020 must contain one unique
14021 directory name. Those names are added to the corresponding path
14022 in their order of appearance in the file. The names can be either absolute
14023 or relative, in the latter case, they are relative to where theses files
14024 are located.
14025
14026 @noindent
14027 "ada_source_path" and "ada_object_path" might actually not be present in a
14028 GNAT installation, in which case, GNAT will look for its run-time library in
14029 the directories "adainclude" for the sources and "adalib" for the
14030 objects and ALI files. When the files exist, the compiler does not
14031 look in "adainclude" and "adalib" at all, and thus the "ada_source_path" file
14032 must contain the location for the GNAT run-time sources (which can simply
14033 be "adainclude"). In the same way, the "ada_object_path" file must contain
14034 the location for the GNAT run-time objects (which can simply
14035 be "adalib").
14036
14037 @noindent
14038 You can also specify a new default path to the runtime library at compilation
14039 time with the switch "--RTS=@var{rts-path}". You can easily choose and change
14040 the runtime you want your program to be compiled with. This switch is
14041 recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref.
14042
14043 @noindent
14044 It is possible to install a library before or after the standard GNAT
14045 library, by reordering the lines in the configuration files. In general, a
14046 library must be installed before the GNAT library if it redefines any part of it.
14047
14048 @node Using an Ada Library
14049 @section Using an Ada Library
14050
14051 @noindent
14052 In order to use a Ada library, you need to make sure that this
14053 library is on both your source and object path
14054 @ref{Search Paths and the Run-Time Library (RTL)}
14055 and @ref{Search Paths for gnatbind}. For
14056 instance, you can use the library "mylib" installed in "/dir/my_lib_src"
14057 and "/dir/my_lib_obj" with the following commands:
14058
14059 @smallexample
14060 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
14061   -largs -lmy_lib
14062 @end smallexample
14063
14064 @noindent
14065 This can be simplified down to the following:
14066 @smallexample
14067 $ gnatmake my_appl
14068 @end smallexample
14069 when the following conditions are met:
14070 @itemize @bullet
14071 @item
14072 "/dir/my_lib_src" has been added by the user to the environment
14073 variable "ADA_INCLUDE_PATH", or by the administrator to the file
14074 "ada_source_path"
14075 @item
14076 "/dir/my_lib_obj" has been added by the user to the environment
14077 variable "ADA_OBJECTS_PATH", or by the administrator to the file
14078 "ada_object_path"
14079 @item
14080 a pragma linker_options, as mentioned in @ref{Creating an Ada Library}
14081 as been added to the sources.
14082 @end itemize
14083 @noindent
14084
14085 @node Creating an Ada Library to be Used in a Non-Ada Context
14086 @section Creating an Ada Library to be Used in a Non-Ada Context
14087
14088 @noindent
14089 The previous sections detailed how to create and install a library that
14090 was usable from an Ada main program. Using this library in a non-Ada
14091 context is not possible, because the elaboration of the library is
14092 automatically done as part of the main program elaboration.
14093
14094 GNAT also provides the ability to build libraries that can be used both
14095 in an Ada and non-Ada context.  This section describes how to build such
14096 a library, and then how to use it from a C program. The method for
14097 interfacing with the library from other languages such as Fortran for
14098 instance remains the same.
14099
14100 @subsection Creating the Library
14101
14102 @itemize @bullet
14103 @item Identify the units representing the interface of the library.
14104
14105 Here is an example of simple library interface:
14106
14107 @smallexample
14108 package Interface is
14109
14110    procedure Do_Something;
14111
14112    procedure Do_Something_Else;
14113
14114 end Interface;
14115 @end smallexample
14116
14117 @item Use @code{pragma Export} or @code{pragma Convention} for the
14118 exported entities.
14119
14120 Our package @code{Interface} is then updated as follow:
14121 @smallexample
14122 package Interface is
14123
14124    procedure Do_Something;
14125    pragma Export (C, Do_Something, "do_something");
14126
14127    procedure Do_Something_Else;
14128    pragma Export (C, Do_Something_Else, "do_something_else");
14129
14130 end Interface;
14131 @end smallexample
14132
14133 @item Compile all the units composing the library.
14134
14135 @item Bind the library objects.
14136
14137 This step is performed by invoking gnatbind with the @code{-L<prefix>}
14138 switch. @code{gnatbind} will then generate the library elaboration
14139 procedure (named @code{<prefix>init}) and the run-time finalization
14140 procedure (named @code{<prefix>final}).
14141
14142 @smallexample
14143 # generate the binder file in Ada
14144 $ gnatbind -Lmylib interface
14145
14146 # generate the binder file in C
14147 $ gnatbind -C -Lmylib interface
14148 @end smallexample
14149
14150 @item Compile the files generated by the binder
14151
14152 @smallexample
14153 $ gcc -c b~interface.adb
14154 @end smallexample
14155
14156 @item Create the library;
14157
14158 The procedure is identical to the procedure explained in
14159 @ref{Creating an Ada Library},
14160 except that @file{b~interface.o} needs to be added to
14161 the list of objects.
14162
14163 @smallexample
14164 # create an archive file
14165 $ ar cr libmylib.a b~interface.o <other object files>
14166
14167 # create a shared library
14168 $ gcc -shared -o libmylib.so b~interface.o <other object files>
14169 @end smallexample
14170
14171 @item Provide a "foreign" view of the library interface;
14172
14173 The example below shows the content of @code{mylib_interface.h} (note
14174 that there is no rule for the naming of this file, any name can be used)
14175 @smallexample
14176 /* the library elaboration procedure */
14177 extern void mylibinit (void);
14178
14179 /* the library finalization procedure */
14180 extern void mylibfinal (void);
14181
14182 /* the interface exported by the library */
14183 extern void do_something (void);
14184 extern void do_something_else (void);
14185 @end smallexample
14186 @end itemize
14187
14188 @subsection Using the Library
14189
14190 @noindent
14191 Libraries built as explained above can be used from any program, provided
14192 that the elaboration procedures (named @code{mylibinit} in the previous
14193 example) are called before the library services are used. Any number of
14194 libraries can be used simultaneously, as long as the elaboration
14195 procedure of each library is called.
14196
14197 Below is an example of C program that uses our @code{mylib} library.
14198
14199 @smallexample
14200 #include "mylib_interface.h"
14201
14202 int
14203 main (void)
14204 @{
14205    /* First, elaborate the library before using it */
14206    mylibinit ();
14207
14208    /* Main program, using the library exported entities */
14209    do_something ();
14210    do_something_else ();
14211
14212    /* Library finalization at the end of the program */
14213    mylibfinal ();
14214    return 0;
14215 @}
14216 @end smallexample
14217
14218 @noindent
14219 Note that this same library can be used from an equivalent Ada main
14220 program. In addition, if the libraries are installed as detailed in
14221 @ref{Installing an Ada Library}, it is not necessary to invoke the
14222 library elaboration and finalization routines. The binder will ensure
14223 that this is done as part of the main program elaboration and
14224 finalization phases.
14225
14226 @subsection The Finalization Phase
14227
14228 @noindent
14229 Invoking any library finalization procedure generated by @code{gnatbind}
14230 shuts down the Ada run time permanently. Consequently, the finalization
14231 of all Ada libraries must be performed at the end of the program. No
14232 call to these libraries nor the Ada run time should be made past the
14233 finalization phase.
14234
14235 @subsection Restrictions in Libraries
14236
14237 @noindent
14238 The pragmas listed below should be used with caution inside libraries,
14239 as they can create incompatibilities with other Ada libraries:
14240 @itemize @bullet
14241 @item pragma @code{Locking_Policy}
14242 @item pragma @code{Queuing_Policy}
14243 @item pragma @code{Task_Dispatching_Policy}
14244 @item pragma @code{Unreserve_All_Interrupts}
14245 @end itemize
14246 When using a library that contains such pragmas, the user must make sure
14247 that all libraries use the same pragmas with the same values. Otherwise,
14248 a @code{Program_Error} will
14249 be raised during the elaboration of the conflicting
14250 libraries. The usage of these pragmas and its consequences for the user
14251 should therefore be well documented.
14252
14253 Similarly, the traceback in exception occurrences mechanism should be
14254 enabled or disabled in a consistent manner across all libraries.
14255 Otherwise, a Program_Error will be raised during the elaboration of the
14256 conflicting libraries.
14257
14258 If the @code{'Version} and @code{'Body_Version}
14259 attributes are used inside a library, then it is necessary to
14260 perform a @code{gnatbind} step that mentions all ali files in all
14261 libraries, so that version identifiers can be properly computed.
14262 In practice these attributes are rarely used, so this is unlikely
14263 to be a consideration.
14264
14265 @node  Rebuilding the GNAT Run-Time Library
14266 @section Rebuilding the GNAT Run-Time Library
14267
14268 @noindent
14269 It may be useful to recompile the GNAT library in various contexts, the
14270 most important one being the use of partition-wide configuration pragmas
14271 such as Normalize_Scalar. A special Makefile called
14272 @code{Makefile.adalib} is provided to that effect and can be found in
14273 the directory containing the GNAT library. The location of this
14274 directory depends on the way the GNAT environment has been installed and can
14275 be determined by means of the command:
14276
14277 @smallexample
14278 $ gnatls -v
14279 @end smallexample
14280
14281 @noindent
14282 The last entry in the object search path usually contains the
14283 gnat library. This Makefile contains its own documentation and in
14284 particular the set of instructions needed to rebuild a new library and
14285 to use it.
14286
14287 @node Using the GNU make Utility
14288 @chapter Using the GNU @code{make} Utility
14289 @findex make
14290
14291 @noindent
14292 This chapter offers some examples of makefiles that solve specific
14293 problems. It does not explain how to write a makefile (see the GNU make
14294 documentation), nor does it try to replace the @code{gnatmake} utility
14295 (@pxref{The GNAT Make Program gnatmake}).
14296
14297 All the examples in this section are specific to the GNU version of
14298 make. Although @code{make} is a standard utility, and the basic language
14299 is the same, these examples use some advanced features found only in
14300 @code{GNU make}.
14301
14302 @menu
14303 * Using gnatmake in a Makefile::
14304 * Automatically Creating a List of Directories::
14305 * Generating the Command Line Switches::
14306 * Overcoming Command Line Length Limits::
14307 @end menu
14308
14309 @node Using gnatmake in a Makefile
14310 @section Using gnatmake in a Makefile
14311 @findex makefile
14312 @cindex GNU make
14313
14314 @noindent
14315 Complex project organizations can be handled in a very powerful way by
14316 using GNU make combined with gnatmake. For instance, here is a Makefile
14317 which allows you to build each subsystem of a big project into a separate
14318 shared library. Such a makefile allows you to significantly reduce the link
14319 time of very big applications while maintaining full coherence at
14320 each step of the build process.
14321
14322 The list of dependencies are handled automatically by
14323 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
14324 the appropriate directories.
14325
14326 Note that you should also read the example on how to automatically
14327 create the list of directories (@pxref{Automatically Creating a List of Directories})
14328 which might help you in case your project has a lot of
14329 subdirectories.
14330
14331 @smallexample
14332 @iftex
14333 @leftskip=0cm
14334 @font@heightrm=cmr8
14335 @heightrm
14336 @end iftex
14337 ## This Makefile is intended to be used with the following directory
14338 ## configuration:
14339 ##  - The sources are split into a series of csc (computer software components)
14340 ##    Each of these csc is put in its own directory.
14341 ##    Their name are referenced by the directory names.
14342 ##    They will be compiled into shared library (although this would also work
14343 ##    with static libraries
14344 ##  - The main program (and possibly other packages that do not belong to any
14345 ##    csc is put in the top level directory (where the Makefile is).
14346 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
14347 ##                    \_ second_csc (sources) __ lib (will contain the library)
14348 ##                    \_ ...
14349 ## Although this Makefile is build for shared library, it is easy to modify
14350 ## to build partial link objects instead (modify the lines with -shared and
14351 ## gnatlink below)
14352 ##
14353 ## With this makefile, you can change any file in the system or add any new
14354 ## file, and everything will be recompiled correctly (only the relevant shared
14355 ## objects will be recompiled, and the main program will be re-linked).
14356
14357 # The list of computer software component for your project. This might be
14358 # generated automatically.
14359 CSC_LIST=aa bb cc
14360
14361 # Name of the main program (no extension)
14362 MAIN=main
14363
14364 # If we need to build objects with -fPIC, uncomment the following line
14365 #NEED_FPIC=-fPIC
14366
14367 # The following variable should give the directory containing libgnat.so
14368 # You can get this directory through 'gnatls -v'. This is usually the last
14369 # directory in the Object_Path.
14370 GLIB=...
14371
14372 # The directories for the libraries
14373 # (This macro expands the list of CSC to the list of shared libraries, you
14374 # could simply use the expanded form :
14375 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
14376 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
14377
14378 $@{MAIN@}: objects $@{LIB_DIR@}
14379     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
14380     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
14381
14382 objects::
14383     # recompile the sources
14384     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
14385
14386 # Note: In a future version of GNAT, the following commands will be simplified
14387 # by a new tool, gnatmlib
14388 $@{LIB_DIR@}:
14389     mkdir -p $@{dir $@@ @}
14390     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
14391     cd $@{dir $@@ @}; cp -f ../*.ali .
14392
14393 # The dependencies for the modules
14394 # Note that we have to force the expansion of *.o, since in some cases make won't
14395 # be able to do it itself.
14396 aa/lib/libaa.so: $@{wildcard aa/*.o@}
14397 bb/lib/libbb.so: $@{wildcard bb/*.o@}
14398 cc/lib/libcc.so: $@{wildcard cc/*.o@}
14399
14400 # Make sure all of the shared libraries are in the path before starting the
14401 # program
14402 run::
14403     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
14404
14405 clean::
14406     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
14407     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
14408     $@{RM@} $@{CSC_LIST:%=%/*.o@}
14409     $@{RM@} *.o *.ali $@{MAIN@}
14410 @end smallexample
14411
14412 @node Automatically Creating a List of Directories
14413 @section Automatically Creating a List of Directories
14414
14415 @noindent
14416 In most makefiles, you will have to specify a list of directories, and
14417 store it in a variable. For small projects, it is often easier to
14418 specify each of them by hand, since you then have full control over what
14419 is the proper order for these directories, which ones should be
14420 included...
14421
14422 However, in larger projects, which might involve hundreds of
14423 subdirectories, it might be more convenient to generate this list
14424 automatically.
14425
14426 The example below presents two methods. The first one, although less
14427 general, gives you more control over the list. It involves wildcard
14428 characters, that are automatically expanded by @code{make}. Its
14429 shortcoming is that you need to explicitly specify some of the
14430 organization of your project, such as for instance the directory tree
14431 depth, whether some directories are found in a separate tree,...
14432
14433 The second method is the most general one. It requires an external
14434 program, called @code{find}, which is standard on all Unix systems. All
14435 the directories found under a given root directory will be added to the
14436 list.
14437
14438 @smallexample
14439 @iftex
14440 @leftskip=0cm
14441 @font@heightrm=cmr8
14442 @heightrm
14443 @end iftex
14444 # The examples below are based on the following directory hierarchy:
14445 # All the directories can contain any number of files
14446 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
14447 #                       ->  ab
14448 #                       ->  ac
14449 #                ->  b  ->  ba  ->  baa
14450 #                       ->  bb
14451 #                       ->  bc
14452 # This Makefile creates a variable called DIRS, that can be reused any time
14453 # you need this list (see the other examples in this section)
14454
14455 # The root of your project's directory hierarchy
14456 ROOT_DIRECTORY=.
14457
14458 ####
14459 # First method: specify explicitly the list of directories
14460 # This allows you to specify any subset of all the directories you need.
14461 ####
14462
14463 DIRS := a/aa/ a/ab/ b/ba/
14464
14465 ####
14466 # Second method: use wildcards
14467 # Note that the argument(s) to wildcard below should end with a '/'.
14468 # Since wildcards also return file names, we have to filter them out
14469 # to avoid duplicate directory names.
14470 # We thus use make's @code{dir} and @code{sort} functions.
14471 # It sets DIRs to the following value (note that the directories aaa and baa
14472 # are not given, unless you change the arguments to wildcard).
14473 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
14474 ####
14475
14476 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ $@{ROOT_DIRECTORY@}/*/*/@}@}@}
14477
14478 ####
14479 # Third method: use an external program
14480 # This command is much faster if run on local disks, avoiding NFS slowdowns.
14481 # This is the most complete command: it sets DIRs to the following value:
14482 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
14483 ####
14484
14485 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
14486
14487 @end smallexample
14488
14489 @node Generating the Command Line Switches
14490 @section Generating the Command Line Switches
14491
14492 @noindent
14493 Once you have created the list of directories as explained in the
14494 previous section (@pxref{Automatically Creating a List of Directories}),
14495 you can easily generate the command line arguments to pass to gnatmake.
14496
14497 For the sake of completeness, this example assumes that the source path
14498 is not the same as the object path, and that you have two separate lists
14499 of directories.
14500
14501 @smallexample
14502 # see "Automatically creating a list of directories" to create
14503 # these variables
14504 SOURCE_DIRS=
14505 OBJECT_DIRS=
14506
14507 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
14508 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
14509
14510 all:
14511         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
14512 @end smallexample
14513
14514 @node Overcoming Command Line Length Limits
14515 @section Overcoming Command Line Length Limits
14516
14517 @noindent
14518 One problem that might be encountered on big projects is that many
14519 operating systems limit the length of the command line. It is thus hard to give
14520 gnatmake the list of source and object directories.
14521
14522 This example shows how you can set up environment variables, which will
14523 make @code{gnatmake} behave exactly as if the directories had been
14524 specified on the command line, but have a much higher length limit (or
14525 even none on most systems).
14526
14527 It assumes that you have created a list of directories in your Makefile,
14528 using one of the methods presented in
14529 @ref{Automatically Creating a List of Directories}.
14530 For the sake of completeness, we assume that the object
14531 path (where the ALI files are found) is different from the sources patch.
14532
14533 Note a small trick in the Makefile below: for efficiency reasons, we
14534 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
14535 expanded immediately by @code{make}. This way we overcome the standard
14536 make behavior which is to expand the variables only when they are
14537 actually used.
14538
14539 @smallexample
14540 @iftex
14541 @leftskip=0cm
14542 @font@heightrm=cmr8
14543 @heightrm
14544 @end iftex
14545 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
14546 # This is the same thing as putting the -I arguments on the command line.
14547 # (the equivalent of using -aI on the command line would be to define
14548 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
14549 # You can of course have different values for these variables.
14550 #
14551 # Note also that we need to keep the previous values of these variables, since
14552 # they might have been set before running 'make' to specify where the GNAT
14553 # library is installed.
14554
14555 # see "Automatically creating a list of directories" to create these
14556 # variables
14557 SOURCE_DIRS=
14558 OBJECT_DIRS=
14559
14560 empty:=
14561 space:=$@{empty@} $@{empty@}
14562 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
14563 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
14564 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
14565 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
14566 export ADA_INCLUDE_PATH
14567 export ADA_OBJECT_PATH
14568
14569 all:
14570         gnatmake main_unit
14571 @end smallexample
14572
14573 @node Finding Memory Problems with gnatmem
14574 @chapter Finding Memory Problems with @code{gnatmem}
14575 @findex gnatmem
14576
14577 @noindent
14578 @code{gnatmem}, is a tool that monitors dynamic allocation and
14579 deallocation activity in a program, and displays information about
14580 incorrect deallocations and possible sources of memory leaks. Gnatmem
14581 provides three type of information:
14582 @itemize @bullet
14583 @item
14584 General information concerning memory management, such as the total
14585 number of allocations and deallocations, the amount of allocated
14586 memory and the high water mark, i.e. the largest amount of allocated
14587 memory in the course of program execution.
14588
14589 @item
14590 Backtraces for all incorrect deallocations, that is to say deallocations
14591 which do not correspond to a valid allocation.
14592
14593 @item
14594 Information on each allocation that is potentially the origin of a memory
14595 leak.
14596 @end itemize
14597
14598 The @code{gnatmem} command has two modes. It can be used with @code{gdb}
14599 or with instrumented allocation and deallocation routines. The later
14600 mode is called the @code{GMEM} mode. Both modes produce the very same
14601 output.
14602
14603 @menu
14604 * Running gnatmem (GDB Mode)::
14605 * Running gnatmem (GMEM Mode)::
14606 * Switches for gnatmem::
14607 * Examples of gnatmem Usage::
14608 * GDB and GMEM Modes::
14609 * Implementation Note::
14610 @end menu
14611
14612 @node Running gnatmem (GDB Mode)
14613 @section Running @code{gnatmem} (GDB Mode)
14614
14615 @noindent
14616 The @code{gnatmem} command has the form
14617
14618 @smallexample
14619    $ gnatmem [-q] [n] [-o file] user_program [program_arg]*
14620 or
14621    $ gnatmem [-q] [n] -i file
14622 @end smallexample
14623
14624 @noindent
14625 Gnatmem must be supplied with the executable to examine, followed by its
14626 run-time inputs. For example, if a program is executed with the command:
14627 @smallexample
14628 $ my_program arg1 arg2
14629 @end smallexample
14630 then it can be run under @code{gnatmem} control using the command:
14631 @smallexample
14632 $ gnatmem my_program arg1 arg2
14633 @end smallexample
14634
14635 The program is transparently executed under the control of the debugger
14636 @ref{The GNAT Debugger GDB}. This does not affect the behavior
14637 of the program, except for sensitive real-time programs. When the program
14638 has completed execution, @code{gnatmem} outputs a report containing general
14639 allocation/deallocation information and potential memory leak.
14640 For better results, the user program should be compiled with
14641 debugging options @ref{Switches for gcc}.
14642
14643 Here is a simple example of use:
14644
14645 *************** debut cc
14646 @smallexample
14647 $ gnatmem test_gm
14648
14649 Global information
14650 ------------------
14651    Total number of allocations        :  45
14652    Total number of deallocations      :   6
14653    Final Water Mark (non freed mem)   :  11.29 Kilobytes
14654    High Water Mark                    :  11.40 Kilobytes
14655
14656 .
14657 .
14658 .
14659 Allocation Root # 2
14660 -------------------
14661  Number of non freed allocations    :  11
14662  Final Water Mark (non freed mem)   :   1.16 Kilobytes
14663  High Water Mark                    :   1.27 Kilobytes
14664  Backtrace                          :
14665    test_gm.adb:23 test_gm.alloc
14666 .
14667 .
14668 .
14669 @end smallexample
14670
14671 The first block of output give general information. In this case, the
14672 Ada construct "@b{new}" was executed 45 times, and only 6 calls to an
14673 unchecked deallocation routine occurred.
14674
14675 Subsequent paragraphs display  information on all allocation roots.
14676 An allocation root is a specific point in the execution of the program
14677 that generates some dynamic allocation, such as a "@b{new}" construct. This
14678 root is represented by an execution backtrace (or subprogram call
14679 stack). By default the backtrace depth for allocations roots is 1, so
14680 that a root corresponds exactly to a source location. The backtrace can
14681 be made deeper, to make the root more specific.
14682
14683 @node Running gnatmem (GMEM Mode)
14684 @section Running @code{gnatmem} (GMEM Mode)
14685 @cindex @code{GMEM} (@code{gnatmem})
14686
14687 @noindent
14688 The @code{gnatmem} command has the form
14689
14690 @smallexample
14691    $ gnatmem [-q] [n] -i gmem.out user_program [program_arg]*
14692 @end smallexample
14693
14694 The program must have been linked with the instrumented version of the
14695 allocation and deallocation routines. This is done with linking with the
14696 @file{libgmem.a} library. For better results, the user program should be
14697 compiled with debugging options @ref{Switches for gcc}. For example to
14698 build @file{my_program}:
14699
14700 @smallexample
14701 $ gnatmake -g my_program -largs -lgmem
14702 @end smallexample
14703
14704 @noindent
14705 When running @file{my_program} the file @file{gmem.out} is produced. This file
14706 contains information about all allocations and deallocations done by the
14707 program. It is produced by the instrumented allocations and
14708 deallocations routines and will be used by @code{gnatmem}.
14709
14710 @noindent
14711 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
14712 examine followed by its run-time inputs. For example, if a program is
14713 executed with the command:
14714 @smallexample
14715 $ my_program arg1 arg2
14716 @end smallexample
14717 then @file{gmem.out} can be analysed by @code{gnatmem} using the command:
14718 @smallexample
14719 $ gnatmem -i gmem.out my_program arg1 arg2
14720 @end smallexample
14721
14722 @node Switches for gnatmem
14723 @section Switches for @code{gnatmem}
14724
14725 @noindent
14726 @code{gnatmem} recognizes the following switches:
14727
14728 @table @code
14729
14730 @item @code{-q}
14731 @cindex @code{-q} (@code{gnatmem})
14732 Quiet. Gives the minimum output needed to identify the origin of the
14733 memory leaks. Omit statistical information.
14734
14735 @item @code{n}
14736 @cindex @code{n} (@code{gnatmem})
14737 N is an integer literal (usually between 1 and 10) which controls the
14738 depth of the backtraces defining allocation root. The default value for
14739 N is 1. The deeper the backtrace, the more precise the localization of
14740 the root. Note that the total number of roots can depend on this
14741 parameter.
14742
14743 @item @code{-o file}
14744 @cindex @code{-o} (@code{gnatmem})
14745 Direct the gdb output to the specified file. The @code{gdb} script used
14746 to generate this output is also saved in the file @file{gnatmem.tmp}.
14747
14748 @item @code{-i file}
14749 @cindex @code{-i} (@code{gnatmem})
14750 Do the @code{gnatmem} processing starting from @file{file} which has
14751 been generated by a previous call to @code{gnatmem} with the -o
14752 switch or @file{gmem.out} produced by @code{GMEM} mode. This is useful
14753 for post mortem processing.
14754
14755 @end table
14756
14757 @node Examples of gnatmem Usage
14758 @section Example of @code{gnatmem} Usage
14759
14760 @noindent
14761 This section is based on the @code{GDB} mode of @code{gnatmem}. The same
14762 results can be achieved using @code{GMEM} mode. See section
14763 @ref{Running gnatmem (GMEM Mode)}.
14764
14765 @noindent
14766 The first example shows the use of @code{gnatmem}
14767 on a simple leaking program.
14768 Suppose that we have the following Ada program:
14769
14770 @smallexample
14771 @group
14772 @cartouche
14773 @b{with} Unchecked_Deallocation;
14774 @b{procedure} Test_Gm @b{is}
14775
14776    @b{type} T @b{is array} (1..1000) @b{of} Integer;
14777    @b{type} Ptr @b{is access} T;
14778    @b{procedure} Free @b{is new} Unchecked_Deallocation (T, Ptr);
14779    A : Ptr;
14780
14781    @b{procedure} My_Alloc @b{is}
14782    @b{begin}
14783       A := @b{new} T;
14784    @b{end} My_Alloc;
14785
14786    @b{procedure} My_DeAlloc @b{is}
14787       B : Ptr := A;
14788    @b{begin}
14789       Free (B);
14790    @b{end} My_DeAlloc;
14791
14792 @b{begin}
14793    My_Alloc;
14794    @b{for} I @b{in} 1 .. 5 @b{loop}
14795       @b{for} J @b{in} I .. 5 @b{loop}
14796          My_Alloc;
14797       @b{end loop};
14798       My_Dealloc;
14799    @b{end loop};
14800 @b{end};
14801 @end cartouche
14802 @end group
14803 @end smallexample
14804
14805 @noindent
14806 The program needs to be compiled with debugging option:
14807
14808 @smallexample
14809 $ gnatmake -g test_gm
14810 @end smallexample
14811
14812 @code{gnatmem} is invoked simply with
14813 @smallexample
14814 $ gnatmem test_gm
14815 @end smallexample
14816
14817 @noindent
14818 which produces the following output:
14819
14820 @smallexample
14821 Global information
14822 ------------------
14823    Total number of allocations        :  18
14824    Total number of deallocations      :   5
14825    Final Water Mark (non freed mem)   :  53.00 Kilobytes
14826    High Water Mark                    :  56.90 Kilobytes
14827
14828 Allocation Root # 1
14829 -------------------
14830  Number of non freed allocations    :  11
14831  Final Water Mark (non freed mem)   :  42.97 Kilobytes
14832  High Water Mark                    :  46.88 Kilobytes
14833  Backtrace                          :
14834    test_gm.adb:11 test_gm.my_alloc
14835
14836 Allocation Root # 2
14837 -------------------
14838  Number of non freed allocations    :   1
14839  Final Water Mark (non freed mem)   :  10.02 Kilobytes
14840  High Water Mark                    :  10.02 Kilobytes
14841  Backtrace                          :
14842    s-secsta.adb:81 system.secondary_stack.ss_init
14843
14844 Allocation Root # 3
14845 -------------------
14846  Number of non freed allocations    :   1
14847  Final Water Mark (non freed mem)   :  12 Bytes
14848  High Water Mark                    :  12 Bytes
14849  Backtrace                          :
14850    s-secsta.adb:181 system.secondary_stack.ss_init
14851 @end smallexample
14852
14853 @noindent
14854 Note that the GNAT run time contains itself a certain number of
14855 allocations that have no  corresponding deallocation,
14856 as shown here for root #2 and root
14857 #1. This is a normal behavior when the number of non freed allocations
14858 is one, it locates dynamic data structures that the run time needs for
14859 the complete lifetime of the program. Note also that there is only one
14860 allocation root in the user program with a single line back trace:
14861 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
14862 program shows that 'My_Alloc' is called at 2 different points in the
14863 source (line 21 and line 24). If those two allocation roots need to be
14864 distinguished, the backtrace depth parameter can be used:
14865
14866 @smallexample
14867 $ gnatmem 3 test_gm
14868 @end smallexample
14869
14870 @noindent
14871 which will give the following output:
14872
14873 @smallexample
14874 Global information
14875 ------------------
14876    Total number of allocations        :  18
14877    Total number of deallocations      :   5
14878    Final Water Mark (non freed mem)   :  53.00 Kilobytes
14879    High Water Mark                    :  56.90 Kilobytes
14880
14881 Allocation Root # 1
14882 -------------------
14883  Number of non freed allocations    :  10
14884  Final Water Mark (non freed mem)   :  39.06 Kilobytes
14885  High Water Mark                    :  42.97 Kilobytes
14886  Backtrace                          :
14887    test_gm.adb:11 test_gm.my_alloc
14888    test_gm.adb:24 test_gm
14889    b_test_gm.c:52 main
14890
14891 Allocation Root # 2
14892 -------------------
14893  Number of non freed allocations    :   1
14894  Final Water Mark (non freed mem)   :  10.02 Kilobytes
14895  High Water Mark                    :  10.02 Kilobytes
14896  Backtrace                          :
14897    s-secsta.adb:81  system.secondary_stack.ss_init
14898    s-secsta.adb:283 <system__secondary_stack___elabb>
14899    b_test_gm.c:33   adainit
14900
14901 Allocation Root # 3
14902 -------------------
14903  Number of non freed allocations    :   1
14904  Final Water Mark (non freed mem)   :   3.91 Kilobytes
14905  High Water Mark                    :   3.91 Kilobytes
14906  Backtrace                          :
14907    test_gm.adb:11 test_gm.my_alloc
14908    test_gm.adb:21 test_gm
14909    b_test_gm.c:52 main
14910
14911 Allocation Root # 4
14912 -------------------
14913  Number of non freed allocations    :   1
14914  Final Water Mark (non freed mem)   :  12 Bytes
14915  High Water Mark                    :  12 Bytes
14916  Backtrace                          :
14917    s-secsta.adb:181 system.secondary_stack.ss_init
14918    s-secsta.adb:283 <system__secondary_stack___elabb>
14919    b_test_gm.c:33   adainit
14920 @end smallexample
14921
14922 @noindent
14923 The allocation root #1 of the first example has been split in 2 roots #1
14924 and #3 thanks to the more precise associated backtrace.
14925
14926 @node GDB and GMEM Modes
14927 @section GDB and GMEM Modes
14928
14929 @noindent
14930 The main advantage of the @code{GMEM} mode is that it is a lot faster than the
14931 @code{GDB} mode where the application must be monitored by a @code{GDB} script.
14932 But the @code{GMEM} mode is available only for DEC Unix, Linux x86,
14933 Solaris (sparc and x86) and Windows 95/98/NT/2000 (x86).
14934
14935 @noindent
14936 The main advantage of the @code{GDB} mode is that it is available on all
14937 supported platforms. But it can be very slow if the application does a
14938 lot of allocations and deallocations.
14939
14940 @node Implementation Note
14941 @section Implementation Note
14942
14943 @menu
14944 * gnatmem Using GDB Mode::
14945 * gnatmem Using GMEM Mode::
14946 @end menu
14947
14948 @node gnatmem Using GDB Mode
14949 @subsection @code{gnatmem} Using @code{GDB} Mode
14950
14951 @noindent
14952 @code{gnatmem} executes the user program under the control of @code{GDB} using
14953 a script that sets breakpoints and gathers information on each dynamic
14954 allocation and deallocation. The output of the script is then analyzed
14955 by @code{gnatmem}
14956 in order to locate memory leaks and their origin in the
14957 program. Gnatmem works by recording each address returned by the
14958 allocation procedure (@code{__gnat_malloc})
14959 along with the backtrace at the
14960 allocation point. On each deallocation, the deallocated address is
14961 matched with the corresponding allocation. At the end of the processing,
14962 the unmatched allocations are considered potential leaks. All the
14963 allocations associated with the same backtrace are grouped together and
14964 form an allocation root. The allocation roots are then sorted so that
14965 those with the biggest number of unmatched allocation are printed
14966 first. A delicate aspect of this technique is to distinguish between the
14967 data produced by the user program and the data produced by the gdb
14968 script. Currently, on systems that allow probing the terminal, the gdb
14969 command "tty" is used to force the program output to be redirected to the
14970 current terminal while the @code{gdb} output is directed to a file or to a
14971 pipe in order to be processed subsequently by @code{gnatmem}.
14972
14973 @node gnatmem Using GMEM Mode
14974 @subsection @code{gnatmem} Using @code{GMEM} Mode
14975
14976 @noindent
14977 This mode use the same algorithm to detect memory leak as the @code{GDB}
14978 mode of @code{gnatmem}, the only difference is in the way data are
14979 gathered. In @code{GMEM} mode the program is linked with instrumented
14980 version of @code{__gnat_malloc} and @code{__gnat_free}
14981 routines. Information needed to find memory leak are recorded by these
14982 routines in file @file{gmem.out}. This mode also require that the stack
14983 traceback be available, this is only implemented on some platforms
14984 @ref{GDB and GMEM Modes}.
14985
14986
14987 @node Finding Memory Problems with GNAT Debug Pool
14988 @chapter Finding Memory Problems with GNAT Debug Pool
14989 @findex Debug Pool
14990 @cindex storage, pool, memory corruption
14991
14992 @noindent
14993 The use of unchecked deallocation and unchecked conversion can easily
14994 lead to incorrect memory references. The problems generated by such
14995 references are usually difficult to tackle because the symptoms can be
14996 very remote from the origin of the problem. In such cases, it is
14997 very helpful to detect the problem as early as possible. This is the
14998 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
14999
15000 @noindent
15001 In order to use the GNAT specific debugging pool, the user must
15002 associate a debug pool object with each of the access types that may be
15003 related to suspected memory problems. See Ada Reference Manual
15004 13.11.
15005 @smallexample
15006 @b{type} Ptr @b{is} @b{access} Some_Type;
15007 Pool : GNAT.Debug_Pools.Debug_Pool;
15008 @b{for} Ptr'Storage_Pool @b{use} Pool;
15009 @end smallexample
15010
15011 @code{GNAT.Debug_Pools} is derived from of a GNAT-specific kind of
15012 pool: the Checked_Pool. Such pools, like standard Ada storage pools,
15013 allow the user to redefine allocation and deallocation strategies. They
15014 also provide a checkpoint for each dereference, through the use of
15015 the primitive operation @code{Dereference} which is implicitly called at
15016 each dereference of an access value.
15017
15018 Once an access type has been associated with a debug pool, operations on
15019 values of the type may raise four distinct exceptions,
15020 which correspond to four potential kinds of memory corruption:
15021 @itemize @bullet
15022 @item
15023 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
15024 @item
15025 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
15026 @item
15027 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
15028 @item
15029 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
15030 @end itemize
15031
15032 @noindent
15033 For types associated with a Debug_Pool, dynamic allocation is performed using
15034 the standard
15035 GNAT allocation routine. References to all allocated chunks of memory
15036 are kept in an internal dictionary. The deallocation strategy consists
15037 in not releasing the memory to the underlying system but rather to fill
15038 it with a memory pattern easily recognizable during debugging sessions:
15039 The memory pattern is the old IBM hexadecimal convention: 16#DEADBEEF#.
15040 Upon each dereference, a check is made that the access value denotes a properly
15041 allocated memory location. Here is a complete example of use of
15042 @code{Debug_Pools}, that includes typical instances of  memory corruption:
15043 @smallexample
15044 @iftex
15045 @leftskip=0cm
15046 @end iftex
15047 @b{with} Gnat.Io; @b{use} Gnat.Io;
15048 @b{with} Unchecked_Deallocation;
15049 @b{with} Unchecked_Conversion;
15050 @b{with} GNAT.Debug_Pools;
15051 @b{with} System.Storage_Elements;
15052 @b{with} Ada.Exceptions; @b{use} Ada.Exceptions;
15053 @b{procedure} Debug_Pool_Test @b{is}
15054
15055    @b{type} T @b{is} @b{access} Integer;
15056    @b{type} U @b{is} @b{access} @b{all} T;
15057
15058    P : GNAT.Debug_Pools.Debug_Pool;
15059    @b{for} T'Storage_Pool @b{use} P;
15060
15061    @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T);
15062    @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T);
15063    A, B : @b{aliased} T;
15064
15065    @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line);
15066
15067 @b{begin}
15068    Info (P);
15069    A := @b{new} Integer;
15070    B := @b{new} Integer;
15071    B := A;
15072    Info (P);
15073    Free (A);
15074    @b{begin}
15075       Put_Line (Integer'Image(B.@b{all}));
15076    @b{exception}
15077       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15078    @b{end};
15079    @b{begin}
15080       Free (B);
15081    @b{exception}
15082       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15083    @b{end};
15084    B := UC(A'Access);
15085    @b{begin}
15086       Put_Line (Integer'Image(B.@b{all}));
15087    @b{exception}
15088       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15089    @b{end};
15090    @b{begin}
15091       Free (B);
15092    @b{exception}
15093       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15094    @b{end};
15095    Info (P);
15096 @b{end} Debug_Pool_Test;
15097 @end smallexample
15098 @noindent
15099 The debug pool mechanism provides the following precise diagnostics on the
15100 execution of this erroneous program:
15101 @smallexample
15102 Debug Pool info:
15103   Total allocated bytes :  0
15104   Total deallocated bytes :  0
15105   Current Water Mark:  0
15106   High Water Mark:  0
15107
15108 Debug Pool info:
15109   Total allocated bytes :  8
15110   Total deallocated bytes :  0
15111   Current Water Mark:  8
15112   High Water Mark:  8
15113
15114 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
15115 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
15116 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
15117 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
15118 Debug Pool info:
15119   Total allocated bytes :  8
15120   Total deallocated bytes :  4
15121   Current Water Mark:  4
15122   High Water Mark:  8
15123
15124 @end smallexample
15125
15126 @node Creating Sample Bodies Using gnatstub
15127 @chapter Creating Sample Bodies Using @code{gnatstub}
15128 @findex gnatstub
15129
15130 @noindent
15131 @code{gnatstub} creates body stubs, that is, empty but compilable bodies
15132 for library unit declarations.
15133
15134 To create a body stub, @code{gnatstub} has to compile the library
15135 unit declaration. Therefore, bodies can be created only for legal
15136 library units. Moreover, if a library unit depends semantically upon
15137 units located outside the current directory, you have to provide
15138 the source search path when calling @code{gnatstub}, see the description
15139 of @code{gnatstub} switches below.
15140
15141 @menu
15142 * Running gnatstub::
15143 * Switches for gnatstub::
15144 @end menu
15145
15146 @node Running gnatstub
15147 @section Running @code{gnatstub}
15148
15149 @noindent
15150 @code{gnatstub} has the command-line interface of the form
15151
15152 @smallexample
15153 $ gnatstub [switches] filename [directory]
15154 @end smallexample
15155
15156 @noindent
15157 where
15158 @table @code
15159 @item filename
15160 is the name of the source file that contains a library unit declaration
15161 for which a body must be created. This name should follow the GNAT file name
15162 conventions. No crunching is allowed for this file name. The file
15163 name may contain the path information.
15164
15165 @item directory
15166 indicates the directory to place a body stub (default is the
15167 current directory)
15168
15169 @item switches
15170 is an optional sequence of switches as described in the next section
15171 @end table
15172
15173 @node Switches for gnatstub
15174 @section Switches for @code{gnatstub}
15175
15176 @table @code
15177
15178 @item -f
15179 If the destination directory already contains a file with a name of the body file
15180 for the argument spec file, replace it with the generated body stub.
15181
15182 @item -hs
15183 Put the comment header (i.e. all the comments preceding the
15184 compilation unit) from the source of the library unit declaration
15185 into the body stub.
15186
15187 @item -hg
15188 Put a sample comment header into the body stub.
15189
15190 @item -IDIR
15191 @itemx -I-
15192 These switches have the same meaning as in calls to gcc.
15193 They define the source search path in the call to gcc issued
15194 by @code{gnatstub} to compile an argument source file.
15195
15196 @item -i@var{n}
15197 (@var{n} is a decimal natural number). Set the indentation level in the
15198 generated body sample to n, '-i0' means "no indentation",
15199 the default indentation is 3.
15200
15201 @item -k
15202 Do not remove the tree file (i.e. the snapshot of the compiler internal
15203 structures used by @code{gnatstub}) after creating the body stub.
15204
15205 @item -l@var{n}
15206 (@var{n} is a decimal positive number) Set the maximum line length in the
15207 body stub to n, the default is 78.
15208
15209 @item -q
15210 Quiet mode: do not generate a confirmation when a body is
15211 successfully created or a message when a body is not required for an
15212 argument unit.
15213
15214 @item -r
15215 Reuse the tree file (if it exists) instead of creating it: instead of
15216 creating the tree file for the library unit declaration, gnatstub
15217 tries to find it in the current directory and use it for creating
15218 a body. If the tree file is not found, no body is created. @code{-r}
15219 also implies @code{-k}, whether or not
15220 @code{-k} is set explicitly.
15221
15222 @item -t
15223 Overwrite the existing tree file: if the current directory already
15224 contains the file which, according to the GNAT file name rules should
15225 be considered as a tree file for the argument source file, gnatstub
15226 will refuse to create the tree file needed to create a body sampler,
15227 unless @code{-t} option is set
15228
15229 @item -v
15230 Verbose mode: generate version information.
15231
15232 @end table
15233
15234 @node Reducing the Size of Ada Executables with gnatelim
15235 @chapter Reducing the Size of Ada Executables with @code{gnatelim}
15236 @findex gnatelim
15237
15238 @menu
15239 * About gnatelim::
15240 * Eliminate Pragma::
15241 * Tree Files::
15242 * Preparing Tree and Bind Files for gnatelim::
15243 * Running gnatelim::
15244 * Correcting the List of Eliminate Pragmas::
15245 * Making Your Executables Smaller::
15246 * Summary of the gnatelim Usage Cycle::
15247 @end menu
15248
15249 @node About gnatelim
15250 @section About @code{gnatelim}
15251
15252 @noindent
15253 When a program shares a set of Ada
15254 packages with other programs, it may happen that this program uses
15255 only a fraction of the subprograms defined in these packages. The code
15256 created for these unused subprograms increases the size of the executable.
15257
15258 @code{gnatelim} tracks unused subprograms in an Ada program and
15259 outputs a list of GNAT-specific @code{Eliminate} pragmas (see next
15260 section) marking all the subprograms that are declared but never called.
15261 By placing the list of @code{Eliminate} pragmas in the GNAT configuration
15262 file @file{gnat.adc} and recompiling your program, you may decrease the
15263 size of its executable, because the compiler will not generate the code
15264 for 'eliminated' subprograms.
15265
15266 @code{gnatelim} needs as its input data a set of tree files
15267 (see @ref{Tree Files}) representing all the components of a program to
15268 process and a bind file for a main subprogram (see
15269 @ref{Preparing Tree and Bind Files for gnatelim}).
15270
15271 @node Eliminate Pragma
15272 @section @code{Eliminate} Pragma
15273 @findex Eliminate
15274
15275 @noindent
15276 The simplified syntax of the Eliminate pragma used by @code{gnatelim} is:
15277
15278 @smallexample
15279 @cartouche
15280 @b{pragma} Eliminate (Library_Unit_Name, Subprogram_Name);
15281 @end cartouche
15282 @end smallexample
15283
15284 @noindent
15285 where
15286 @table @code
15287 @item Library_Unit_Name
15288 full expanded Ada name of a library unit
15289
15290 @item Subprogram_Name
15291 a simple or expanded name of a subprogram declared within this
15292 compilation unit
15293
15294 @end table
15295
15296 @noindent
15297 The effect of an @code{Eliminate} pragma placed in the GNAT configuration
15298 file @file{gnat.adc} is:
15299
15300 @itemize @bullet
15301
15302 @item
15303 If the subprogram @code{Subprogram_Name} is declared within
15304 the library unit @code{Library_Unit_Name}, the compiler will not generate
15305 code for this subprogram. This applies to all overloaded subprograms denoted
15306 by @code{Subprogram_Name}.
15307
15308 @item
15309 If a subprogram marked by the pragma @code{Eliminate} is used (called)
15310 in a program, the compiler will produce an error message in the place where
15311 it is called.
15312 @end itemize
15313
15314 @node Tree Files
15315 @section Tree Files
15316 @cindex Tree file
15317
15318 @noindent
15319 A tree file stores a snapshot of the compiler internal data
15320 structures at the very end of a successful compilation. It contains all the
15321 syntactic and semantic information for the compiled unit and all the
15322 units upon which it depends semantically.
15323 To use tools that make use of tree files, you
15324 need to first produce the right set of tree files.
15325
15326 GNAT produces correct tree files when -gnatt -gnatc options are set
15327 in a gcc call. The tree files have an .adt extension.
15328 Therefore, to produce a tree file for the compilation unit contained in a file
15329 named @file{foo.adb}, you must use the command
15330
15331 @smallexample
15332 $ gcc -c -gnatc -gnatt foo.adb
15333 @end smallexample
15334
15335 @noindent
15336 and you will get the tree file @file{foo.adt}.
15337 compilation.
15338
15339 @node Preparing Tree and Bind Files for gnatelim
15340 @section Preparing Tree and Bind Files for @code{gnatelim}
15341
15342 @noindent
15343 A set of tree files covering the program to be analyzed with
15344 @code{gnatelim} and
15345 the bind file for the main subprogram does not have to
15346 be in the current directory.
15347 '-T' gnatelim option may be used to provide
15348 the search path for tree files, and '-b'
15349 option may be used to point to the bind
15350 file to process (see @ref{Running gnatelim})
15351
15352 If you do not have the appropriate set of tree
15353 files and the right bind file, you
15354 may create them in the current directory using the following procedure.
15355
15356 Let @code{Main_Prog} be the name of a main subprogram, and suppose
15357 this subprogram is in a file named @file{main_prog.adb}.
15358
15359 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
15360 the main subprogram. @code{gnatelim} can work with both Ada and C
15361 bind files; when both are present, it uses the Ada bind file.
15362 The following commands will build the program and create the bind file:
15363
15364 @smallexample
15365 $ gnatmake -c Main_Prog
15366 $ gnatbind main_prog
15367 @end smallexample
15368
15369 @noindent
15370 To create a minimal set of tree files covering the whole program, call
15371 @code{gnatmake} for this program as follows:
15372
15373 @smallexample
15374 $ gnatmake -f -c -gnatc -gnatt Main_Prog
15375 @end smallexample
15376
15377 @noindent
15378 The @code{-c} gnatmake option turns off the bind and link
15379 steps, that are useless anyway because the sources are compiled with
15380 @option{-gnatc} option which turns off code generation.
15381
15382 The @code{-f} gnatmake option forces
15383 recompilation of all the needed sources.
15384
15385 This sequence of actions will create all the data needed by @code{gnatelim}
15386 from scratch and therefore guarantee its consistency. If you would like to
15387 use some existing set of files as @code{gnatelim} output, you must make
15388 sure that the set of files is complete and consistent. You can use the
15389 @code{-m} switch to check if there are missed tree files
15390
15391 Note, that @code{gnatelim} needs neither object nor ALI files.
15392
15393 @node Running gnatelim
15394 @section Running @code{gnatelim}
15395
15396 @noindent
15397 @code{gnatelim} has the following command-line interface:
15398
15399 @smallexample
15400 $ gnatelim [options] name
15401 @end smallexample
15402
15403 @noindent
15404 @code{name} should be a full expanded Ada name of a main subprogram
15405 of a program (partition).
15406
15407 @code{gnatelim} options:
15408
15409 @table @code
15410 @item -q
15411 Quiet mode: by default @code{gnatelim} generates to the standard error
15412 stream a trace of the source file names of the compilation units being
15413 processed. This option turns this trace off.
15414
15415 @item -v
15416 Verbose mode: @code{gnatelim} version information is printed as Ada
15417 comments to the standard output stream.
15418
15419 @item -a
15420 Also look for subprograms from the GNAT run time that can be eliminated.
15421
15422 @item -m
15423 Check if any tree files are missing for an accurate result.
15424
15425 @item -T@var{dir}
15426 When looking for tree files also look in directory @var{dir}
15427
15428 @item -b@var{bind_file}
15429 Specifies @var{bind_file} as the bind file to process. If not set, the name
15430 of the bind file is computed from the full expanded Ada name of a main subprogram.
15431
15432 @item -d@var{x}
15433 Activate internal debugging switches. @var{x} is a letter or digit, or
15434 string of letters or digits, which specifies the type of debugging
15435 mode desired.  Normally these are used only for internal development
15436 or system debugging purposes. You can find full documentation for these
15437 switches in the body of the @code{Gnatelim.Options} unit in the compiler
15438 source file @file{gnatelim-options.adb}.
15439 @end table
15440
15441 @noindent
15442 @code{gnatelim} sends its output to the standard output stream, and all the
15443 tracing and debug information is sent to the standard error stream.
15444 In order to produce a proper GNAT configuration file
15445 @file{gnat.adc}, redirection must be used:
15446
15447 @smallexample
15448 $ gnatelim Main_Prog > gnat.adc
15449 @end smallexample
15450
15451 @noindent
15452 or
15453
15454 @smallexample
15455 $ gnatelim Main_Prog >> gnat.adc
15456 @end smallexample
15457
15458 @noindent
15459 In order to append the @code{gnatelim} output to the existing contents of
15460 @file{gnat.adc}.
15461
15462 @node Correcting the List of Eliminate Pragmas
15463 @section Correcting the List of Eliminate Pragmas
15464
15465 @noindent
15466 In some rare cases it may happen that @code{gnatelim} will try to eliminate
15467 subprograms which are actually called in the program. In this case, the
15468 compiler will generate an error message of the form:
15469
15470 @smallexample
15471 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
15472 @end smallexample
15473
15474 @noindent
15475 You will need to manually remove the wrong @code{Eliminate} pragmas from
15476 the @file{gnat.adc} file. It is advised that you recompile your program
15477 from scratch after that because you need a consistent @file{gnat.adc} file
15478 during the entire compilation.
15479
15480 @node Making Your Executables Smaller
15481 @section Making Your Executables Smaller
15482
15483 @noindent
15484 In order to get a smaller executable for your program you now have to
15485 recompile the program completely with the new @file{gnat.adc} file
15486 created by @code{gnatelim} in your current directory:
15487
15488 @smallexample
15489 $ gnatmake -f Main_Prog
15490 @end smallexample
15491
15492 @noindent
15493 (you will need @code{-f} option for gnatmake to
15494 recompile everything
15495 with the set of pragmas @code{Eliminate} you have obtained with
15496 @code{gnatelim}).
15497
15498 Be aware that the set of @code{Eliminate} pragmas is specific to each
15499 program. It is not recommended to merge sets of @code{Eliminate}
15500 pragmas created for different programs in one @file{gnat.adc} file.
15501
15502 @node Summary of the gnatelim Usage Cycle
15503 @section Summary of the gnatelim Usage Cycle
15504
15505 @noindent
15506 Here is a quick summary of the steps to be taken in order to reduce
15507 the size of your executables with @code{gnatelim}. You may use
15508 other GNAT options to control the optimization level,
15509 to produce the debugging information, to set search path, etc.
15510
15511 @enumerate
15512 @item
15513 Produce a bind file and a set of tree files
15514
15515 @smallexample
15516 $ gnatmake -c Main_Prog
15517 $ gnatbind main_prog
15518 $ gnatmake -f -c -gnatc -gnatt Main_Prog
15519 @end smallexample
15520
15521 @item
15522 Generate a list of @code{Eliminate} pragmas
15523 @smallexample
15524 $ gnatelim Main_Prog >[>] gnat.adc
15525 @end smallexample
15526
15527 @item
15528 Recompile the application
15529
15530 @smallexample
15531 $ gnatmake -f Main_Prog
15532 @end smallexample
15533
15534 @end enumerate
15535
15536 @node Other Utility Programs
15537 @chapter Other Utility Programs
15538
15539 @noindent
15540 This chapter discusses some other utility programs available in the Ada
15541 environment.
15542
15543 @menu
15544 * Using Other Utility Programs with GNAT::
15545 * The gnatpsta Utility Program::
15546 * The External Symbol Naming Scheme of GNAT::
15547 * Ada Mode for Glide::
15548 * Converting Ada Files to html with gnathtml::
15549 * Installing gnathtml::
15550 @end menu
15551
15552 @node Using Other Utility Programs with GNAT
15553 @section Using Other Utility Programs with GNAT
15554
15555 @noindent
15556 The object files generated by GNAT are in standard system format and in
15557 particular the debugging information uses this format. This means
15558 programs generated by GNAT can be used with existing utilities that
15559 depend on these formats.
15560
15561 In general, any utility program that works with C will also often work with
15562 Ada programs generated by GNAT. This includes software utilities such as
15563 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
15564 as Purify.
15565
15566 @node The gnatpsta Utility Program
15567 @section The @code{gnatpsta} Utility Program
15568
15569 @noindent
15570 Many of the definitions in package Standard are implementation-dependent.
15571 However, the source of this package does not exist as an Ada source
15572 file, so these values cannot be determined by inspecting the source.
15573 They can be determined by examining in detail the coding of
15574 @file{cstand.adb} which creates the image of Standard in the compiler,
15575 but this is awkward and requires a great deal of internal knowledge
15576 about the system.
15577
15578 The @code{gnatpsta} utility is designed to deal with this situation.
15579 It is an Ada program that dynamically determines the
15580 values of all the relevant parameters in Standard, and prints them
15581 out in the form of an Ada source listing for Standard, displaying all
15582 the values of interest. This output is generated to
15583 @file{stdout}.
15584
15585 To determine the value of any parameter in package Standard, simply
15586 run @code{gnatpsta} with no qualifiers or arguments, and examine
15587 the output. This is preferable to consulting documentation, because
15588 you know that the values you are getting are the actual ones provided
15589 by the executing system.
15590
15591 @node The External Symbol Naming Scheme of GNAT
15592 @section The External Symbol Naming Scheme of GNAT
15593
15594 @noindent
15595 In order to interpret the output from GNAT, when using tools that are
15596 originally intended for use with other languages, it is useful to
15597 understand the conventions used to generate link names from the Ada
15598 entity names.
15599
15600 All link names are in all lowercase letters. With the exception of library
15601 procedure names, the mechanism used is simply to use the full expanded
15602 Ada name with dots replaced by double underscores. For example, suppose
15603 we have the following package spec:
15604
15605 @smallexample
15606 @group
15607 @cartouche
15608 @b{package} QRS @b{is}
15609    MN : Integer;
15610 @b{end} QRS;
15611 @end cartouche
15612 @end group
15613 @end smallexample
15614
15615 @noindent
15616 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
15617 the corresponding link name is @code{qrs__mn}.
15618 @findex Export
15619 Of course if a @code{pragma Export} is used this may be overridden:
15620
15621 @smallexample
15622 @group
15623 @cartouche
15624 @b{package} Exports @b{is}
15625    Var1 : Integer;
15626    @b{pragma} Export (Var1, C, External_Name => "var1_name");
15627    Var2 : Integer;
15628    @b{pragma} Export (Var2, C, Link_Name => "var2_link_name");
15629 @b{end} Exports;
15630 @end cartouche
15631 @end group
15632 @end smallexample
15633
15634 @noindent
15635 In this case, the link name for @var{Var1} is whatever link name the
15636 C compiler would assign for the C function @var{var1_name}. This typically
15637 would be either @var{var1_name} or @var{_var1_name}, depending on operating
15638 system conventions, but other possibilities exist. The link name for
15639 @var{Var2} is @var{var2_link_name}, and this is not operating system
15640 dependent.
15641
15642 @findex _main
15643 One exception occurs for library level procedures. A potential ambiguity
15644 arises between the required name @code{_main} for the C main program,
15645 and the name we would otherwise assign to an Ada library level procedure
15646 called @code{Main} (which might well not be the main program).
15647
15648 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
15649 names. So if we have a library level procedure such as
15650
15651 @smallexample
15652 @group
15653 @cartouche
15654 @b{procedure} Hello (S : String);
15655 @end cartouche
15656 @end group
15657 @end smallexample
15658
15659 @noindent
15660 the external name of this procedure will be @var{_ada_hello}.
15661
15662 @node Ada Mode for Glide
15663 @section Ada Mode for @code{Glide}
15664
15665 @noindent
15666 The Glide mode for programming in Ada (both, Ada83 and Ada95) helps the
15667 user in understanding existing code and facilitates writing new code. It
15668 furthermore provides some utility functions for easier integration of
15669 standard Emacs features when programming in Ada.
15670
15671 @subsection General Features:
15672
15673 @itemize @bullet
15674 @item
15675 Full Integrated Development Environment :
15676
15677 @itemize @bullet
15678 @item
15679 support of 'project files' for the configuration (directories,
15680 compilation options,...)
15681
15682 @item
15683 compiling and stepping through error messages.
15684
15685 @item
15686 running and debugging your applications within Glide.
15687 @end itemize
15688
15689 @item
15690 easy to use for beginners by pull-down menus,
15691
15692 @item
15693 user configurable by many user-option variables.
15694 @end itemize
15695
15696 @subsection Ada Mode Features That Help Understanding Code:
15697
15698 @itemize @bullet
15699 @item
15700 functions for easy and quick stepping through Ada code,
15701
15702 @item
15703 getting cross reference information for identifiers (e.g. find the
15704 defining place by a keystroke),
15705
15706 @item
15707 displaying an index menu of types and subprograms and move point to
15708 the chosen one,
15709
15710 @item
15711 automatic color highlighting of the various entities in Ada code.
15712 @end itemize
15713
15714 @subsection Glide Support for Writing Ada Code:
15715
15716 @itemize @bullet
15717 @item
15718 switching between spec and body files with possible
15719 autogeneration of body files,
15720
15721 @item
15722 automatic formating of subprograms parameter lists.
15723
15724 @item
15725 automatic smart indentation according to Ada syntax,
15726
15727 @item
15728 automatic completion of identifiers,
15729
15730 @item
15731 automatic casing of identifiers, keywords, and attributes,
15732
15733 @item
15734 insertion of statement templates,
15735
15736 @item
15737 filling comment paragraphs like filling normal text,
15738 @end itemize
15739
15740 For more information, please refer to the online Glide documentation
15741 available in the Glide --> Help Menu.
15742
15743 @node Converting Ada Files to html with gnathtml
15744 @section Converting Ada Files to html with @code{gnathtml}
15745
15746 @noindent
15747 This @code{Perl} script allows Ada source files to be browsed using
15748 standard Web browsers. For installation procedure, see the section
15749 @xref{Installing gnathtml}.
15750
15751 Ada reserved keywords are highlighted in a bold font and Ada comments in
15752 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
15753 switch to suppress the generation of cross-referencing information, user
15754 defined variables and types will appear in a different color; you will
15755 be able to click on any identifier and go to its declaration.
15756
15757 The command line is as follow:
15758 @smallexample
15759 $ perl gnathtml.pl [switches] ada-files
15760 @end smallexample
15761
15762 You can pass it as many Ada files as you want. @code{gnathtml} will generate
15763 an html file for every ada file, and a global file called @file{index.htm}.
15764 This file is an index of every identifier defined in the files.
15765
15766 The available switches are the following ones :
15767
15768 @table @code
15769 @item -83
15770 @cindex @code{-83} (@code{gnathtml})
15771 Only the subset on the Ada 83 keywords will be highlighted, not the full
15772 Ada 95 keywords set.
15773
15774 @item -cc @var{color}
15775 This option allows you to change the color used for comments. The default
15776 value is green. The color argument can be any name accepted by html.
15777
15778 @item -d
15779 @cindex @code{-d} (@code{gnathtml})
15780 If the ada files depend on some other files (using for instance the
15781 @code{with} command, the latter will also be converted to html.
15782 Only the files in the user project will be converted to html, not the files
15783 in the run-time library itself.
15784
15785 @item -D
15786 This command is the same as -d above, but @code{gnathtml} will also look
15787 for files in the run-time library, and generate html files for them.
15788
15789 @item -f
15790 @cindex @code{-f} (@code{gnathtml})
15791 By default, gnathtml will generate html links only for global entities
15792 ('with'ed units, global variables and types,...). If you specify the
15793 @code{-f} on the command line, then links will be generated for local
15794 entities too.
15795
15796 @item -l @var{number}
15797 @cindex @code{-l} (@code{gnathtml})
15798 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
15799 will number the html files every @var{number} line.
15800
15801 @item -I @var{dir}
15802 @cindex @code{-I} (@code{gnathtml})
15803 Specify a directory to search for library files (@file{.ali} files) and
15804 source files. You can provide several -I switches on the command line,
15805 and the directories will be parsed in the order of the command line.
15806
15807 @item -o @var{dir}
15808 @cindex @code{-o} (@code{gnathtml})
15809 Specify the output directory for html files. By default, gnathtml will
15810 saved the generated html files in a subdirectory named @file{html/}.
15811
15812 @item -p @var{file}
15813 @cindex @code{-p} (@code{gnathtml})
15814 If you are using Emacs and the most recent Emacs Ada mode, which provides
15815 a full Integrated Development Environment for compiling, checking,
15816 running and debugging applications, you may be using @file{.adp} files
15817 to give the directories where Emacs can find sources and object files.
15818
15819 Using this switch, you can tell gnathtml to use these files. This allows
15820 you to get an html version of your application, even if it is spread
15821 over multiple directories.
15822
15823 @item -sc @var{color}
15824 @cindex @code{-sc} (@code{gnathtml})
15825 This option allows you to change the color used for symbol definitions.
15826 The default value is red. The color argument can be any name accepted by html.
15827
15828 @item -t @var{file}
15829 @cindex @code{-t} (@code{gnathtml})
15830 This switch provides the name of a file. This file contains a list of
15831 file names to be converted, and the effect is exactly as though they had
15832 appeared explicitly on the command line. This
15833 is the recommended way to work around the command line length limit on some
15834 systems.
15835
15836 @end table
15837
15838 @node Installing gnathtml
15839 @section Installing @code{gnathtml}
15840
15841 @noindent
15842 @code{Perl} needs to be installed on your machine to run this script.
15843 @code{Perl} is freely available for almost every architecture and
15844 Operating System via the Internet.
15845
15846 On Unix systems, you  may want to modify  the  first line of  the script
15847 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
15848 is. The syntax of this line is :
15849 @smallexample
15850 #!full_path_name_to_perl
15851 @end smallexample
15852
15853 @noindent
15854 Alternatively, you may run the script using the following command line:
15855
15856 @smallexample
15857 $ perl gnathtml.pl [switches] files
15858 @end smallexample
15859
15860
15861 @node Running and Debugging Ada Programs
15862 @chapter Running and Debugging Ada Programs
15863 @cindex Debugging
15864
15865 @noindent
15866 This chapter discusses how to debug Ada programs. An incorrect Ada program
15867 may be handled in three ways by the GNAT compiler:
15868
15869 @enumerate
15870 @item
15871 The illegality may be a violation of the static semantics of Ada. In
15872 that case GNAT diagnoses the constructs in the program that are illegal.
15873 It is then a straightforward matter for the user to modify those parts of
15874 the program.
15875
15876 @item
15877 The illegality may be a violation of the dynamic semantics of Ada. In
15878 that case the program compiles and executes, but may generate incorrect
15879 results, or may terminate abnormally with some exception.
15880
15881 @item
15882 When presented with a program that contains convoluted errors, GNAT
15883 itself may terminate abnormally without providing full diagnostics on
15884 the incorrect user program.
15885 @end enumerate
15886
15887 @menu
15888 * The GNAT Debugger GDB::
15889 * Running GDB::
15890 * Introduction to GDB Commands::
15891 * Using Ada Expressions::
15892 * Calling User-Defined Subprograms::
15893 * Using the Next Command in a Function::
15894 * Ada Exceptions::
15895 * Ada Tasks::
15896 * Debugging Generic Units::
15897 * GNAT Abnormal Termination or Failure to Terminate::
15898 * Naming Conventions for GNAT Source Files::
15899 * Getting Internal Debugging Information::
15900 * Stack Traceback::
15901 @end menu
15902
15903 @cindex Debugger
15904 @findex gdb
15905
15906 @node The GNAT Debugger GDB
15907 @section The GNAT Debugger GDB
15908
15909 @noindent
15910 @code{GDB} is a general purpose, platform-independent debugger that
15911 can be used to debug mixed-language programs compiled with @code{GCC},
15912 and in particular is capable of debugging Ada programs compiled with
15913 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
15914 complex Ada data structures.
15915
15916 The manual @cite{Debugging with GDB}
15917 contains full details on the usage of @code{GDB}, including a section on
15918 its usage on programs. This manual should be consulted for full
15919 details. The section that follows is a brief introduction to the
15920 philosophy and use of @code{GDB}.
15921
15922 When GNAT programs are compiled, the compiler optionally writes debugging
15923 information into the generated object file, including information on
15924 line numbers, and on declared types and variables. This information is
15925 separate from the generated code. It makes the object files considerably
15926 larger, but it does not add to the size of the actual executable that
15927 will be loaded into memory, and has no impact on run-time performance. The
15928 generation of debug information is triggered by the use of the
15929 -g switch in the gcc or gnatmake command used to carry out
15930 the compilations. It is important to emphasize that the use of these
15931 options does not change the generated code.
15932
15933 The debugging information is written in standard system formats that
15934 are used by many tools, including debuggers and profilers. The format
15935 of the information is typically designed to describe C types and
15936 semantics, but GNAT implements a translation scheme which allows full
15937 details about Ada types and variables to be encoded into these
15938 standard C formats. Details of this encoding scheme may be found in
15939 the file exp_dbug.ads in the GNAT source distribution. However, the
15940 details of this encoding are, in general, of no interest to a user,
15941 since @code{GDB} automatically performs the necessary decoding.
15942
15943 When a program is bound and linked, the debugging information is
15944 collected from the object files, and stored in the executable image of
15945 the program. Again, this process significantly increases the size of
15946 the generated executable file, but it does not increase the size of
15947 the executable program itself. Furthermore, if this program is run in
15948 the normal manner, it runs exactly as if the debug information were
15949 not present, and takes no more actual memory.
15950
15951 However, if the program is run under control of @code{GDB}, the
15952 debugger is activated.  The image of the program is loaded, at which
15953 point it is ready to run.  If a run command is given, then the program
15954 will run exactly as it would have if @code{GDB} were not present. This
15955 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
15956 entirely non-intrusive until a breakpoint is encountered.  If no
15957 breakpoint is ever hit, the program will run exactly as it would if no
15958 debugger were present. When a breakpoint is hit, @code{GDB} accesses
15959 the debugging information and can respond to user commands to inspect
15960 variables, and more generally to report on the state of execution.
15961
15962 @node Running GDB
15963 @section Running GDB
15964
15965 @noindent
15966 The debugger can be launched directly and simply from @code{glide} or
15967 through its graphical interface: @code{gvd}. It can also be used
15968 directly in text mode. Here is described the basic use of @code{GDB}
15969 in text mode. All the commands described below can be used in the
15970 @code{gvd} console window eventhough there is usually other more
15971 graphical ways to achieve the same goals.
15972
15973 @noindent
15974 The command to run de graphical interface of the debugger is
15975 @smallexample
15976 $ gvd program
15977 @end smallexample
15978
15979 @noindent
15980 The command to run @code{GDB} in text mode is
15981
15982 @smallexample
15983 $ gdb program
15984 @end smallexample
15985
15986 @noindent
15987 where @code{program} is the name of the executable file. This
15988 activates the debugger and results in a prompt for debugger commands.
15989 The simplest command is simply @code{run}, which causes the program to run
15990 exactly as if the debugger were not present. The following section
15991 describes some of the additional commands that can be given to @code{GDB}.
15992
15993
15994 @node Introduction to GDB Commands
15995 @section Introduction to GDB Commands
15996
15997 @noindent
15998 @code{GDB} contains a large repertoire of commands. The manual
15999 @cite{Debugging with GDB}
16000 includes extensive documentation on the use
16001 of these commands, together with examples of their use. Furthermore,
16002 the command @var{help} invoked from within @code{GDB} activates a simple help
16003 facility which summarizes the available commands and their options.
16004 In this section we summarize a few of the most commonly
16005 used commands to give an idea of what @code{GDB} is about. You should create
16006 a simple program with debugging information and experiment with the use of
16007 these @code{GDB} commands on the program as you read through the
16008 following section.
16009
16010 @table @code
16011 @item set args @var{arguments}
16012 The @var{arguments} list above is a list of arguments to be passed to
16013 the program on a subsequent run command, just as though the arguments
16014 had been entered on a normal invocation of the program. The @code{set args}
16015 command is not needed if the program does not require arguments.
16016
16017 @item run
16018 The @code{run} command causes execution of the program to start from
16019 the beginning. If the program is already running, that is to say if
16020 you are currently positioned at a breakpoint, then a prompt will ask
16021 for confirmation that you want to abandon the current execution and
16022 restart.
16023
16024 @item breakpoint @var{location}
16025 The breakpoint command sets a breakpoint, that is to say a point at which
16026 execution will halt and @code{GDB} will await further
16027 commands. @var{location} is
16028 either a line number within a file, given in the format @code{file:linenumber},
16029 or it is the name of a subprogram. If you request that a breakpoint be set on
16030 a subprogram that is overloaded, a prompt will ask you to specify on which of
16031 those subprograms you want to breakpoint. You can also
16032 specify that all of them should be breakpointed. If the program is run
16033 and execution encounters the breakpoint, then the program
16034 stops and @code{GDB} signals that the breakpoint was encountered by
16035 printing the line of code before which the program is halted.
16036
16037 @item breakpoint exception @var{name}
16038 A special form of the breakpoint command which breakpoints whenever
16039 exception @var{name} is raised.
16040 If @var{name} is omitted,
16041 then a breakpoint will occur when any exception is raised.
16042
16043 @item print @var{expression}
16044 This will print the value of the given expression. Most simple
16045 Ada expression formats are properly handled by @code{GDB}, so the expression
16046 can contain function calls, variables, operators, and attribute references.
16047
16048 @item continue
16049 Continues execution following a breakpoint, until the next breakpoint or the
16050 termination of the program.
16051
16052 @item step
16053 Executes a single line after a breakpoint. If the next statement is a subprogram
16054 call, execution continues into (the first statement of) the
16055 called subprogram.
16056
16057 @item next
16058 Executes a single line. If this line is a subprogram call, executes and
16059 returns from the call.
16060
16061 @item list
16062 Lists a few lines around the current source location. In practice, it
16063 is usually more convenient to have a separate edit window open with the
16064 relevant source file displayed. Successive applications of this command
16065 print subsequent lines. The command can be given an argument which is a
16066 line number, in which case it displays a few lines around the specified one.
16067
16068 @item backtrace
16069 Displays a backtrace of the call chain. This command is typically
16070 used after a breakpoint has occurred, to examine the sequence of calls that
16071 leads to the current breakpoint. The display includes one line for each
16072 activation record (frame) corresponding to an active subprogram.
16073
16074 @item up
16075 At a breakpoint, @code{GDB} can display the values of variables local
16076 to the current frame. The command @code{up} can be used to
16077 examine the contents of other active frames, by moving the focus up
16078 the stack, that is to say from callee to caller, one frame at a time.
16079
16080 @item down
16081 Moves the focus of @code{GDB} down from the frame currently being
16082 examined to the frame of its callee (the reverse of the previous command),
16083
16084 @item frame @var{n}
16085 Inspect the frame with the given number. The value 0 denotes the frame
16086 of the current breakpoint, that is to say the top of the call stack.
16087
16088 @end table
16089
16090 The above list is a very short introduction to the commands that
16091 @code{GDB} provides. Important additional capabilities, including conditional
16092 breakpoints, the ability to execute command sequences on a breakpoint,
16093 the ability to debug at the machine instruction level and many other
16094 features are described in detail in @cite{Debugging with GDB}.
16095 Note that most commands can be abbreviated
16096 (for example, c for continue, bt for backtrace).
16097
16098 @node Using Ada Expressions
16099 @section Using Ada Expressions
16100 @cindex Ada expressions
16101
16102 @noindent
16103 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
16104 extensions. The philosophy behind the design of this subset is
16105
16106 @itemize @bullet
16107 @item
16108 That @code{GDB} should provide basic literals and access to operations for
16109 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
16110 leaving more sophisticated computations to subprograms written into the
16111 program (which therefore may be called from @code{GDB}).
16112
16113 @item
16114 That type safety and strict adherence to Ada language restrictions
16115 are not particularly important to the @code{GDB} user.
16116
16117 @item
16118 That brevity is important to the @code{GDB} user.
16119 @end itemize
16120
16121 Thus, for brevity, the debugger acts as if there were
16122 implicit @code{with} and @code{use} clauses in effect for all user-written
16123 packages, thus making it unnecessary to fully qualify most names with
16124 their packages, regardless of context. Where this causes ambiguity,
16125 @code{GDB} asks the user's intent.
16126
16127 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
16128
16129 @node Calling User-Defined Subprograms
16130 @section Calling User-Defined Subprograms
16131
16132 @noindent
16133 An important capability of @code{GDB} is the ability to call user-defined
16134 subprograms while debugging. This is achieved simply by entering
16135 a subprogram call statement in the form:
16136
16137 @smallexample
16138 call subprogram-name (parameters)
16139 @end smallexample
16140
16141 @noindent
16142 The keyword @code{call} can be omitted in the normal case where the
16143 @code{subprogram-name} does not coincide with any of the predefined
16144 @code{GDB} commands.
16145
16146 The effect is to invoke the given subprogram, passing it the
16147 list of parameters that is supplied. The parameters can be expressions and
16148 can include variables from the program being debugged. The
16149 subprogram must be defined
16150 at the library level within your program, and @code{GDB} will call the
16151 subprogram within the environment of your program execution (which
16152 means that the subprogram is free to access or even modify variables
16153 within your program).
16154
16155 The most important use of this facility is in allowing the inclusion of
16156 debugging routines that are tailored to particular data structures
16157 in your program. Such debugging routines can be written to provide a suitably
16158 high-level description of an abstract type, rather than a low-level dump
16159 of its physical layout. After all, the standard
16160 @code{GDB print} command only knows the physical layout of your
16161 types, not their abstract meaning. Debugging routines can provide information
16162 at the desired semantic level and are thus enormously useful.
16163
16164 For example, when debugging GNAT itself, it is crucial to have access to
16165 the contents of the tree nodes used to represent the program internally.
16166 But tree nodes are represented simply by an integer value (which in turn
16167 is an index into a table of nodes).
16168 Using the @code{print} command on a tree node would simply print this integer
16169 value, which is not very useful. But the PN routine (defined in file
16170 treepr.adb in the GNAT sources) takes a tree node as input, and displays
16171 a useful high level representation of the tree node, which includes the
16172 syntactic category of the node, its position in the source, the integers
16173 that denote descendant nodes and parent node, as well as varied
16174 semantic information. To study this example in more detail, you might want to
16175 look at the body of the PN procedure in the stated file.
16176
16177 @node Using the Next Command in a Function
16178 @section Using the Next Command in a Function
16179
16180 @noindent
16181 When you use the @code{next} command in a function, the current source
16182 location will advance to the next statement as usual. A special case
16183 arises in the case of a @code{return} statement.
16184
16185 Part of the code for a return statement is the "epilog" of the function.
16186 This is the code that returns to the caller. There is only one copy of
16187 this epilog code, and it is typically associated with the last return
16188 statement in the function if there is more than one return. In some
16189 implementations, this epilog is associated with the first statement
16190 of the function.
16191
16192 The result is that if you use the @code{next} command from a return
16193 statement that is not the last return statement of the function you
16194 may see a strange apparent jump to the last return statement or to
16195 the start of the function. You should simply ignore this odd jump.
16196 The value returned is always that from the first return statement
16197 that was stepped through.
16198
16199 @node Ada Exceptions
16200 @section Breaking on Ada Exceptions
16201 @cindex Exceptions
16202
16203 @noindent
16204 You can set breakpoints that trip when your program raises
16205 selected exceptions.
16206
16207 @table @code
16208 @item break exception
16209 Set a breakpoint that trips whenever (any task in the) program raises
16210 any exception.
16211
16212 @item break exception @var{name}
16213 Set a breakpoint that trips whenever (any task in the) program raises
16214 the exception @var{name}.
16215
16216 @item break exception unhandled
16217 Set a breakpoint that trips whenever (any task in the) program raises an
16218 exception for which there is no handler.
16219
16220 @item info exceptions
16221 @itemx info exceptions @var{regexp}
16222 The @code{info exceptions} command permits the user to examine all defined
16223 exceptions within Ada programs. With a regular expression, @var{regexp}, as
16224 argument, prints out only those exceptions whose name matches @var{regexp}.
16225 @end table
16226
16227 @node Ada Tasks
16228 @section Ada Tasks
16229 @cindex Tasks
16230
16231 @noindent
16232 @code{GDB} allows the following task-related commands:
16233
16234 @table @code
16235 @item info tasks
16236 This command shows a list of current Ada tasks, as in the following example:
16237
16238 @smallexample
16239 @iftex
16240 @leftskip=0cm
16241 @end iftex
16242 (gdb) info tasks
16243   ID       TID P-ID   Thread Pri State                 Name
16244    1   8088000   0   807e000  15 Child Activation Wait main_task
16245    2   80a4000   1   80ae000  15 Accept/Select Wait    b
16246    3   809a800   1   80a4800  15 Child Activation Wait a
16247 *  4   80ae800   3   80b8000  15 Running               c
16248 @end smallexample
16249
16250 @noindent
16251 In this listing, the asterisk before the first task indicates it to be the
16252 currently running task. The first column lists the task ID that is used
16253 to refer to tasks in the following commands.
16254
16255 @item break @var{linespec} task @var{taskid}
16256 @itemx break @var{linespec} task @var{taskid} if @dots{}
16257 @cindex Breakpoints and tasks
16258 These commands are like the @code{break @dots{} thread @dots{}}.
16259 @var{linespec} specifies source lines.
16260
16261 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
16262 to specify that you only want @code{GDB} to stop the program when a
16263 particular Ada task reaches this breakpoint. @var{taskid} is one of the
16264 numeric task identifiers assigned by @code{GDB}, shown in the first
16265 column of the @samp{info tasks} display.
16266
16267 If you do not specify @samp{task @var{taskid}} when you set a
16268 breakpoint, the breakpoint applies to @emph{all} tasks of your
16269 program.
16270
16271 You can use the @code{task} qualifier on conditional breakpoints as
16272 well; in this case, place @samp{task @var{taskid}} before the
16273 breakpoint condition (before the @code{if}).
16274
16275 @item task @var{taskno}
16276 @cindex Task switching
16277
16278 This command allows to switch to the task referred by @var{taskno}. In
16279 particular, This allows to browse the backtrace of the specified
16280 task. It is advised to switch back to the original task before
16281 continuing execution otherwise the scheduling of the program may be
16282 perturbated.
16283 @end table
16284
16285 @noindent
16286 For more detailed information on the tasking support, see @cite{Debugging with GDB}.
16287
16288 @node Debugging Generic Units
16289 @section Debugging Generic Units
16290 @cindex Debugging Generic Units
16291 @cindex Generics
16292
16293 @noindent
16294 GNAT always uses code expansion for generic instantiation. This means that
16295 each time an instantiation occurs, a complete copy of the original code is
16296 made, with appropriate substitutions of formals by actuals.
16297
16298 It is not possible to refer to the original generic entities in
16299 @code{GDB}, but it is always possible to debug a particular instance of
16300 a generic, by using the appropriate expanded names. For example, if we have
16301
16302 @smallexample
16303 @group
16304 @cartouche
16305 @b{procedure} g @b{is}
16306
16307    @b{generic package} k @b{is}
16308       @b{procedure} kp (v1 : @b{in out} integer);
16309    @b{end} k;
16310
16311    @b{package body} k @b{is}
16312       @b{procedure} kp (v1 : @b{in out} integer) @b{is}
16313       @b{begin}
16314          v1 := v1 + 1;
16315       @b{end} kp;
16316    @b{end} k;
16317
16318    @b{package} k1 @b{is new} k;
16319    @b{package} k2 @b{is new} k;
16320
16321    var : integer := 1;
16322
16323 @b{begin}
16324    k1.kp (var);
16325    k2.kp (var);
16326    k1.kp (var);
16327    k2.kp (var);
16328 @b{end};
16329 @end cartouche
16330 @end group
16331 @end smallexample
16332
16333 @noindent
16334 Then to break on a call to procedure kp in the k2 instance, simply
16335 use the command:
16336
16337 @smallexample
16338 (gdb) break g.k2.kp
16339 @end smallexample
16340
16341 @noindent
16342 When the breakpoint occurs, you can step through the code of the
16343 instance in the normal manner and examine the values of local variables, as for
16344 other units.
16345
16346 @node GNAT Abnormal Termination or Failure to Terminate
16347 @section GNAT Abnormal Termination or Failure to Terminate
16348 @cindex GNAT Abnormal Termination or Failure to Terminate
16349
16350 @noindent
16351 When presented with programs that contain serious errors in syntax
16352 or semantics,
16353 GNAT may on rare occasions  experience problems in operation, such
16354 as aborting with a
16355 segmentation fault or illegal memory access, raising an internal
16356 exception, terminating abnormally, or failing to terminate at all.
16357 In such cases, you can activate
16358 various features of GNAT that can help you pinpoint the construct in your
16359 program that is the likely source of the problem.
16360
16361 The following strategies are presented in increasing order of
16362 difficulty, corresponding to your experience in using GNAT and your
16363 familiarity with compiler internals.
16364
16365 @enumerate
16366 @item
16367 Run @code{gcc} with the @option{-gnatf}. This first
16368 switch causes all errors on a given line to be reported. In its absence,
16369 only the first error on a line is displayed.
16370
16371 The @option{-gnatdO} switch causes errors to be displayed as soon as they
16372 are encountered, rather than after compilation is terminated. If GNAT
16373 terminates prematurely or goes into an infinite loop, the last error
16374 message displayed may help to pinpoint the culprit.
16375
16376 @item
16377 Run @code{gcc} with the @code{-v (verbose)} switch. In this mode,
16378 @code{gcc} produces ongoing information about the progress of the
16379 compilation and provides the name of each procedure as code is
16380 generated. This switch allows you to find which Ada procedure was being
16381 compiled when it encountered a code generation problem.
16382
16383 @item
16384 @cindex @option{-gnatdc} switch
16385 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
16386 switch that does for the front-end what @code{-v} does for the back end.
16387 The system prints the name of each unit, either a compilation unit or
16388 nested unit, as it is being analyzed.
16389 @item
16390 Finally, you can start
16391 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
16392 front-end of GNAT, and can be run independently (normally it is just
16393 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
16394 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
16395 @code{where} command is the first line of attack; the variable
16396 @code{lineno} (seen by @code{print lineno}), used by the second phase of
16397 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
16398 which the execution stopped, and @code{input_file name} indicates the name of
16399 the source file.
16400 @end enumerate
16401
16402 @node Naming Conventions for GNAT Source Files
16403 @section Naming Conventions for GNAT Source Files
16404
16405 @noindent
16406 In order to examine the workings of the GNAT system, the following
16407 brief description of its organization may be helpful:
16408
16409 @itemize @bullet
16410 @item
16411 Files with prefix @file{sc} contain the lexical scanner.
16412
16413 @item
16414 All files prefixed with @file{par} are components of the parser. The
16415 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
16416 parsing of select statements can be found in @file{par-ch9.adb}.
16417
16418 @item
16419 All files prefixed with @file{sem} perform semantic analysis. The
16420 numbers correspond to chapters of the Ada standard. For example, all
16421 issues involving context clauses can be found in @file{sem_ch10.adb}. In
16422 addition, some features of the language require sufficient special processing
16423 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
16424 dynamic dispatching, etc.
16425
16426 @item
16427 All files prefixed with @file{exp} perform normalization and
16428 expansion of the intermediate representation (abstract syntax tree, or AST).
16429 these files use the same numbering scheme as the parser and semantics files.
16430 For example, the construction of record initialization procedures is done in
16431 @file{exp_ch3.adb}.
16432
16433 @item
16434 The files prefixed with @file{bind} implement the binder, which
16435 verifies the consistency of the compilation, determines an order of
16436 elaboration, and generates the bind file.
16437
16438 @item
16439 The files @file{atree.ads} and @file{atree.adb} detail the low-level
16440 data structures used by the front-end.
16441
16442 @item
16443 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
16444 the abstract syntax tree as produced by the parser.
16445
16446 @item
16447 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
16448 all entities, computed during semantic analysis.
16449
16450 @item
16451 Library management issues are dealt with in files with prefix
16452 @file{lib}.
16453
16454 @item
16455 @findex Ada
16456 @cindex Annex A
16457 Ada files with the prefix @file{a-} are children of @code{Ada}, as
16458 defined in Annex A.
16459
16460 @item
16461 @findex Interfaces
16462 @cindex Annex B
16463 Files with prefix @file{i-} are children of @code{Interfaces}, as
16464 defined in Annex B.
16465
16466 @item
16467 @findex System
16468 Files with prefix @file{s-} are children of @code{System}. This includes
16469 both language-defined children and GNAT run-time routines.
16470
16471 @item
16472 @findex GNAT
16473 Files with prefix @file{g-} are children of @code{GNAT}. These are useful
16474 general-purpose packages, fully documented in their specifications. All
16475 the other @file{.c} files are modifications of common @code{gcc} files.
16476 @end itemize
16477
16478 @node Getting Internal Debugging Information
16479 @section Getting Internal Debugging Information
16480
16481 @noindent
16482 Most compilers have internal debugging switches and modes. GNAT
16483 does also, except GNAT internal debugging switches and modes are not
16484 secret. A summary and full description of all the compiler and binder
16485 debug flags are in the file @file{debug.adb}. You must obtain the
16486 sources of the compiler to see the full detailed effects of these flags.
16487
16488 The switches that print the source of the program (reconstructed from
16489 the internal tree) are of general interest for user programs, as are the
16490 options to print
16491 the full internal tree, and the entity table (the symbol table
16492 information). The reconstructed source provides a readable version of the
16493 program after the front-end has completed analysis and  expansion, and is useful
16494 when studying the performance of specific constructs. For example, constraint
16495 checks are indicated, complex aggregates are replaced with loops and
16496 assignments, and tasking primitives are replaced with run-time calls.
16497
16498 @node Stack Traceback
16499 @section Stack Traceback
16500 @cindex traceback
16501 @cindex stack traceback
16502 @cindex stack unwinding
16503
16504 @noindent
16505 Traceback is a mechanism to display the sequence of subprogram calls that
16506 leads to a specified execution point in a program. Often (but not always)
16507 the execution point is an instruction at which an exception has been raised.
16508 This mechanism is also known as @i{stack unwinding} because it obtains
16509 its information by scanning the run-time stack and recovering the activation
16510 records of all active subprograms. Stack unwinding is one of the most
16511 important tools for program debugging.
16512
16513 @noindent
16514 The first entry stored in traceback corresponds to the deepest calling level,
16515 that is to say the subprogram currently executing the instruction
16516 from which we want to obtain the traceback.
16517
16518 @noindent
16519 Note that there is no runtime performance penalty when stack traceback
16520 is enabled and no exception are raised during program execution.
16521
16522 @menu
16523 * Non-Symbolic Traceback::
16524 * Symbolic Traceback::
16525 @end menu
16526
16527 @node Non-Symbolic Traceback
16528 @subsection Non-Symbolic Traceback
16529 @cindex traceback, non-symbolic
16530
16531 @noindent
16532 Note: this feature is not supported on all platforms. See
16533 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
16534 platforms.
16535
16536 @menu
16537 * Tracebacks From an Unhandled Exception::
16538 * Tracebacks From Exception Occurrences (non-symbolic)::
16539 * Tracebacks From Anywhere in a Program (non-symbolic)::
16540 @end menu
16541
16542 @node Tracebacks From an Unhandled Exception
16543 @subsubsection Tracebacks From an Unhandled Exception
16544
16545 @noindent
16546 A runtime non-symbolic traceback is a list of addresses of call instructions.
16547 To enable this feature you must use the @code{-E}
16548 @code{gnatbind}'s option. With this option a stack traceback is stored as part
16549 of exception information. It is possible to retrieve this information using the
16550 standard @code{Ada.Exception.Exception_Information} routine.
16551
16552 @noindent
16553 Let's have a look at a simple example:
16554
16555 @smallexample
16556 @cartouche
16557 @group
16558 procedure STB is
16559
16560    procedure P1 is
16561    begin
16562       raise Constraint_Error;
16563    end P1;
16564
16565    procedure P2 is
16566    begin
16567       P1;
16568    end P2;
16569
16570 begin
16571    P2;
16572 end STB;
16573 @end group
16574 @end cartouche
16575 @end smallexample
16576
16577 @smallexample
16578 $ gnatmake stb -bargs -E
16579 $ stb
16580
16581 Execution terminated by unhandled exception
16582 Exception name: CONSTRAINT_ERROR
16583 Message: stb.adb:5
16584 Call stack traceback locations:
16585 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
16586 @end smallexample
16587
16588 @noindent
16589 As we see the traceback lists a sequence of addresses for the unhandled
16590 exception @code{CONSTAINT_ERROR} raised in procedure P1. It is easy to
16591 guess that this exception come from procedure P1. To translate these
16592 addresses into the source lines where the calls appear, the
16593 @code{addr2line} tool, described below, is invaluable. The use of this tool
16594 requires the program to be compiled with debug information.
16595
16596 @smallexample
16597 $ gnatmake -g stb -bargs -E
16598 $ stb
16599
16600 Execution terminated by unhandled exception
16601 Exception name: CONSTRAINT_ERROR
16602 Message: stb.adb:5
16603 Call stack traceback locations:
16604 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
16605
16606 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
16607    0x4011f1 0x77e892a4
16608
16609 00401373 at d:/stb/stb.adb:5
16610 0040138B at d:/stb/stb.adb:10
16611 0040139C at d:/stb/stb.adb:14
16612 00401335 at d:/stb/b~stb.adb:104
16613 004011C4 at /build/.../crt1.c:200
16614 004011F1 at /build/.../crt1.c:222
16615 77E892A4 in ?? at ??:0
16616 @end smallexample
16617
16618 @noindent
16619 @code{addr2line} has a number of other useful options:
16620
16621 @table @code
16622 @item --functions
16623 to get the function name corresponding to any location
16624
16625 @item --demangle=gnat
16626 to use the @b{gnat} decoding mode for the function names. Note that
16627 for binutils version 2.9.x the option is simply @code{--demangle}.
16628 @end table
16629
16630 @smallexample
16631 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
16632    0x40139c 0x401335 0x4011c4 0x4011f1
16633
16634 00401373 in stb.p1 at d:/stb/stb.adb:5
16635 0040138B in stb.p2 at d:/stb/stb.adb:10
16636 0040139C in stb at d:/stb/stb.adb:14
16637 00401335 in main at d:/stb/b~stb.adb:104
16638 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
16639 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
16640 @end smallexample
16641
16642 @noindent
16643 From this traceback we can see that the exception was raised in
16644 @file{stb.adb} at line 5, which was reached from a procedure call in
16645 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
16646 which contains the call to the main program.
16647 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
16648 and the output will vary from platform to platform.
16649
16650 @noindent
16651 It is also possible to use @code{GDB} with these traceback addresses to debug
16652 the program. For example, we can break at a given code location, as reported
16653 in the stack traceback:
16654
16655 @smallexample
16656 $ gdb -nw stb
16657 @noindent
16658 Furthermore, this feature is not implemented inside Windows DLL. Only
16659 the non-symbolic traceback is reported in this case.
16660
16661 (gdb) break *0x401373
16662 Breakpoint 1 at 0x401373: file stb.adb, line 5.
16663 @end smallexample
16664
16665 @noindent
16666 It is important to note that the stack traceback addresses
16667 do not change when debug information is included. This is particularly useful
16668 because it makes it possible to release software without debug information (to
16669 minimize object size), get a field report that includes a stack traceback
16670 whenever an internal bug occurs, and then be able to retrieve the sequence
16671 of calls with the same program compiled with debug information.
16672
16673 @node Tracebacks From Exception Occurrences (non-symbolic)
16674 @subsubsection Tracebacks From Exception Occurrences
16675
16676 @noindent
16677 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
16678 The stack traceback is attached to the exception information string, and can
16679 be retrieved in an exception handler within the Ada program, by means of the
16680 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
16681
16682 @smallexample
16683 @cartouche
16684 @group
16685 with Ada.Text_IO;
16686 with Ada.Exceptions;
16687
16688 procedure STB is
16689
16690    use Ada;
16691    use Ada.Exceptions;
16692
16693    procedure P1 is
16694       K : Positive := 1;
16695    begin
16696       K := K - 1;
16697    exception
16698       when E : others =>
16699          Text_IO.Put_Line (Exception_Information (E));
16700    end P1;
16701
16702    procedure P2 is
16703    begin
16704       P1;
16705    end P2;
16706
16707 begin
16708    P2;
16709 end STB;
16710 @end group
16711 @end cartouche
16712 @end smallexample
16713
16714 @noindent
16715 This program will output:
16716
16717 @smallexample
16718 $ stb
16719
16720 Exception name: CONSTRAINT_ERROR
16721 Message: stb.adb:12
16722 Call stack traceback locations:
16723 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
16724 @end smallexample
16725
16726 @node Tracebacks From Anywhere in a Program (non-symbolic)
16727 @subsubsection Tracebacks From Anywhere in a Program
16728
16729 @noindent
16730 It is also possible to retrieve a stack traceback from anywhere in a
16731 program. For this you need to
16732 use the @code{GNAT.Traceback} API. This package includes a procedure called
16733 @code{Call_Chain} that computes a complete stack traceback, as well as useful
16734 display procedures described below. It is not necessary to use the
16735 @code{-E gnatbind} option in this case, because the stack traceback mechanism
16736 is invoked explicitly.
16737
16738 @noindent
16739 In the following example we compute a traceback at a specific location in
16740 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
16741 convert addresses to strings:
16742
16743 @smallexample
16744 @cartouche
16745 @group
16746 with Ada.Text_IO;
16747 with GNAT.Traceback;
16748 with GNAT.Debug_Utilities;
16749
16750 procedure STB is
16751
16752    use Ada;
16753    use GNAT;
16754    use GNAT.Traceback;
16755
16756    procedure P1 is
16757       TB  : Tracebacks_Array (1 .. 10);
16758       --  We are asking for a maximum of 10 stack frames.
16759       Len : Natural;
16760       --  Len will receive the actual number of stack frames returned.
16761    begin
16762       Call_Chain (TB, Len);
16763
16764       Text_IO.Put ("In STB.P1 : ");
16765
16766       for K in 1 .. Len loop
16767          Text_IO.Put (Debug_Utilities.Image (TB (K)));
16768          Text_IO.Put (' ');
16769       end loop;
16770
16771       Text_IO.New_Line;
16772    end P1;
16773
16774    procedure P2 is
16775    begin
16776       P1;
16777    end P2;
16778
16779 begin
16780    P2;
16781 end STB;
16782 @end group
16783 @end cartouche
16784 @end smallexample
16785
16786 @smallexample
16787 $ gnatmake stb
16788 $ stb
16789
16790 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
16791 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
16792 @end smallexample
16793
16794 @node Symbolic Traceback
16795 @subsection Symbolic Traceback
16796 @cindex traceback, symbolic
16797
16798 @noindent
16799 A symbolic traceback is a stack traceback in which procedure names are
16800 associated with each code location.
16801
16802 @noindent
16803 Note that this feature is not supported on all platforms. See
16804 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
16805 list of currently supported platforms.
16806
16807 @noindent
16808 Note that the symbolic traceback requires that the program be compiled
16809 with debug information. If it is not compiled with debug information
16810 only the non-symbolic information will be valid.
16811
16812 @menu
16813 * Tracebacks From Exception Occurrences (symbolic)::
16814 * Tracebacks From Anywhere in a Program (symbolic)::
16815 @end menu
16816
16817 @node Tracebacks From Exception Occurrences (symbolic)
16818 @subsubsection Tracebacks From Exception Occurrences
16819
16820 @smallexample
16821 @cartouche
16822 @group
16823 with Ada.Text_IO;
16824 with GNAT.Traceback.Symbolic;
16825
16826 procedure STB is
16827
16828    procedure P1 is
16829    begin
16830       raise Constraint_Error;
16831    end P1;
16832
16833    procedure P2 is
16834    begin
16835       P1;
16836    end P2;
16837
16838    procedure P3 is
16839    begin
16840       P2;
16841    end P3;
16842
16843 begin
16844    P3;
16845 exception
16846    when E : others =>
16847       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
16848 end STB;
16849 @end group
16850 @end cartouche
16851 @end smallexample
16852
16853 @smallexample
16854 $ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl
16855 $ stb
16856
16857 0040149F in stb.p1 at stb.adb:8
16858 004014B7 in stb.p2 at stb.adb:13
16859 004014CF in stb.p3 at stb.adb:18
16860 004015DD in ada.stb at stb.adb:22
16861 00401461 in main at b~stb.adb:168
16862 004011C4 in __mingw_CRTStartup at crt1.c:200
16863 004011F1 in mainCRTStartup at crt1.c:222
16864 77E892A4 in ?? at ??:0
16865 @end smallexample
16866
16867 @noindent
16868 The exact sequence of linker options may vary from platform to platform.
16869 The above @code{-largs} section is for Windows platforms. By contrast,
16870 under Unix there is no need for the @code{-largs} section.
16871 Differences across platforms are due to details of linker implementation.
16872
16873 @node Tracebacks From Anywhere in a Program (symbolic)
16874 @subsubsection Tracebacks From Anywhere in a Program
16875
16876 @noindent
16877 It is possible to get a symbolic stack traceback
16878 from anywhere in a program, just as for non-symbolic tracebacks.
16879 The first step is to obtain a non-symbolic
16880 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
16881 information. Here is an example:
16882
16883 @smallexample
16884 @cartouche
16885 @group
16886 with Ada.Text_IO;
16887 with GNAT.Traceback;
16888 with GNAT.Traceback.Symbolic;
16889
16890 procedure STB is
16891
16892    use Ada;
16893    use GNAT.Traceback;
16894    use GNAT.Traceback.Symbolic;
16895
16896    procedure P1 is
16897       TB  : Tracebacks_Array (1 .. 10);
16898       --  We are asking for a maximum of 10 stack frames.
16899       Len : Natural;
16900       --  Len will receive the actual number of stack frames returned.
16901    begin
16902       Call_Chain (TB, Len);
16903       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
16904    end P1;
16905
16906    procedure P2 is
16907    begin
16908       P1;
16909    end P2;
16910
16911 begin
16912    P2;
16913 end STB;
16914 @end group
16915 @end cartouche
16916 @end smallexample
16917
16918
16919 @node Inline Assembler
16920 @chapter Inline Assembler
16921
16922 @noindent
16923 If you need to write low-level software that interacts directly with the hardware, Ada provides two ways to incorporate assembly language code into your program.  First, you can import and invoke external routines written in assembly language, an Ada feature fully supported by GNAT.  However, for small sections of code it may be simpler or more efficient to include assembly language statements directly in your Ada source program, using the facilities of the implementation-defined package @code{System.Machine_Code}, which incorporates the gcc Inline Assembler.  The Inline Assembler approach offers a number of advantages, including the following:
16924
16925 @itemize @bullet
16926 @item No need to use non-Ada tools
16927 @item Consistent interface over different targets
16928 @item Automatic usage of the proper calling conventions
16929 @item Access to Ada constants and variables
16930 @item Definition of intrinsic routines
16931 @item Possibility of inlining a subprogram comprising assembler code
16932 @item Code optimizer can take Inline Assembler code into account
16933 @end itemize
16934
16935 This chapter presents a series of examples to show you how to use the Inline Assembler.  Although it focuses on the Intel x86, the general approach applies also to other processors.  It is assumed that you are familiar with Ada and with assembly language programming.
16936
16937 @menu
16938 * Basic Assembler Syntax::
16939 * A Simple Example of Inline Assembler::
16940 * Output Variables in Inline Assembler::
16941 * Input Variables in Inline Assembler::
16942 * Inlining Inline Assembler Code::
16943 * Other Asm Functionality::
16944 * A Complete Example::
16945 @end menu
16946
16947 @c ---------------------------------------------------------------------------
16948 @node Basic Assembler Syntax
16949 @section Basic Assembler Syntax
16950
16951 @noindent
16952 The assembler used by GNAT and gcc is based not on the Intel assembly language, but rather on a
16953 language that descends from the AT&T Unix assembler @emph{as} (and which is often
16954 referred to as ``AT&T syntax'').
16955 The following table summarizes the main features of @emph{as} syntax and points out the differences from the Intel conventions.
16956 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
16957 pre-processor) documentation for further information.
16958
16959 @table @asis
16960 @item Register names
16961 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
16962 @*
16963 Intel: No extra punctuation; for example @code{eax}
16964
16965 @item Immediate operand
16966 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
16967 @*
16968 Intel: No extra punctuation; for example @code{4}
16969
16970 @item Address
16971 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
16972 @*
16973 Intel: No extra punctuation; for example @code{loc}
16974
16975 @item Memory contents
16976 gcc / @emph{as}: No extra punctuation; for example @code{loc}
16977 @*
16978 Intel: Square brackets; for example @code{[loc]}
16979
16980 @item Register contents
16981 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
16982 @*
16983 Intel: Square brackets; for example @code{[eax]}
16984
16985 @item Hexadecimal numbers
16986 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
16987 @*
16988 Intel: Trailing ``h''; for example @code{A0h}
16989
16990 @item Operand size
16991 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move a 16-bit word
16992 @*
16993 Intel: Implicit, deduced by assembler; for example @code{mov}
16994
16995 @item Instruction repetition
16996 gcc / @emph{as}: Split into two lines; for example
16997 @*
16998 @code{rep}
16999 @*
17000 @code{stosl}
17001 @*
17002 Intel: Keep on one line; for example @code{rep stosl}
17003
17004 @item Order of operands
17005 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
17006 @*
17007 Intel: Destination first; for example @code{mov eax, 4}
17008 @end table
17009
17010 @c ---------------------------------------------------------------------------
17011 @node A Simple Example of Inline Assembler
17012 @section A Simple Example of Inline Assembler
17013
17014 @noindent
17015 The following example will generate a single assembly language statement, @code{nop}, which does nothing.  Despite its lack of run-time effect, the example will be useful in illustrating the basics of the Inline Assembler facility.
17016
17017 @smallexample
17018 @group
17019 with System.Machine_Code; use System.Machine_Code;
17020 procedure Nothing is
17021 begin
17022    Asm ("nop");
17023 end Nothing;
17024 @end group
17025 @end smallexample
17026
17027 @code{Asm} is a procedure declared in package @code{System.Machine_Code}; here it takes one parameter, a @emph{template string} that must be a static expression and that will form the generated instruction.
17028 @code{Asm} may be regarded as a compile-time procedure that parses the template string and additional parameters (none here), from which it generates a sequence of assembly language instructions.
17029
17030 The examples in this chapter will illustrate several of the forms for invoking @code{Asm}; a complete specification of the syntax is found in the @cite{GNAT Reference Manual}.
17031
17032 Under the standard GNAT conventions, the @code{Nothing} procedure should be in a file named @file{nothing.adb}.  You can build the executable in the usual way:
17033 @smallexample
17034 gnatmake nothing
17035 @end smallexample
17036 However, the interesting aspect of this example is not its run-time behavior but rather the
17037 generated assembly code.  To see this output, invoke the compiler as follows:
17038 @smallexample
17039    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
17040 @end smallexample
17041 where the options are:
17042
17043 @table @code
17044 @item -c
17045 compile only (no bind or link)
17046 @item -S
17047 generate assembler listing
17048 @item -fomit-frame-pointer
17049 do not set up separate stack frames
17050 @item -gnatp
17051 do not add runtime checks
17052 @end table
17053
17054 This gives a human-readable assembler version of the code. The resulting
17055 file will have the same name as the Ada source file, but with a @code{.s} extension.
17056 In our example, the file @file{nothing.s} has the following contents:
17057
17058 @smallexample
17059 @group
17060 .file "nothing.adb"
17061 gcc2_compiled.:
17062 ___gnu_compiled_ada:
17063 .text
17064    .align 4
17065 .globl __ada_nothing
17066 __ada_nothing:
17067 #APP
17068    nop
17069 #NO_APP
17070    jmp L1
17071    .align 2,0x90
17072 L1:
17073    ret
17074 @end group
17075 @end smallexample
17076
17077 The assembly code you included is clearly indicated by
17078 the compiler, between the @code{#APP} and @code{#NO_APP}
17079 delimiters. The character before the 'APP' and 'NOAPP'
17080 can differ on different targets. For example, Linux uses '#APP' while
17081 on NT you will see '/APP'.
17082
17083 If you make a mistake in your assembler code (such as using the
17084 wrong size modifier, or using a wrong operand for the instruction) GNAT
17085 will report this error in a temporary file, which will be deleted when
17086 the compilation is finished.  Generating an assembler file will help
17087 in such cases, since you can assemble this file separately using the
17088 @emph{as} assembler that comes with gcc.
17089
17090 Assembling the file using the command
17091
17092 @smallexample
17093 as @file{nothing.s}
17094 @end smallexample
17095 @noindent
17096 will give you error messages whose lines correspond to the assembler
17097 input file, so you can easily find and correct any mistakes you made.
17098 If there are no errors, @emph{as} will generate an object file @file{nothing.out}.
17099
17100 @c ---------------------------------------------------------------------------
17101 @node Output Variables in Inline Assembler
17102 @section Output Variables in Inline Assembler
17103
17104 @noindent
17105 The examples in this section, showing how to access the processor flags, illustrate how to specify the destination operands for assembly language statements.
17106
17107 @smallexample
17108 @group
17109 with Interfaces; use Interfaces;
17110 with Ada.Text_IO; use Ada.Text_IO;
17111 with System.Machine_Code; use System.Machine_Code;
17112 procedure Get_Flags is
17113    Flags : Unsigned_32;
17114    use ASCII;
17115 begin
17116    Asm ("pushfl"          & LF & HT & -- push flags on stack
17117         "popl %%eax"      & LF & HT & -- load eax with flags
17118         "movl %%eax, %0",             -- store flags in variable
17119         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17120    Put_Line ("Flags register:" & Flags'Img);
17121 end Get_Flags;
17122 @end group
17123 @end smallexample
17124
17125 In order to have a nicely aligned assembly listing, we have separated
17126 multiple assembler statements in the Asm template string with linefeed (ASCII.LF)
17127 and horizontal tab (ASCII.HT) characters.  The resulting section of the
17128 assembly output file is:
17129
17130 @smallexample
17131 @group
17132 #APP
17133    pushfl
17134    popl %eax
17135    movl %eax, -40(%ebp)
17136 #NO_APP
17137 @end group
17138 @end smallexample
17139
17140 It would have been legal to write the Asm invocation as:
17141
17142 @smallexample
17143 Asm ("pushfl popl %%eax movl %%eax, %0")
17144 @end smallexample
17145
17146 but in the generated assembler file, this would come out as:
17147
17148 @smallexample
17149 #APP
17150    pushfl popl %eax movl %eax, -40(%ebp)
17151 #NO_APP
17152 @end smallexample
17153
17154 which is not so convenient for the human reader.
17155
17156 We use Ada comments
17157 at the end of each line to explain what the assembler instructions
17158 actually do.  This is a useful convention.
17159
17160 When writing Inline Assembler instructions, you need to precede each register and variable name with a percent sign.  Since the assembler already requires a percent sign at the beginning of a register name, you need two consecutive percent signs for such names in the Asm template string, thus @code{%%eax}.  In the generated assembly code, one of the percent signs will be stripped off.
17161
17162 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output variables: operands you later define using @code{Input} or @code{Output} parameters to @code{Asm}.
17163 An output variable is illustrated in
17164 the third statement in the Asm template string:
17165 @smallexample
17166 movl %%eax, %0
17167 @end smallexample
17168 The intent is to store the contents of the eax register in a variable that can be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not necessarily work, since the compiler might optimize by using a register to hold Flags, and the expansion of the @code{movl} instruction would not be aware of this optimization.  The solution is not to store the result directly but rather to advise the compiler to choose the correct operand form; that is the purpose of the @code{%0} output variable.
17169
17170 Information about the output variable is supplied in the @code{Outputs} parameter to @code{Asm}:
17171 @smallexample
17172 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17173 @end smallexample
17174
17175 The output is defined by the @code{Asm_Output} attribute of the target type; the general format is
17176 @smallexample
17177 Type'Asm_Output (constraint_string, variable_name)
17178 @end smallexample
17179
17180 The constraint string directs the compiler how
17181 to store/access the associated variable.  In the example
17182 @smallexample
17183 Unsigned_32'Asm_Output ("=m", Flags);
17184 @end smallexample
17185 the @code{"m"} (memory) constraint tells the compiler that the variable
17186 @code{Flags} should be stored in a memory variable, thus preventing
17187 the optimizer from keeping it in a register.  In contrast,
17188 @smallexample
17189 Unsigned_32'Asm_Output ("=r", Flags);
17190 @end smallexample
17191 uses the @code{"r"} (register) constraint, telling the compiler to
17192 store the variable in a register.
17193
17194 If the constraint is preceded by the equal character (@strong{=}), it tells the
17195 compiler that the variable will be used to store data into it.
17196
17197 In the @code{Get_Flags} example, we used the "g" (global) constraint, allowing the optimizer
17198 to choose whatever it deems best.
17199
17200 There are a fairly large number of constraints, but the ones that are most useful (for the Intel x86 processor) are the following:
17201
17202 @table @code
17203 @item =
17204 output constraint
17205 @item g
17206 global (i.e. can be stored anywhere)
17207 @item m
17208 in memory
17209 @item I
17210 a constant
17211 @item a
17212 use eax
17213 @item b
17214 use ebx
17215 @item c
17216 use ecx
17217 @item d
17218 use edx
17219 @item S
17220 use esi
17221 @item D
17222 use edi
17223 @item r
17224 use one of eax, ebx, ecx or edx
17225 @item q
17226 use one of eax, ebx, ecx, edx, esi or edi
17227 @end table
17228
17229 The full set of constraints is described in the gcc and @emph{as} documentation; note that it is possible to combine certain constraints in one constraint string.
17230
17231 You specify the association of an output variable with an assembler operand through the @code{%}@emph{n} notation, where @emph{n} is a non-negative integer.  Thus in
17232 @smallexample
17233 @group
17234 Asm ("pushfl"          & LF & HT & -- push flags on stack
17235      "popl %%eax"      & LF & HT & -- load eax with flags
17236      "movl %%eax, %0",             -- store flags in variable
17237      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17238 @end group
17239 @end smallexample
17240 @noindent
17241 @code{%0} will be replaced in the expanded code by the appropriate operand,
17242 whatever
17243 the compiler decided for the @code{Flags} variable.
17244
17245 In general, you may have any number of output variables:
17246 @itemize @bullet
17247 @item
17248 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
17249 @item
17250 Specify the @code{Outputs} parameter as a parenthesized comma-separated list of @code{Asm_Output} attributes
17251 @end itemize
17252
17253 For example:
17254 @smallexample
17255 @group
17256 Asm ("movl %%eax, %0" & LF & HT &
17257      "movl %%ebx, %1" & LF & HT &
17258      "movl %%ecx, %2",
17259      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
17260                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
17261                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
17262 @end group
17263 @end smallexample
17264 @noindent
17265 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables in the Ada program.
17266
17267 As a variation on the @code{Get_Flags} example, we can use the constraints string to direct the compiler to store the eax register into the @code{Flags} variable, instead of including the store instruction explicitly in the @code{Asm} template string:
17268
17269 @smallexample
17270 @group
17271 with Interfaces; use Interfaces;
17272 with Ada.Text_IO; use Ada.Text_IO;
17273 with System.Machine_Code; use System.Machine_Code;
17274 procedure Get_Flags_2 is
17275    Flags : Unsigned_32;
17276    use ASCII;
17277 begin
17278    Asm ("pushfl"      & LF & HT & -- push flags on stack
17279         "popl %%eax",             -- save flags in eax
17280         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
17281    Put_Line ("Flags register:" & Flags'Img);
17282 end Get_Flags_2;
17283 @end group
17284 @end smallexample
17285
17286 @noindent
17287 The @code{"a"} constraint tells the compiler that the @code{Flags}
17288 variable will come from the eax register. Here is the resulting code:
17289
17290 @smallexample
17291 @group
17292 #APP
17293    pushfl
17294    popl %eax
17295 #NO_APP
17296    movl %eax,-40(%ebp)
17297 @end group
17298 @end smallexample
17299
17300 @noindent
17301 The compiler generated the store of eax into Flags after
17302 expanding the assembler code.
17303
17304 Actually, there was no need to pop the flags into the eax register; more simply, we could just pop the flags directly into the program variable:
17305
17306 @smallexample
17307 @group
17308 with Interfaces; use Interfaces;
17309 with Ada.Text_IO; use Ada.Text_IO;
17310 with System.Machine_Code; use System.Machine_Code;
17311 procedure Get_Flags_3 is
17312    Flags : Unsigned_32;
17313    use ASCII;
17314 begin
17315    Asm ("pushfl"  & LF & HT & -- push flags on stack
17316         "pop %0",             -- save flags in Flags
17317         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17318    Put_Line ("Flags register:" & Flags'Img);
17319 end Get_Flags_3;
17320 @end group
17321 @end smallexample
17322
17323 @c ---------------------------------------------------------------------------
17324 @node Input Variables in Inline Assembler
17325 @section Input Variables in Inline Assembler
17326
17327 @noindent
17328 The example in this section illustrates how to specify the source operands for assembly language statements.  The program simply increments its input value by 1:
17329
17330 @smallexample
17331 @group
17332 with Interfaces; use Interfaces;
17333 with Ada.Text_IO; use Ada.Text_IO;
17334 with System.Machine_Code; use System.Machine_Code;
17335 procedure Increment is
17336
17337    function Incr (Value : Unsigned_32) return Unsigned_32 is
17338       Result : Unsigned_32;
17339    begin
17340       Asm ("incl %0",
17341            Inputs  => Unsigned_32'Asm_Input ("a", Value),
17342            Outputs => Unsigned_32'Asm_Output ("=a", Result));
17343       return Result;
17344    end Incr;
17345
17346    Value : Unsigned_32;
17347
17348 begin
17349    Value := 5;
17350    Put_Line ("Value before is" & Value'Img);
17351    Value := Incr (Value);
17352    Put_Line ("Value after is" & Value'Img);
17353 end Increment;
17354 @end group
17355 @end smallexample
17356
17357 The @code{Outputs} parameter to @code{Asm} specifies
17358 that the result will be in the eax register and that it is to be stored in the @code{Result}
17359 variable.
17360
17361 The @code{Inputs} parameter looks much like the @code{Outputs} parameter, but with an
17362 @code{Asm_Input} attribute. The
17363 @code{"="} constraint, indicating an output value, is not present.
17364
17365 You can have multiple input variables, in the same way that you can have more
17366 than one output variable.
17367
17368 The parameter count (%0, %1) etc, now starts at the first input
17369 statement, and continues with the output statements.
17370 When both parameters use the same variable, the
17371 compiler will treat them as the same %n operand, which is the case here.
17372
17373 Just as the @code{Outputs} parameter causes the register to be stored into the
17374 target variable after execution of the assembler statements, so does the
17375 @code{Inputs} parameter cause its variable to be loaded into the register before execution
17376 of the
17377 assembler statements.
17378
17379 Thus the effect of the @code{Asm} invocation is:
17380 @enumerate
17381 @item load the 32-bit value of @code{Value} into eax
17382 @item execute the @code{incl %eax} instruction
17383 @item store the contents of eax into the @code{Result} variable
17384 @end enumerate
17385
17386 The resulting assembler file (with @code{-O2} optimization) contains:
17387 @smallexample
17388 @group
17389 _increment__incr.1:
17390    subl $4,%esp
17391    movl 8(%esp),%eax
17392 #APP
17393    incl %eax
17394 #NO_APP
17395    movl %eax,%edx
17396    movl %ecx,(%esp)
17397    addl $4,%esp
17398    ret
17399 @end group
17400 @end smallexample
17401
17402 @c ---------------------------------------------------------------------------
17403 @node Inlining Inline Assembler Code
17404 @section Inlining Inline Assembler Code
17405
17406 @noindent
17407 For a short subprogram such as the @code{Incr} function in the previous section, the overhead of the call and return (creating / deleting the stack frame)
17408 can be significant, compared to the amount of code in the subprogram body.
17409 A solution is to apply Ada's @code{Inline} pragma to the subprogram,
17410 which directs the compiler to expand invocations of the subprogram at the point(s)
17411 of call, instead of setting up a stack frame for out-of-line calls.
17412 Here is the resulting program:
17413
17414 @smallexample
17415 @group
17416 with Interfaces; use Interfaces;
17417 with Ada.Text_IO; use Ada.Text_IO;
17418 with System.Machine_Code; use System.Machine_Code;
17419 procedure Increment_2 is
17420
17421    function Incr (Value : Unsigned_32) return Unsigned_32 is
17422       Result : Unsigned_32;
17423    begin
17424       Asm ("incl %0",
17425            Inputs  => Unsigned_32'Asm_Input ("a", Value),
17426            Outputs => Unsigned_32'Asm_Output ("=a", Result));
17427       return Result;
17428    end Incr;
17429    pragma Inline (Increment);
17430
17431    Value : Unsigned_32;
17432
17433 begin
17434    Value := 5;
17435    Put_Line ("Value before is" & Value'Img);
17436    Value := Increment (Value);
17437    Put_Line ("Value after is" & Value'Img);
17438 end Increment_2;
17439 @end group
17440 @end smallexample
17441
17442 Compile the program with both optimization (@code{-O2}) and inlining
17443 enabled (@option{-gnatpn} instead of @option{-gnatp}).
17444
17445 The @code{Incr} function is still compiled as usual, but at the
17446 point in @code{Increment} where our function used to be called:
17447
17448 @smallexample
17449 @group
17450 pushl %edi
17451 call _increment__incr.1
17452 @end group
17453 @end smallexample
17454
17455 @noindent
17456 the code for the function body directly appears:
17457
17458 @smallexample
17459 @group
17460 movl %esi,%eax
17461 #APP
17462    incl %eax
17463 #NO_APP
17464    movl %eax,%edx
17465 @end group
17466 @end smallexample
17467
17468 @noindent
17469 thus saving the overhead of stack frame setup and an out-of-line call.
17470
17471 @c ---------------------------------------------------------------------------
17472 @node Other Asm Functionality
17473 @section Other @code{Asm} Functionality
17474
17475 @noindent
17476 This section describes two important parameters to the @code{Asm} procedure: @code{Clobber}, which identifies register usage; and @code{Volatile}, which inhibits unwanted optimizations.
17477
17478 @menu
17479 * The Clobber Parameter::
17480 * The Volatile Parameter::
17481 @end menu
17482
17483 @c ---------------------------------------------------------------------------
17484 @node The Clobber Parameter
17485 @subsection The @code{Clobber} Parameter
17486
17487 @noindent
17488 One of the dangers of intermixing assembly language and a compiled language such as Ada is
17489 that the compiler needs to be aware of which registers are being used by the assembly code.
17490 In some cases, such as the earlier examples, the constraint string is sufficient to
17491 indicate register usage (e.g. "a" for the eax register).  But more generally, the
17492 compiler needs an explicit identification of the registers that are used by the Inline
17493 Assembly statements.
17494
17495 Using a register that the compiler doesn't know about
17496 could be a side effect of an instruction (like @code{mull}
17497 storing its result in both eax and edx).
17498 It can also arise from explicit register usage in your
17499 assembly code; for example:
17500 @smallexample
17501 @group
17502 Asm ("movl %0, %%ebx" & LF & HT &
17503      "movl %%ebx, %1",
17504      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
17505      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
17506 @end group
17507 @end smallexample
17508 @noindent
17509 where the compiler (since it does not analyze the @code{Asm} template string)
17510 does not know you are using the ebx register.
17511
17512 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
17513 to identify the registers that will be used by your assembly code:
17514
17515 @smallexample
17516 @group
17517 Asm ("movl %0, %%ebx" & LF & HT &
17518      "movl %%ebx, %1",
17519      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
17520      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
17521      Clobber => "ebx");
17522 @end group
17523 @end smallexample
17524
17525 The Clobber parameter is a static string expression specifying the
17526 register(s) you are using.  Note that register names are @emph{not} prefixed by a percent sign.
17527 Also, if more than one register is used then their names are separated by commas; e.g., @code{"eax, ebx"}
17528
17529 The @code{Clobber} parameter has several additional uses:
17530 @enumerate
17531 @item Use the "register" name @code{cc} to indicate that flags might have changed
17532 @item Use the "register" name @code{memory} if you changed a memory location
17533 @end enumerate
17534
17535 @c ---------------------------------------------------------------------------
17536 @node The Volatile Parameter
17537 @subsection The @code{Volatile} Parameter
17538 @cindex Volatile parameter
17539
17540 @noindent
17541 Compiler optimizations in the presence of Inline Assembler may sometimes have unwanted effects.
17542 For example, when
17543 an @code{Asm} invocation with an input variable is inside a loop, the compiler might move
17544 the loading of the input variable outside the loop, regarding it as a
17545 one-time initialization.
17546
17547 If this effect is not desired, you can disable such optimizations by setting the
17548 @code{Volatile} parameter to @code{True}; for example:
17549
17550 @smallexample
17551 @group
17552 Asm ("movl %0, %%ebx" & LF & HT &
17553      "movl %%ebx, %1",
17554      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
17555      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
17556      Clobber  => "ebx",
17557      Volatile => True);
17558 @end group
17559 @end smallexample
17560
17561 By default, @code{Volatile} is set to @code{False} unless there is no @code{Outputs}
17562 parameter.
17563
17564 Although setting @code{Volatile} to @code{True} prevents unwanted optimizations,
17565 it will also disable other optimizations that might be important for efficiency.
17566 In general, you should set @code{Volatile} to @code{True} only if the compiler's
17567 optimizations have created problems.
17568
17569 @c ---------------------------------------------------------------------------
17570 @node A Complete Example
17571 @section A Complete Example
17572
17573 @noindent
17574 This section contains a complete program illustrating a realistic usage of GNAT's Inline Assembler
17575 capabilities.  It comprises a main procedure @code{Check_CPU} and a package @code{Intel_CPU}.
17576 The package declares a collection of functions that detect the properties of the 32-bit
17577 x86 processor that is running the program.  The main procedure invokes these functions
17578 and displays the information.
17579
17580 The Intel_CPU package could be enhanced by adding functions to
17581 detect the type of x386 co-processor, the processor caching options and
17582 special operations such as the SIMD extensions.
17583
17584 Although the Intel_CPU package has been written for 32-bit Intel
17585 compatible CPUs, it is OS neutral. It has been tested on DOS,
17586 Windows/NT and Linux.
17587
17588 @menu
17589 * Check_CPU Procedure::
17590 * Intel_CPU Package Specification::
17591 * Intel_CPU Package Body::
17592 @end menu
17593
17594 @c ---------------------------------------------------------------------------
17595 @node Check_CPU Procedure
17596 @subsection @code{Check_CPU} Procedure
17597 @cindex Check_CPU procedure
17598
17599 @smallexample
17600 ---------------------------------------------------------------------
17601 --                                                                 --
17602 --  Uses the Intel_CPU package to identify the CPU the program is  --
17603 --  running on, and some of the features it supports.              --
17604 --                                                                 --
17605 ---------------------------------------------------------------------
17606
17607 with Intel_CPU;                     --  Intel CPU detection functions
17608 with Ada.Text_IO;                   --  Standard text I/O
17609 with Ada.Command_Line;              --  To set the exit status
17610
17611 procedure Check_CPU is
17612
17613    Type_Found : Boolean := False;
17614    --  Flag to indicate that processor was identified
17615
17616    Features   : Intel_CPU.Processor_Features;
17617    --  The processor features
17618
17619    Signature  : Intel_CPU.Processor_Signature;
17620    --  The processor type signature
17621
17622 begin
17623
17624    -----------------------------------
17625    --  Display the program banner.  --
17626    -----------------------------------
17627
17628    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
17629                          ": check Intel CPU version and features, v1.0");
17630    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
17631    Ada.Text_IO.New_Line;
17632
17633    -----------------------------------------------------------------------
17634    --  We can safely start with the assumption that we are on at least  --
17635    --  a x386 processor. If the CPUID instruction is present, then we   --
17636    --  have a later processor type.                                     --
17637    -----------------------------------------------------------------------
17638
17639    if Intel_CPU.Has_CPUID = False then
17640
17641       --  No CPUID instruction, so we assume this is indeed a x386
17642       --  processor. We can still check if it has a FP co-processor.
17643       if Intel_CPU.Has_FPU then
17644          Ada.Text_IO.Put_Line
17645            ("x386-type processor with a FP co-processor");
17646       else
17647          Ada.Text_IO.Put_Line
17648            ("x386-type processor without a FP co-processor");
17649       end if;  --  check for FPU
17650
17651       --  Program done
17652       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17653       return;
17654
17655    end if;  --  check for CPUID
17656
17657    -----------------------------------------------------------------------
17658    --  If CPUID is supported, check if this is a true Intel processor,  --
17659    --  if it is not, display a warning.                                 --
17660    -----------------------------------------------------------------------
17661
17662    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
17663       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
17664       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
17665    end if;  --  check if Intel
17666
17667    ----------------------------------------------------------------------
17668    --  With the CPUID instruction present, we can assume at least a    --
17669    --  x486 processor. If the CPUID support level is < 1 then we have  --
17670    --  to leave it at that.                                            --
17671    ----------------------------------------------------------------------
17672
17673    if Intel_CPU.CPUID_Level < 1 then
17674
17675       --  Ok, this is a x486 processor. we still can get the Vendor ID
17676       Ada.Text_IO.Put_Line ("x486-type processor");
17677       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
17678
17679       --  We can also check if there is a FPU present
17680       if Intel_CPU.Has_FPU then
17681          Ada.Text_IO.Put_Line ("Floating-Point support");
17682       else
17683          Ada.Text_IO.Put_Line ("No Floating-Point support");
17684       end if;  --  check for FPU
17685
17686       --  Program done
17687       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17688       return;
17689
17690    end if;  --  check CPUID level
17691
17692    ---------------------------------------------------------------------
17693    --  With a CPUID level of 1 we can use the processor signature to  --
17694    --  determine it's exact type.                                     --
17695    ---------------------------------------------------------------------
17696
17697    Signature := Intel_CPU.Signature;
17698
17699    ----------------------------------------------------------------------
17700    --  Ok, now we go into a lot of messy comparisons to get the        --
17701    --  processor type. For clarity, no attememt to try to optimize the --
17702    --  comparisons has been made. Note that since Intel_CPU does not   --
17703    --  support getting cache info, we cannot distinguish between P5    --
17704    --  and Celeron types yet.                                          --
17705    ----------------------------------------------------------------------
17706
17707    --  x486SL
17708    if Signature.Processor_Type = 2#00#   and
17709      Signature.Family          = 2#0100# and
17710      Signature.Model           = 2#0100# then
17711       Type_Found := True;
17712       Ada.Text_IO.Put_Line ("x486SL processor");
17713    end if;
17714
17715    --  x486DX2 Write-Back
17716    if Signature.Processor_Type = 2#00#   and
17717      Signature.Family          = 2#0100# and
17718      Signature.Model           = 2#0111# then
17719       Type_Found := True;
17720       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
17721    end if;
17722
17723    --  x486DX4
17724    if Signature.Processor_Type = 2#00#   and
17725      Signature.Family          = 2#0100# and
17726      Signature.Model           = 2#1000# then
17727       Type_Found := True;
17728       Ada.Text_IO.Put_Line ("x486DX4 processor");
17729    end if;
17730
17731    --  x486DX4 Overdrive
17732    if Signature.Processor_Type = 2#01#   and
17733      Signature.Family          = 2#0100# and
17734      Signature.Model           = 2#1000# then
17735       Type_Found := True;
17736       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
17737    end if;
17738
17739    --  Pentium (60, 66)
17740    if Signature.Processor_Type = 2#00#   and
17741      Signature.Family          = 2#0101# and
17742      Signature.Model           = 2#0001# then
17743       Type_Found := True;
17744       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
17745    end if;
17746
17747    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
17748    if Signature.Processor_Type = 2#00#   and
17749      Signature.Family          = 2#0101# and
17750      Signature.Model           = 2#0010# then
17751       Type_Found := True;
17752       Ada.Text_IO.Put_Line
17753         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
17754    end if;
17755
17756    --  Pentium OverDrive (60, 66)
17757    if Signature.Processor_Type = 2#01#   and
17758      Signature.Family          = 2#0101# and
17759      Signature.Model           = 2#0001# then
17760       Type_Found := True;
17761       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
17762    end if;
17763
17764    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
17765    if Signature.Processor_Type = 2#01#   and
17766      Signature.Family          = 2#0101# and
17767      Signature.Model           = 2#0010# then
17768       Type_Found := True;
17769       Ada.Text_IO.Put_Line
17770         ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
17771    end if;
17772
17773    --  Pentium OverDrive processor for x486 processor-based systems
17774    if Signature.Processor_Type = 2#01#   and
17775      Signature.Family          = 2#0101# and
17776      Signature.Model           = 2#0011# then
17777       Type_Found := True;
17778       Ada.Text_IO.Put_Line
17779         ("Pentium OverDrive processor for x486 processor-based systems");
17780    end if;
17781
17782    --  Pentium processor with MMX technology (166, 200)
17783    if Signature.Processor_Type = 2#00#   and
17784      Signature.Family          = 2#0101# and
17785      Signature.Model           = 2#0100# then
17786       Type_Found := True;
17787       Ada.Text_IO.Put_Line
17788         ("Pentium processor with MMX technology (166, 200)");
17789    end if;
17790
17791    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
17792    if Signature.Processor_Type = 2#01#   and
17793      Signature.Family          = 2#0101# and
17794      Signature.Model           = 2#0100# then
17795       Type_Found := True;
17796       Ada.Text_IO.Put_Line
17797         ("Pentium OverDrive processor with MMX " &
17798          "technology for Pentium processor (75, 90, 100, 120, 133)");
17799    end if;
17800
17801    --  Pentium Pro processor
17802    if Signature.Processor_Type = 2#00#   and
17803      Signature.Family          = 2#0110# and
17804      Signature.Model           = 2#0001# then
17805       Type_Found := True;
17806       Ada.Text_IO.Put_Line ("Pentium Pro processor");
17807    end if;
17808
17809    --  Pentium II processor, model 3
17810    if Signature.Processor_Type = 2#00#   and
17811      Signature.Family          = 2#0110# and
17812      Signature.Model           = 2#0011# then
17813       Type_Found := True;
17814       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
17815    end if;
17816
17817    --  Pentium II processor, model 5 or Celeron processor
17818    if Signature.Processor_Type = 2#00#   and
17819      Signature.Family          = 2#0110# and
17820      Signature.Model           = 2#0101# then
17821       Type_Found := True;
17822       Ada.Text_IO.Put_Line
17823         ("Pentium II processor, model 5 or Celeron processor");
17824    end if;
17825
17826    --  Pentium Pro OverDrive processor
17827    if Signature.Processor_Type = 2#01#   and
17828      Signature.Family          = 2#0110# and
17829      Signature.Model           = 2#0011# then
17830       Type_Found := True;
17831       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
17832    end if;
17833
17834    --  If no type recognized, we have an unknown. Display what
17835    --  we _do_ know
17836    if Type_Found = False then
17837       Ada.Text_IO.Put_Line ("Unknown processor");
17838    end if;
17839
17840    -----------------------------------------
17841    --  Display processor stepping level.  --
17842    -----------------------------------------
17843
17844    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
17845
17846    ---------------------------------
17847    --  Display vendor ID string.  --
17848    ---------------------------------
17849
17850    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
17851
17852    ------------------------------------
17853    --  Get the processors features.  --
17854    ------------------------------------
17855
17856    Features := Intel_CPU.Features;
17857
17858    -----------------------------
17859    --  Check for a FPU unit.  --
17860    -----------------------------
17861
17862    if Features.FPU = True then
17863       Ada.Text_IO.Put_Line ("Floating-Point unit available");
17864    else
17865       Ada.Text_IO.Put_Line ("no Floating-Point unit");
17866    end if;  --  check for FPU
17867
17868    --------------------------------
17869    --  List processor features.  --
17870    --------------------------------
17871
17872    Ada.Text_IO.Put_Line ("Supported features: ");
17873
17874    --  Virtual Mode Extension
17875    if Features.VME = True then
17876       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
17877    end if;
17878
17879    --  Debugging Extension
17880    if Features.DE = True then
17881       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
17882    end if;
17883
17884    --  Page Size Extension
17885    if Features.PSE = True then
17886       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
17887    end if;
17888
17889    --  Time Stamp Counter
17890    if Features.TSC = True then
17891       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
17892    end if;
17893
17894    --  Model Specific Registers
17895    if Features.MSR = True then
17896       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
17897    end if;
17898
17899    --  Physical Address Extension
17900    if Features.PAE = True then
17901       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
17902    end if;
17903
17904    --  Machine Check Extension
17905    if Features.MCE = True then
17906       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
17907    end if;
17908
17909    --  CMPXCHG8 instruction supported
17910    if Features.CX8 = True then
17911       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
17912    end if;
17913
17914    --  on-chip APIC hardware support
17915    if Features.APIC = True then
17916       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
17917    end if;
17918
17919    --  Fast System Call
17920    if Features.SEP = True then
17921       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
17922    end if;
17923
17924    --  Memory Type Range Registers
17925    if Features.MTRR = True then
17926       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
17927    end if;
17928
17929    --  Page Global Enable
17930    if Features.PGE = True then
17931       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
17932    end if;
17933
17934    --  Machine Check Architecture
17935    if Features.MCA = True then
17936       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
17937    end if;
17938
17939    --  Conditional Move Instruction Supported
17940    if Features.CMOV = True then
17941       Ada.Text_IO.Put_Line
17942         ("    CMOV   - Conditional Move Instruction Supported");
17943    end if;
17944
17945    --  Page Attribute Table
17946    if Features.PAT = True then
17947       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
17948    end if;
17949
17950    --  36-bit Page Size Extension
17951    if Features.PSE_36 = True then
17952       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
17953    end if;
17954
17955    --  MMX technology supported
17956    if Features.MMX = True then
17957       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
17958    end if;
17959
17960    --  Fast FP Save and Restore
17961    if Features.FXSR = True then
17962       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
17963    end if;
17964
17965    ---------------------
17966    --  Program done.  --
17967    ---------------------
17968
17969    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17970
17971 exception
17972
17973    when others =>
17974       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
17975       raise;
17976
17977 end Check_CPU;
17978 @end smallexample
17979
17980 @c ---------------------------------------------------------------------------
17981 @node Intel_CPU Package Specification
17982 @subsection @code{Intel_CPU} Package Specification
17983 @cindex Intel_CPU package specification
17984
17985 @smallexample
17986 -------------------------------------------------------------------------
17987 --                                                                     --
17988 --  file: intel_cpu.ads                                                --
17989 --                                                                     --
17990 --           *********************************************             --
17991 --           * WARNING: for 32-bit Intel processors only *             --
17992 --           *********************************************             --
17993 --                                                                     --
17994 --  This package contains a number of subprograms that are useful in   --
17995 --  determining the Intel x86 CPU (and the features it supports) on    --
17996 --  which the program is running.                                      --
17997 --                                                                     --
17998 --  The package is based upon the information given in the Intel       --
17999 --  Application Note AP-485: "Intel Processor Identification and the   --
18000 --  CPUID Instruction" as of April 1998. This application note can be  --
18001 --  found on www.intel.com.                                            --
18002 --                                                                     --
18003 --  It currently deals with 32-bit processors only, will not detect    --
18004 --  features added after april 1998, and does not guarantee proper     --
18005 --  results on Intel-compatible processors.                            --
18006 --                                                                     --
18007 --  Cache info and x386 fpu type detection are not supported.          --
18008 --                                                                     --
18009 --  This package does not use any privileged instructions, so should   --
18010 --  work on any OS running on a 32-bit Intel processor.                --
18011 --                                                                     --
18012 -------------------------------------------------------------------------
18013
18014 with Interfaces;             use Interfaces;
18015 --  for using unsigned types
18016
18017 with System.Machine_Code;    use System.Machine_Code;
18018 --  for using inline assembler code
18019
18020 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
18021 --  for inserting control characters
18022
18023 package Intel_CPU is
18024
18025    ----------------------
18026    --  Processor bits  --
18027    ----------------------
18028
18029    subtype Num_Bits is Natural range 0 .. 31;
18030    --  the number of processor bits (32)
18031
18032    --------------------------
18033    --  Processor register  --
18034    --------------------------
18035
18036    --  define a processor register type for easy access to
18037    --  the individual bits
18038
18039    type Processor_Register is array (Num_Bits) of Boolean;
18040    pragma Pack (Processor_Register);
18041    for Processor_Register'Size use 32;
18042
18043    -------------------------
18044    --  Unsigned register  --
18045    -------------------------
18046
18047    --  define a processor register type for easy access to
18048    --  the individual bytes
18049
18050    type Unsigned_Register is
18051       record
18052          L1 : Unsigned_8;
18053          H1 : Unsigned_8;
18054          L2 : Unsigned_8;
18055          H2 : Unsigned_8;
18056       end record;
18057
18058    for Unsigned_Register use
18059       record
18060          L1 at 0 range  0 ..  7;
18061          H1 at 0 range  8 .. 15;
18062          L2 at 0 range 16 .. 23;
18063          H2 at 0 range 24 .. 31;
18064       end record;
18065
18066    for Unsigned_Register'Size use 32;
18067
18068    ---------------------------------
18069    --  Intel processor vendor ID  --
18070    ---------------------------------
18071
18072    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
18073    --  indicates an Intel manufactured processor
18074
18075    ------------------------------------
18076    --  Processor signature register  --
18077    ------------------------------------
18078
18079    --  a register type to hold the processor signature
18080
18081    type Processor_Signature is
18082       record
18083          Stepping       : Natural range 0 .. 15;
18084          Model          : Natural range 0 .. 15;
18085          Family         : Natural range 0 .. 15;
18086          Processor_Type : Natural range 0 .. 3;
18087          Reserved       : Natural range 0 .. 262143;
18088       end record;
18089
18090    for Processor_Signature use
18091       record
18092          Stepping       at 0 range  0 ..  3;
18093          Model          at 0 range  4 ..  7;
18094          Family         at 0 range  8 .. 11;
18095          Processor_Type at 0 range 12 .. 13;
18096          Reserved       at 0 range 14 .. 31;
18097       end record;
18098
18099    for Processor_Signature'Size use 32;
18100
18101    -----------------------------------
18102    --  Processor features register  --
18103    -----------------------------------
18104
18105    --  a processor register to hold the processor feature flags
18106
18107    type Processor_Features is
18108       record
18109          FPU    : Boolean;                --  floating point unit on chip
18110          VME    : Boolean;                --  virtual mode extension
18111          DE     : Boolean;                --  debugging extension
18112          PSE    : Boolean;                --  page size extension
18113          TSC    : Boolean;                --  time stamp counter
18114          MSR    : Boolean;                --  model specific registers
18115          PAE    : Boolean;                --  physical address extension
18116          MCE    : Boolean;                --  machine check extension
18117          CX8    : Boolean;                --  cmpxchg8 instruction
18118          APIC   : Boolean;                --  on-chip apic hardware
18119          Res_1  : Boolean;                --  reserved for extensions
18120          SEP    : Boolean;                --  fast system call
18121          MTRR   : Boolean;                --  memory type range registers
18122          PGE    : Boolean;                --  page global enable
18123          MCA    : Boolean;                --  machine check architecture
18124          CMOV   : Boolean;                --  conditional move supported
18125          PAT    : Boolean;                --  page attribute table
18126          PSE_36 : Boolean;                --  36-bit page size extension
18127          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
18128          MMX    : Boolean;                --  MMX technology supported
18129          FXSR   : Boolean;                --  fast FP save and restore
18130          Res_3  : Natural range 0 .. 127; --  reserved for extensions
18131       end record;
18132
18133    for Processor_Features use
18134       record
18135          FPU    at 0 range  0 ..  0;
18136          VME    at 0 range  1 ..  1;
18137          DE     at 0 range  2 ..  2;
18138          PSE    at 0 range  3 ..  3;
18139          TSC    at 0 range  4 ..  4;
18140          MSR    at 0 range  5 ..  5;
18141          PAE    at 0 range  6 ..  6;
18142          MCE    at 0 range  7 ..  7;
18143          CX8    at 0 range  8 ..  8;
18144          APIC   at 0 range  9 ..  9;
18145          Res_1  at 0 range 10 .. 10;
18146          SEP    at 0 range 11 .. 11;
18147          MTRR   at 0 range 12 .. 12;
18148          PGE    at 0 range 13 .. 13;
18149          MCA    at 0 range 14 .. 14;
18150          CMOV   at 0 range 15 .. 15;
18151          PAT    at 0 range 16 .. 16;
18152          PSE_36 at 0 range 17 .. 17;
18153          Res_2  at 0 range 18 .. 22;
18154          MMX    at 0 range 23 .. 23;
18155          FXSR   at 0 range 24 .. 24;
18156          Res_3  at 0 range 25 .. 31;
18157       end record;
18158
18159    for Processor_Features'Size use 32;
18160
18161    -------------------
18162    --  Subprograms  --
18163    -------------------
18164
18165    function Has_FPU return Boolean;
18166    --  return True if a FPU is found
18167    --  use only if CPUID is not supported
18168
18169    function Has_CPUID return Boolean;
18170    --  return True if the processor supports the CPUID instruction
18171
18172    function CPUID_Level return Natural;
18173    --  return the CPUID support level (0, 1 or 2)
18174    --  can only be called if the CPUID instruction is supported
18175
18176    function Vendor_ID return String;
18177    --  return the processor vendor identification string
18178    --  can only be called if the CPUID instruction is supported
18179
18180    function Signature return Processor_Signature;
18181    --  return the processor signature
18182    --  can only be called if the CPUID instruction is supported
18183
18184    function Features return Processor_Features;
18185    --  return the processors features
18186    --  can only be called if the CPUID instruction is supported
18187
18188 private
18189
18190    ------------------------
18191    --  EFLAGS bit names  --
18192    ------------------------
18193
18194    ID_Flag : constant Num_Bits := 21;
18195    --  ID flag bit
18196
18197 end Intel_CPU;
18198 @end smallexample
18199
18200 @c ---------------------------------------------------------------------------
18201 @node Intel_CPU Package Body
18202 @subsection @code{Intel_CPU} Package Body
18203 @cindex Intel_CPU package body
18204
18205 @smallexample
18206 package body Intel_CPU is
18207
18208    ---------------------------
18209    --  Detect FPU presence  --
18210    ---------------------------
18211
18212    --  There is a FPU present if we can set values to the FPU Status
18213    --  and Control Words.
18214
18215    function Has_FPU return Boolean is
18216
18217       Register : Unsigned_16;
18218       --  processor register to store a word
18219
18220    begin
18221
18222       --  check if we can change the status word
18223       Asm (
18224
18225            --  the assembler code
18226            "finit"              & LF & HT &    --  reset status word
18227            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
18228            "fnstsw %0"          & LF & HT &    --  save status word
18229            "movw %%ax, %0",                    --  store status word
18230
18231            --  output stored in Register
18232            --  register must be a memory location
18233            Outputs => Unsigned_16'Asm_output ("=m", Register),
18234
18235            --  tell compiler that we used eax
18236            Clobber => "eax");
18237
18238       --  if the status word is zero, there is no FPU
18239       if Register = 0 then
18240          return False;   --  no status word
18241       end if;  --  check status word value
18242
18243       --  check if we can get the control word
18244       Asm (
18245
18246            --  the assembler code
18247            "fnstcw %0",   --  save the control word
18248
18249            --  output into Register
18250            --  register must be a memory location
18251            Outputs => Unsigned_16'Asm_output ("=m", Register));
18252
18253       --  check the relevant bits
18254       if (Register and 16#103F#) /= 16#003F# then
18255          return False;   --  no control word
18256       end if;  --  check control word value
18257
18258       --  FPU found
18259       return True;
18260
18261    end Has_FPU;
18262
18263    --------------------------------
18264    --  Detect CPUID instruction  --
18265    --------------------------------
18266
18267    --  The processor supports the CPUID instruction if it is possible
18268    --  to change the value of ID flag bit in the EFLAGS register.
18269
18270    function Has_CPUID return Boolean is
18271
18272       Original_Flags, Modified_Flags : Processor_Register;
18273       --  EFLAG contents before and after changing the ID flag
18274
18275    begin
18276
18277       --  try flipping the ID flag in the EFLAGS register
18278       Asm (
18279
18280            --  the assembler code
18281            "pushfl"               & LF & HT &     --  push EFLAGS on stack
18282            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
18283            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
18284            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
18285            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
18286            "popfl"                & LF & HT &     --  load EFLAGS register
18287            "pushfl"               & LF & HT &     --  push EFLAGS on stack
18288            "pop %1",                              --  save EFLAGS content
18289
18290            --  output values, may be anything
18291            --  Original_Flags is %0
18292            --  Modified_Flags is %1
18293            Outputs =>
18294               (Processor_Register'Asm_output ("=g", Original_Flags),
18295                Processor_Register'Asm_output ("=g", Modified_Flags)),
18296
18297            --  tell compiler eax is destroyed
18298            Clobber => "eax");
18299
18300       --  check if CPUID is supported
18301       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
18302          return True;   --  ID flag was modified
18303       else
18304          return False;  --  ID flag unchanged
18305       end if;  --  check for CPUID
18306
18307    end Has_CPUID;
18308
18309    -------------------------------
18310    --  Get CPUID support level  --
18311    -------------------------------
18312
18313    function CPUID_Level return Natural is
18314
18315       Level : Unsigned_32;
18316       --  returned support level
18317
18318    begin
18319
18320       --  execute CPUID, storing the results in the Level register
18321       Asm (
18322
18323            --  the assembler code
18324            "cpuid",    --  execute CPUID
18325
18326            --  zero is stored in eax
18327            --  returning the support level in eax
18328            Inputs => Unsigned_32'Asm_input ("a", 0),
18329
18330            --  eax is stored in Level
18331            Outputs => Unsigned_32'Asm_output ("=a", Level),
18332
18333            --  tell compiler ebx, ecx and edx registers are destroyed
18334            Clobber => "ebx, ecx, edx");
18335
18336       --  return the support level
18337       return Natural (Level);
18338
18339    end CPUID_Level;
18340
18341    --------------------------------
18342    --  Get CPU Vendor ID String  --
18343    --------------------------------
18344
18345    --  The vendor ID string is returned in the ebx, ecx and edx register
18346    --  after executing the CPUID instruction with eax set to zero.
18347    --  In case of a true Intel processor the string returned is
18348    --  "GenuineIntel"
18349
18350    function Vendor_ID return String is
18351
18352       Ebx, Ecx, Edx : Unsigned_Register;
18353       --  registers containing the vendor ID string
18354
18355       Vendor_ID : String (1 .. 12);
18356       -- the vendor ID string
18357
18358    begin
18359
18360       --  execute CPUID, storing the results in the processor registers
18361       Asm (
18362
18363            --  the assembler code
18364            "cpuid",    --  execute CPUID
18365
18366            --  zero stored in eax
18367            --  vendor ID string returned in ebx, ecx and edx
18368            Inputs => Unsigned_32'Asm_input ("a", 0),
18369
18370            --  ebx is stored in Ebx
18371            --  ecx is stored in Ecx
18372            --  edx is stored in Edx
18373            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
18374                        Unsigned_Register'Asm_output ("=c", Ecx),
18375                        Unsigned_Register'Asm_output ("=d", Edx)));
18376
18377       --  now build the vendor ID string
18378       Vendor_ID( 1) := Character'Val (Ebx.L1);
18379       Vendor_ID( 2) := Character'Val (Ebx.H1);
18380       Vendor_ID( 3) := Character'Val (Ebx.L2);
18381       Vendor_ID( 4) := Character'Val (Ebx.H2);
18382       Vendor_ID( 5) := Character'Val (Edx.L1);
18383       Vendor_ID( 6) := Character'Val (Edx.H1);
18384       Vendor_ID( 7) := Character'Val (Edx.L2);
18385       Vendor_ID( 8) := Character'Val (Edx.H2);
18386       Vendor_ID( 9) := Character'Val (Ecx.L1);
18387       Vendor_ID(10) := Character'Val (Ecx.H1);
18388       Vendor_ID(11) := Character'Val (Ecx.L2);
18389       Vendor_ID(12) := Character'Val (Ecx.H2);
18390
18391       --  return string
18392       return Vendor_ID;
18393
18394    end Vendor_ID;
18395
18396    -------------------------------
18397    --  Get processor signature  --
18398    -------------------------------
18399
18400    function Signature return Processor_Signature is
18401
18402       Result : Processor_Signature;
18403       --  processor signature returned
18404
18405    begin
18406
18407       --  execute CPUID, storing the results in the Result variable
18408       Asm (
18409
18410            --  the assembler code
18411            "cpuid",    --  execute CPUID
18412
18413            --  one is stored in eax
18414            --  processor signature returned in eax
18415            Inputs => Unsigned_32'Asm_input ("a", 1),
18416
18417            --  eax is stored in Result
18418            Outputs => Processor_Signature'Asm_output ("=a", Result),
18419
18420            --  tell compiler that ebx, ecx and edx are also destroyed
18421            Clobber => "ebx, ecx, edx");
18422
18423       --  return processor signature
18424       return Result;
18425
18426    end Signature;
18427
18428    ------------------------------
18429    --  Get processor features  --
18430    ------------------------------
18431
18432    function Features return Processor_Features is
18433
18434       Result : Processor_Features;
18435       --  processor features returned
18436
18437    begin
18438
18439       --  execute CPUID, storing the results in the Result variable
18440       Asm (
18441
18442            --  the assembler code
18443            "cpuid",    --  execute CPUID
18444
18445            --  one stored in eax
18446            --  processor features returned in edx
18447            Inputs => Unsigned_32'Asm_input ("a", 1),
18448
18449            --  edx is stored in Result
18450            Outputs => Processor_Features'Asm_output ("=d", Result),
18451
18452            --  tell compiler that ebx and ecx are also destroyed
18453            Clobber => "ebx, ecx");
18454
18455       --  return processor signature
18456       return Result;
18457
18458    end Features;
18459
18460 end Intel_CPU;
18461 @end smallexample
18462 @c END OF INLINE ASSEMBLER CHAPTER
18463 @c ===============================
18464
18465 @node Microsoft Windows Topics
18466 @chapter Microsoft Windows Topics
18467 @cindex Windows NT
18468 @cindex Windows 95
18469 @cindex Windows 98
18470
18471 @noindent
18472 This chapter describes topics that are specific to the Microsoft Windows
18473 platforms (NT, 95 and 98).
18474
18475 @menu
18476 * Using GNAT on Windows::
18477 * GNAT Setup Tool::
18478 * CONSOLE and WINDOWS subsystems::
18479 * Temporary Files::
18480 * Mixed-Language Programming on Windows::
18481 * Windows Calling Conventions::
18482 * Introduction to Dynamic Link Libraries (DLLs)::
18483 * Using DLLs with GNAT::
18484 * Building DLLs with GNAT::
18485 * GNAT and Windows Resources::
18486 * Debugging a DLL::
18487 * GNAT and COM/DCOM Objects::
18488 @end menu
18489
18490 @node Using GNAT on Windows
18491 @section Using GNAT on Windows
18492
18493 @noindent
18494 One of the strengths of the GNAT technology is that its tool set
18495 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
18496 @code{gdb} debugger, etc.) is used in the same way regardless of the
18497 platform.
18498
18499 On Windows this tool set is complemented by a number of Microsoft-specific
18500 tools that have been provided to facilitate interoperability with Windows
18501 when this is required. With these tools:
18502
18503 @itemize @bullet
18504
18505 @item
18506 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
18507 subsystems.
18508
18509 @item
18510 You can use any Dynamically Linked Library (DLL) in your Ada code (both
18511 relocatable and non-relocatable DLLs are supported).
18512
18513 @item
18514 You can build Ada DLLs for use in other applications. These applications
18515 can be written in a language other than Ada (e.g., C, C++, etc). Again both
18516 relocatable and non-relocatable Ada DLLs are supported.
18517
18518 @item
18519 You can include Windows resources in your Ada application.
18520
18521 @item
18522 You can use or create COM/DCOM objects.
18523 @end itemize
18524
18525 @noindent
18526 Immediately below are listed all known general GNAT-for-Windows restrictions.
18527 Other restrictions about specific features like Windows Resources and DLLs
18528 are listed in separate sections below.
18529
18530 @itemize @bullet
18531
18532 @item
18533 It is not possible to use @code{GetLastError} and @code{SetLastError}
18534 when tasking, protected records, or exceptions are used. In these
18535 cases, in order to implement Ada semantics, the GNAT run-time system
18536 calls certain Win32 routines that set the last error variable to 0 upon
18537 success. It should be possible to use @code{GetLastError} and
18538 @code{SetLastError} when tasking, protected record, and exception
18539 features are not used, but it is not guaranteed to work.
18540 @end itemize
18541
18542 @node GNAT Setup Tool
18543 @section GNAT Setup Tool
18544 @cindex GNAT Setup Tool
18545 @cindex Setup Tool
18546 @cindex gnatreg
18547
18548 @menu
18549 * Command-line arguments::
18550 * Creating a network installation of GNAT::
18551 * Registering and unregistering additional libraries::
18552 @end menu
18553
18554 @noindent
18555 GNAT installation on Windows is using the Windows registry in order to
18556 locate proper executables and standard libraries. GNAT setup tool, called
18557 @code{gnatreg.exe}, is provided in order to display and modify GNAT-specific
18558 registry entries, allowing to create network GNAT installations, modify the
18559 locations of GNAT components, as well as register and unregister additional
18560 libraries for use with GNAT.
18561
18562 @node Command-line arguments
18563 @subsection Command-line arguments
18564
18565 @noindent
18566 @code{gnatreg [switches] [parameter]}
18567
18568 @noindent
18569 Specifying no arguments causes gnatreg to display current configuration.
18570
18571 @noindent
18572 The switches understood by gnatreg are:
18573 @table @asis
18574 @item  -h
18575        print the help message
18576 @item  -a
18577        add a standard library
18578 @item  -r
18579        remove a standard library
18580 @item  -f
18581        force creation of keys if they don't exist
18582 @item  -q
18583        be quiet/terse
18584 @end table
18585
18586 @node Creating a network installation of GNAT
18587 @subsection Creating a network installation of GNAT
18588
18589 @noindent
18590 Make sure the system on which GNAT is installed is accessible from the
18591 current machine.
18592
18593 Use the command
18594
18595 @code{@ @ @ gnatreg -f \\server\sharename\path}
18596
18597 in order to setup the registry entries on a current machine.
18598
18599 For example, if GNAT is installed in @file{\GNAT} directory of a share location
18600 called @file{c-drive} on a machine @file{LOKI}, the command that can be used on
18601 other machines to allow the remote use of GNAT is,
18602
18603 @code{@ @ @ gnatreg -f \\loki\c-drive\gnat}
18604
18605 Remember to also add @file{\\loki\c-drive\gnat\bin} in front of your PATH variable.
18606
18607 Be aware that every compilation using the network installation results in the
18608 transfer of large amounts of data across the network and may cause serious
18609 performance penalty.
18610
18611 @node Registering and unregistering additional libraries
18612 @subsection Registering and unregistering additional libraries
18613
18614 @noindent
18615 To register a standard library use a command:
18616
18617 @code{@ @ @ gnatreg -a <library_name>=<path>}
18618
18619 For example:
18620
18621 @code{@ @ @ gnatreg -a WIN32ADA=c:\Win32Ada}
18622
18623 The libraries registered in this manner will be treated like standard libraries
18624 by the compiler (i.e. they don't have to be specified in -I and -l switches to
18625 various GNAT tools).
18626
18627 To unregister a library, enter
18628 @code{   gnatreg -r <library_name>}
18629
18630 e.g.,
18631 @code{   gnatreg -r WIN32ADA}
18632
18633 @node CONSOLE and WINDOWS subsystems
18634 @section CONSOLE and WINDOWS subsystems
18635 @cindex CONSOLE Subsystem
18636 @cindex WINDOWS Subsystem
18637 @cindex -mwindows
18638
18639 @noindent
18640 Under Windows there is two main subsystems. The @code{CONSOLE} subsystem
18641 (which is the default subsystem) will always create a console when
18642 launching the application. This is not something desirable when the
18643 application has a Windows GUI. To get rid of this console the
18644 application must be using the @code{WINDOWS} subsystem. To do so
18645 the @code{-mwindows} linker option must be specified.
18646
18647 @smallexample
18648 $ gnatmake winprog -largs -mwindows
18649 @end smallexample
18650
18651 @node Temporary Files
18652 @section Temporary Files
18653 @cindex Temporary files
18654
18655 @noindent
18656 It is possible to control where temporary files gets created by setting
18657 the TMP environment variable. The file will be created:
18658
18659 @itemize
18660 @item Under the directory pointed to by the TMP environment variable if
18661 this directory exists.
18662
18663 @item Under c:\temp, if the TMP environment variable is not set (or not
18664 pointing to a directory) and if this directory exists.
18665
18666 @item Under the current working directory otherwise.
18667 @end itemize
18668
18669 @noindent
18670 This allows you to determine exactly where the temporary
18671 file will be created. This is particularly useful in networked
18672 environments where you may not have write access to some
18673 directories.
18674
18675 @node Mixed-Language Programming on Windows
18676 @section Mixed-Language Programming on Windows
18677
18678 @noindent
18679 Developing pure Ada applications on Windows is no different than on
18680 other GNAT-supported platforms. However, when developing or porting an
18681 application that contains a mix of Ada and C/C++, the choice of your
18682 Windows C/C++ development environment conditions your overall
18683 interoperability strategy.
18684
18685 If you use @code{gcc} to compile the non-Ada part of your application,
18686 there are no Windows-specific restrictions that affect the overall
18687 interoperability with your Ada code. If you plan to use
18688 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
18689 the following limitations:
18690
18691 @itemize @bullet
18692 @item
18693 You cannot link your Ada code with an object or library generated with
18694 Microsoft tools if these use the @code{.tls} section (Thread Local
18695 Storage section) since the GNAT linker does not yet support this section.
18696
18697 @item
18698 You cannot link your Ada code with an object or library generated with
18699 Microsoft tools if these use I/O routines other than those provided in
18700 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
18701 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
18702 libraries can cause a conflict with @code{msvcrt.dll} services. For
18703 instance Visual C++ I/O stream routines conflict with those in
18704 @code{msvcrt.dll}.
18705 @end itemize
18706
18707 @noindent
18708 If you do want to use the Microsoft tools for your non-Ada code and hit one
18709 of the above limitations, you have two choices:
18710
18711 @enumerate
18712 @item
18713 Encapsulate your non Ada code in a DLL to be linked with your Ada
18714 application. In this case, use the Microsoft or whatever environment to
18715 build the DLL and use GNAT to build your executable
18716 (@pxref{Using DLLs with GNAT}).
18717
18718 @item
18719 Or you can encapsulate your Ada code in a DLL to be linked with the
18720 other part of your application. In this case, use GNAT to build the DLL
18721 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
18722 environment to build your executable.
18723 @end enumerate
18724
18725 @node Windows Calling Conventions
18726 @section Windows Calling Conventions
18727 @findex Stdcall
18728 @findex APIENTRY
18729
18730 @menu
18731 * C Calling Convention::
18732 * Stdcall Calling Convention::
18733 * DLL Calling Convention::
18734 @end menu
18735
18736 @noindent
18737 When a subprogram @code{F} (caller) calls a subprogram @code{G}
18738 (callee), there are several ways to push @code{G}'s parameters on the
18739 stack and there are several possible scenarios to clean up the stack
18740 upon @code{G}'s return. A calling convention is an agreed upon software
18741 protocol whereby the responsibilities between the caller (@code{F}) and
18742 the callee (@code{G}) are clearly defined. Several calling conventions
18743 are available for Windows:
18744
18745 @itemize @bullet
18746 @item
18747 @code{C} (Microsoft defined)
18748
18749 @item
18750 @code{Stdcall} (Microsoft defined)
18751
18752 @item
18753 @code{DLL} (GNAT specific)
18754 @end itemize
18755
18756 @node C Calling Convention
18757 @subsection @code{C} Calling Convention
18758
18759 @noindent
18760 This is the default calling convention used when interfacing to C/C++
18761 routines compiled with either @code{gcc} or Microsoft Visual C++.
18762
18763 In the @code{C} calling convention subprogram parameters are pushed on the
18764 stack by the caller from right to left. The caller itself is in charge of
18765 cleaning up the stack after the call. In addition, the name of a routine
18766 with @code{C} calling convention is mangled by adding a leading underscore.
18767
18768 The name to use on the Ada side when importing (or exporting) a routine
18769 with @code{C} calling convention is the name of the routine. For
18770 instance the C function:
18771
18772 @smallexample
18773 int get_val (long);
18774 @end smallexample
18775
18776 @noindent
18777 should be imported from Ada as follows:
18778
18779 @smallexample
18780 @group
18781 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
18782 @b{pragma} Import (C, Get_Val, External_Name => "get_val");
18783 @end group
18784 @end smallexample
18785
18786 @noindent
18787 Note that in this particular case the @code{External_Name} parameter could
18788 have been omitted since, when missing, this parameter is taken to be the
18789 name of the Ada entity in lower case. When the @code{Link_Name} parameter
18790 is missing, as in the above example, this parameter is set to be the
18791 @code{External_Name} with a leading underscore.
18792
18793 When importing a variable defined in C, you should always use the @code{C}
18794 calling convention unless the object containing the variable is part of a
18795 DLL (in which case you should use the @code{DLL} calling convention,
18796 @pxref{DLL Calling Convention}).
18797
18798 @node Stdcall Calling Convention
18799 @subsection @code{Stdcall} Calling Convention
18800
18801 @noindent
18802 This convention, which was the calling convention used for Pascal
18803 programs, is used by Microsoft for all the routines in the Win32 API for
18804 efficiency reasons. It must be used to import any routine for which this
18805 convention was specified.
18806
18807 In the @code{Stdcall} calling convention subprogram parameters are pushed
18808 on the stack by the caller from right to left. The callee (and not the
18809 caller) is in charge of cleaning the stack on routine exit. In addition,
18810 the name of a routine with @code{Stdcall} calling convention is mangled by
18811 adding a leading underscore (as for the @code{C} calling convention) and a
18812 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
18813 bytes) of the parameters passed to the routine.
18814
18815 The name to use on the Ada side when importing a C routine with a
18816 @code{Stdcall} calling convention is the name of the C routine. The leading
18817 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
18818 the compiler. For instance the Win32 function:
18819
18820 @smallexample
18821 @b{APIENTRY} int get_val (long);
18822 @end smallexample
18823
18824 @noindent
18825 should be imported from Ada as follows:
18826
18827 @smallexample
18828 @group
18829 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
18830 @b{pragma} Import (Stdcall, Get_Val);
18831 --  @i{On the x86 a long is 4 bytes, so the Link_Name is }"_get_val@@4"
18832 @end group
18833 @end smallexample
18834
18835 @noindent
18836 As for the @code{C} calling convention, when the @code{External_Name}
18837 parameter is missing, it is taken to be the name of the Ada entity in lower
18838 case. If instead of writing the above import pragma you write:
18839
18840 @smallexample
18841 @group
18842 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
18843 @b{pragma} Import (Stdcall, Get_Val, External_Name => "retrieve_val");
18844 @end group
18845 @end smallexample
18846
18847 @noindent
18848 then the imported routine is @code{_retrieve_val@@4}. However, if instead
18849 of specifying the @code{External_Name} parameter you specify the
18850 @code{Link_Name} as in the following example:
18851
18852 @smallexample
18853 @group
18854 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
18855 @b{pragma} Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
18856 @end group
18857 @end smallexample
18858
18859 @noindent
18860 then the imported routine is @code{retrieve_val@@4}, that is, there is no
18861 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
18862 added at the end of the @code{Link_Name} by the compiler.
18863
18864 @noindent
18865 Note, that in some special cases a DLL's entry point name lacks a trailing
18866 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
18867 The @code{gnatdll} tool, which creates the import library for the DLL, is able
18868 to handle those cases (see the description of the switches in
18869 @pxref{Using gnatdll} section).
18870
18871 @node DLL Calling Convention
18872 @subsection @code{DLL} Calling Convention
18873
18874 @noindent
18875 This convention, which is GNAT-specific, must be used when you want to
18876 import in Ada a variables defined in a DLL. For functions and procedures
18877 this convention is equivalent to the @code{Stdcall} convention. As an
18878 example, if a DLL contains a variable defined as:
18879
18880 @smallexample
18881 int my_var;
18882 @end smallexample
18883
18884 @noindent
18885 then, to access this variable from Ada you should write:
18886
18887 @smallexample
18888 @group
18889 My_Var : Interfaces.C.int;
18890 @b{pragma} Import (DLL, My_Var);
18891 @end group
18892 @end smallexample
18893
18894 The remarks concerning the @code{External_Name} and @code{Link_Name}
18895 parameters given in the previous sections equally apply to the @code{DLL}
18896 calling convention.
18897
18898 @node Introduction to Dynamic Link Libraries (DLLs)
18899 @section Introduction to Dynamic Link Libraries (DLLs)
18900 @findex DLL
18901
18902 @noindent
18903 A Dynamically Linked Library (DLL) is a library that can be shared by
18904 several applications running under Windows. A DLL can contain any number of
18905 routines and variables.
18906
18907 One advantage of DLLs is that you can change and enhance them without
18908 forcing all the applications that depend on them to be relinked or
18909 recompiled. However, you should be aware than all calls to DLL routines are
18910 slower since, as you will understand below, such calls are indirect.
18911
18912 To illustrate the remainder of this section, suppose that an application
18913 wants to use the services of a DLL @file{API.dll}. To use the services
18914 provided by @file{API.dll} you must statically link against an import
18915 library which contains a jump table with an entry for each routine and
18916 variable exported by the DLL. In the Microsoft world this import library is
18917 called @file{API.lib}. When using GNAT this import library is called either
18918 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
18919
18920 After you have statically linked your application with the import library
18921 and you run your application, here is what happens:
18922
18923 @enumerate
18924 @item
18925 Your application is loaded into memory.
18926
18927 @item
18928 The DLL @file{API.dll} is mapped into the address space of your
18929 application. This means that:
18930
18931 @itemize @bullet
18932 @item
18933 The DLL will use the stack of the calling thread.
18934
18935 @item
18936 The DLL will use the virtual address space of the calling process.
18937
18938 @item
18939 The DLL will allocate memory from the virtual address space of the calling
18940 process.
18941
18942 @item
18943 Handles (pointers) can be safely exchanged between routines in the DLL
18944 routines and routines in the application using the DLL.
18945 @end itemize
18946
18947 @item
18948 The entries in the @file{libAPI.a} or @file{API.lib} jump table which is
18949 part of your application are initialized with the addresses of the routines
18950 and variables in @file{API.dll}.
18951
18952 @item
18953 If present in @file{API.dll}, routines @code{DllMain} or
18954 @code{DllMainCRTStartup} are invoked. These routines typically contain
18955 the initialization code needed for the well-being of the routines and
18956 variables exported by the DLL.
18957 @end enumerate
18958
18959 @noindent
18960 There is an additional point which is worth mentioning. In the Windows
18961 world there are two kind of DLLs: relocatable and non-relocatable
18962 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
18963 in the target application address space. If the addresses of two
18964 non-relocatable DLLs overlap and these happen to be used by the same
18965 application, a conflict will occur and the application will run
18966 incorrectly. Hence, when possible, it is always preferable to use and
18967 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
18968 supported by GNAT.
18969
18970 As a side note, an interesting difference between Microsoft DLLs and
18971 Unix shared libraries, is the fact that on most Unix systems all public
18972 routines are exported by default in a Unix shared library, while under
18973 Windows the exported routines must be listed explicitly in a definition
18974 file (@pxref{The Definition File}).
18975
18976 @node Using DLLs with GNAT
18977 @section Using DLLs with GNAT
18978
18979 @menu
18980 * Creating an Ada Spec for the DLL Services::
18981 * Creating an Import Library::
18982 @end menu
18983
18984 @noindent
18985 To use the services of a DLL, say @file{API.dll}, in your Ada application
18986 you must have:
18987
18988 @enumerate
18989 @item
18990 The Ada spec for the routines and/or variables you want to access in
18991 @file{API.dll}. If not available this Ada spec must be built from the C/C++
18992 header files provided with the DLL.
18993
18994 @item
18995 The import library (@file{libAPI.a} or @file{API.lib}). As previously
18996 mentioned an import library is a statically linked library containing the
18997 import table which will be filled at load time to point to the actual
18998 @file{API.dll} routines. Sometimes you don't have an import library for the
18999 DLL you want to use. The following sections will explain how to build one.
19000
19001 @item
19002 The actual DLL, @file{API.dll}.
19003 @end enumerate
19004
19005 @noindent
19006 Once you have all the above, to compile an Ada application that uses the
19007 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
19008 you simply issue the command
19009
19010 @smallexample
19011 $ gnatmake my_ada_app -largs -lAPI
19012 @end smallexample
19013
19014 @noindent
19015 The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
19016 tells the GNAT linker to look first for a library named @file{API.lib}
19017 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
19018 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
19019 contains the following pragma
19020
19021 @smallexample
19022 @b{pragma} Linker_Options ("-lAPI");
19023 @end smallexample
19024
19025 @noindent
19026 you do not have to add @code{-largs -lAPI} at the end of the @code{gnatmake}
19027 command.
19028
19029 If any one of the items above is missing you will have to create it
19030 yourself. The following sections explain how to do so using as an
19031 example a fictitious DLL called @file{API.dll}.
19032
19033 @node Creating an Ada Spec for the DLL Services
19034 @subsection Creating an Ada Spec for the DLL Services
19035
19036 @noindent
19037 A DLL typically comes with a C/C++ header file which provides the
19038 definitions of the routines and variables exported by the DLL. The Ada
19039 equivalent of this header file is a package spec that contains definitions
19040 for the imported entities. If the DLL you intend to use does not come with
19041 an Ada spec you have to generate one such spec yourself. For example if
19042 the header file of @file{API.dll} is a file @file{api.h} containing the
19043 following two definitions:
19044
19045 @smallexample
19046 @group
19047 @cartouche
19048 int some_var;
19049 int get (char *);
19050 @end cartouche
19051 @end group
19052 @end smallexample
19053
19054 @noindent
19055 then the equivalent Ada spec could be:
19056
19057 @smallexample
19058 @group
19059 @cartouche
19060 @b{with} Interfaces.C.Strings;
19061 @b{package} API @b{is}
19062    @b{use} Interfaces;
19063
19064    Some_Var : C.int;
19065    @b{function} Get (Str : C.Strings.Chars_Ptr) @b{return} C.int;
19066
19067 @b{private}
19068    @b{pragma} Import (C, Get);
19069    @b{pragma} Import (DLL, Some_Var);
19070 @b{end} API;
19071 @end cartouche
19072 @end group
19073 @end smallexample
19074
19075 @noindent
19076 Note that a variable is @strong{always imported with a DLL convention}. A
19077 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
19078 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
19079 (@pxref{Windows Calling Conventions}).
19080
19081 @node Creating an Import Library
19082 @subsection Creating an Import Library
19083 @cindex Import library
19084
19085 @menu
19086 * The Definition File::
19087 * GNAT-Style Import Library::
19088 * Microsoft-Style Import Library::
19089 @end menu
19090
19091 @noindent
19092 If a Microsoft-style import library @file{API.lib} or a GNAT-style
19093 import library @file{libAPI.a} is available with @file{API.dll} you
19094 can skip this section. Otherwise read on.
19095
19096 @node The Definition File
19097 @subsubsection The Definition File
19098 @cindex Definition file
19099 @findex .def
19100
19101 @noindent
19102 As previously mentioned, and unlike Unix systems, the list of symbols
19103 that are exported from a DLL must be provided explicitly in Windows.
19104 The main goal of a definition file is precisely that: list the symbols
19105 exported by a DLL. A definition file (usually a file with a @code{.def}
19106 suffix) has the following structure:
19107
19108 @smallexample
19109 @group
19110 @cartouche
19111 [LIBRARY @i{name}]
19112 [DESCRIPTION @i{string}]
19113 EXPORTS
19114    @i{symbol1}
19115    @i{symbol2}
19116    ...
19117 @end cartouche
19118 @end group
19119 @end smallexample
19120
19121 @table @code
19122 @item LIBRARY @i{name}
19123 This section, which is optional, gives the name of the DLL.
19124
19125 @item DESCRIPTION @i{string}
19126 This section, which is optional, gives a description string that will be
19127 embedded in the import library.
19128
19129 @item EXPORTS
19130 This section gives the list of exported symbols (procedures, functions or
19131 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
19132 section of @file{API.def} looks like:
19133
19134 @smallexample
19135 @group
19136 @cartouche
19137 EXPORTS
19138    some_var
19139    get
19140 @end cartouche
19141 @end group
19142 @end smallexample
19143 @end table
19144
19145 @noindent
19146 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
19147 (@pxref{Windows Calling Conventions}) for a Stdcall
19148 calling convention function in the exported symbols list.
19149
19150 @noindent
19151 There can actually be other sections in a definition file, but these
19152 sections are not relevant to the discussion at hand.
19153
19154 @node GNAT-Style Import Library
19155 @subsubsection GNAT-Style Import Library
19156
19157 @noindent
19158 To create a static import library from @file{API.dll} with the GNAT tools
19159 you should proceed as follows:
19160
19161 @enumerate
19162 @item
19163 Create the definition file @file{API.def} (@pxref{The Definition File}).
19164 For that use the @code{dll2def} tool as follows:
19165
19166 @smallexample
19167 $ dll2def API.dll > API.def
19168 @end smallexample
19169
19170 @noindent
19171 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
19172 to standard output the list of entry points in the DLL. Note that if
19173 some routines in the DLL have the @code{Stdcall} convention
19174 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
19175 suffix then you'll have to edit @file{api.def} to add it.
19176
19177 @noindent
19178 Here are some hints to find the right @code{@@}@i{nn} suffix.
19179
19180 @enumerate
19181 @item
19182 If you have the Microsoft import library (.lib), it is possible to get
19183 the right symbols by using Microsoft @code{dumpbin} tool (see the
19184 corresponding Microsoft documentation for further details).
19185
19186 @smallexample
19187 $ dumpbin /exports api.lib
19188 @end smallexample
19189
19190 @item
19191 If you have a message about a missing symbol at link time the compiler
19192 tells you what symbol is expected. You just have to go back to the
19193 definition file and add the right suffix.
19194 @end enumerate
19195
19196 @item
19197 Build the import library @code{libAPI.a}, using @code{gnatdll}
19198 (@pxref{Using gnatdll}) as follows:
19199
19200 @smallexample
19201 $ gnatdll -e API.def -d API.dll
19202 @end smallexample
19203
19204 @noindent
19205 @code{gnatdll} takes as input a definition file @file{API.def} and the
19206 name of the DLL containing the services listed in the definition file
19207 @file{API.dll}. The name of the static import library generated is
19208 computed from the name of the definition file as follows: if the
19209 definition file name is @i{xyz}@code{.def}, the import library name will
19210 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
19211 @code{-e} could have been removed because the name of the definition
19212 file (before the "@code{.def}" suffix) is the same as the name of the
19213 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
19214 @end enumerate
19215
19216 @node Microsoft-Style Import Library
19217 @subsubsection Microsoft-Style Import Library
19218
19219 @noindent
19220 With GNAT you can either use a GNAT-style or Microsoft-style import
19221 library. A Microsoft import library is needed only if you plan to make an
19222 Ada DLL available to applications developed with Microsoft
19223 tools (@pxref{Mixed-Language Programming on Windows}).
19224
19225 To create a Microsoft-style import library for @file{API.dll} you
19226 should proceed as follows:
19227
19228 @enumerate
19229 @item
19230 Create the definition file @file{API.def} from the DLL. For this use either
19231 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
19232 tool (see the corresponding Microsoft documentation for further details).
19233
19234 @item
19235 Build the actual import library using Microsoft's @code{lib} utility:
19236
19237 @smallexample
19238 $ lib -machine:IX86 -def:API.def -out:API.lib
19239 @end smallexample
19240
19241 @noindent
19242 If you use the above command the definition file @file{API.def} must
19243 contain a line giving the name of the DLL:
19244
19245 @smallexample
19246 LIBRARY      "API"
19247 @end smallexample
19248
19249 @noindent
19250 See the Microsoft documentation for further details about the usage of
19251 @code{lib}.
19252 @end enumerate
19253
19254 @node Building DLLs with GNAT
19255 @section Building DLLs with GNAT
19256 @cindex DLLs, building
19257
19258 @menu
19259 * Limitations When Using Ada DLLs from Ada::
19260 * Exporting Ada Entities::
19261 * Ada DLLs and Elaboration::
19262 * Ada DLLs and Finalization::
19263 * Creating a Spec for Ada DLLs::
19264 * Creating the Definition File::
19265 * Using gnatdll::
19266 @end menu
19267
19268 @noindent
19269 This section explains how to build DLLs containing Ada code. These DLLs
19270 will be referred to as Ada DLLs in the remainder of this section.
19271
19272 The steps required to build an Ada DLL that is to be used by Ada as well as
19273 non-Ada applications are as follows:
19274
19275 @enumerate
19276 @item
19277 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
19278 @code{Stdcall} calling convention to avoid any Ada name mangling for the
19279 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
19280 skip this step if you plan to use the Ada DLL only from Ada applications.
19281
19282 @item
19283 Your Ada code must export an initialization routine which calls the routine
19284 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
19285 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
19286 routine exported by the Ada DLL must be invoked by the clients of the DLL
19287 to initialize the DLL.
19288
19289 @item
19290 When useful, the DLL should also export a finalization routine which calls
19291 routine @code{adafinal} generated by @code{gnatbind} to perform the
19292 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
19293 The finalization routine exported by the Ada DLL must be invoked by the
19294 clients of the DLL when the DLL services are no further needed.
19295
19296 @item
19297 You must provide a spec for the services exported by the Ada DLL in each
19298 of the programming languages to which you plan to make the DLL available.
19299
19300 @item
19301 You must provide a definition file listing the exported entities
19302 (@pxref{The Definition File}).
19303
19304 @item
19305 Finally you must use @code{gnatdll} to produce the DLL and the import
19306 library (@pxref{Using gnatdll}).
19307 @end enumerate
19308
19309 @node Limitations When Using Ada DLLs from Ada
19310 @subsection Limitations When Using Ada DLLs from Ada
19311
19312 @noindent
19313 When using Ada DLLs from Ada applications there is a limitation users
19314 should be aware of. Because on Windows the GNAT run time is not in a DLL of
19315 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
19316 each Ada DLL includes the services of the GNAT run time that are necessary
19317 to the Ada code inside the DLL. As a result, when an Ada program uses an
19318 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
19319 one in the main program.
19320
19321 It is therefore not possible to exchange GNAT run-time objects between the
19322 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
19323 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
19324 types, etc.
19325
19326 It is completely safe to exchange plain elementary, array or record types,
19327 Windows object handles, etc.
19328
19329 @node Exporting Ada Entities
19330 @subsection Exporting Ada Entities
19331 @cindex Export table
19332
19333 @noindent
19334 Building a DLL is a way to encapsulate a set of services usable from any
19335 application. As a result, the Ada entities exported by a DLL should be
19336 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
19337 any Ada name mangling. Please note that the @code{Stdcall} convention
19338 should only be used for subprograms, not for variables. As an example here
19339 is an Ada package @code{API}, spec and body, exporting two procedures, a
19340 function, and a variable:
19341
19342 @smallexample
19343 @group
19344 @cartouche
19345 @b{with} Interfaces.C; @b{use} Interfaces;
19346 @b{package} API @b{is}
19347    Count : C.int := 0;
19348    @b{function} Factorial (Val : C.int) @b{return} C.int;
19349
19350    @b{procedure} Initialize_API;
19351    @b{procedure} Finalize_API;
19352    --  @i{Initialization & Finalization routines. More in the next section.}
19353 @b{private}
19354    @b{pragma} Export (C, Initialize_API);
19355    @b{pragma} Export (C, Finalize_API);
19356    @b{pragma} Export (C, Count);
19357    @b{pragma} Export (C, Factorial);
19358 @b{end} API;
19359 @end cartouche
19360 @end group
19361 @end smallexample
19362
19363 @smallexample
19364 @group
19365 @cartouche
19366 @b{package body} API @b{is}
19367    @b{function} Factorial (Val : C.int) @b{return} C.int @b{is}
19368       Fact : C.int := 1;
19369    @b{begin}
19370       Count := Count + 1;
19371       @b{for} K @b{in} 1 .. Val @b{loop}
19372          Fact := Fact * K;
19373       @b{end loop};
19374       @b{return} Fact;
19375    @b{end} Factorial;
19376
19377    @b{procedure} Initialize_API @b{is}
19378       @b{procedure} Adainit;
19379       @b{pragma} Import (C, Adainit);
19380    @b{begin}
19381       Adainit;
19382    @b{end} Initialize_API;
19383
19384    @b{procedure} Finalize_API @b{is}
19385       @b{procedure} Adafinal;
19386       @b{pragma} Import (C, Adafinal);
19387    @b{begin}
19388       Adafinal;
19389    @b{end} Finalize_API;
19390 @b{end} API;
19391 @end cartouche
19392 @end group
19393 @end smallexample
19394
19395 @noindent
19396 If the Ada DLL you are building will only be used by Ada applications
19397 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
19398 convention. As an example, the previous package could be written as
19399 follows:
19400
19401 @smallexample
19402 @group
19403 @cartouche
19404 @b{package} API @b{is}
19405    Count : Integer := 0;
19406    @b{function} Factorial (Val : Integer) @b{return} Integer;
19407
19408    @b{procedure} Initialize_API;
19409    @b{procedure} Finalize_API;
19410    --  @i{Initialization and Finalization routines.}
19411 @b{end} API;
19412 @end cartouche
19413 @end group
19414 @end smallexample
19415
19416 @smallexample
19417 @group
19418 @cartouche
19419 @b{package body} API @b{is}
19420    @b{function} Factorial (Val : Integer) @b{return} Integer @b{is}
19421       Fact : Integer := 1;
19422    @b{begin}
19423       Count := Count + 1;
19424       @b{for} K @b{in} 1 .. Val @b{loop}
19425          Fact := Fact * K;
19426       @b{end loop};
19427       @b{return} Fact;
19428       @b{end} Factorial;
19429
19430    ...
19431    --  @i{The remainder of this package body is unchanged.}
19432 @b{end} API;
19433 @end cartouche
19434 @end group
19435 @end smallexample
19436
19437 @noindent
19438 Note that if you do not export the Ada entities with a @code{C} or
19439 @code{Stdcall} convention you will have to provide the mangled Ada names
19440 in the definition file of the Ada DLL
19441 (@pxref{Creating the Definition File}).
19442
19443 @node Ada DLLs and Elaboration
19444 @subsection Ada DLLs and Elaboration
19445 @cindex DLLs and elaboration
19446
19447 @noindent
19448 The DLL that you are building contains your Ada code as well as all the
19449 routines in the Ada library that are needed by it. The first thing a
19450 user of your DLL must do is elaborate the Ada code
19451 (@pxref{Elaboration Order Handling in GNAT}).
19452
19453 To achieve this you must export an initialization routine
19454 (@code{Initialize_API} in the previous example), which must be invoked
19455 before using any of the DLL services. This elaboration routine must call
19456 the Ada elaboration routine @code{adainit} generated by the GNAT binder
19457 (@pxref{Binding with Non-Ada Main Programs}). See the body of
19458 @code{Initialize_Api} for an example. Note that the GNAT binder is
19459 automatically invoked during the DLL build process by the @code{gnatdll}
19460 tool (@pxref{Using gnatdll}).
19461
19462 When a DLL is loaded, Windows systematically invokes a routine called
19463 @code{DllMain}. It would therefore be possible to call @code{adainit}
19464 directly from @code{DllMain} without having to provide an explicit
19465 initialization routine. Unfortunately, it is not possible to call
19466 @code{adainit} from the @code{DllMain} if your program has library level
19467 tasks because access to the @code{DllMain} entry point is serialized by
19468 the system (that is, only a single thread can execute "through" it at a
19469 time), which means that the GNAT run time will deadlock waiting for the
19470 newly created task to complete its initialization.
19471
19472 @node Ada DLLs and Finalization
19473 @subsection Ada DLLs and Finalization
19474 @cindex DLLs and finalization
19475
19476 @noindent
19477 When the services of an Ada DLL are no longer needed, the client code should
19478 invoke the DLL finalization routine, if available. The DLL finalization
19479 routine is in charge of releasing all resources acquired by the DLL. In the
19480 case of the Ada code contained in the DLL, this is achieved by calling
19481 routine @code{adafinal} generated by the GNAT binder
19482 (@pxref{Binding with Non-Ada Main Programs}).
19483 See the body of @code{Finalize_Api} for an
19484 example. As already pointed out the GNAT binder is automatically invoked
19485 during the DLL build process by the @code{gnatdll} tool
19486 (@pxref{Using gnatdll}).
19487
19488 @code{-g}
19489 @cindex @code{-g} (@code{gnatdll})
19490 @*
19491 Generate debugging information. This information is stored in the object
19492 file and copied from there to the final DLL file by the linker,
19493 where it can be read by the debugger. You must use the
19494 @code{-g} switch if you plan on using the debugger or the symbolic
19495 stack traceback.
19496
19497 @node Creating a Spec for Ada DLLs
19498 @subsection Creating a Spec for Ada DLLs
19499
19500 @noindent
19501 To use the services exported by the Ada DLL from another programming
19502 language (e.g. C), you have to translate the specs of the exported Ada
19503 entities in that language. For instance in the case of @code{API.dll},
19504 the corresponding C header file could look like:
19505
19506 @smallexample
19507 @group
19508 @cartouche
19509 extern int *__imp__count;
19510 #define count (*__imp__count)
19511 int factorial (int);
19512 @end cartouche
19513 @end group
19514 @end smallexample
19515
19516 @noindent
19517 It is important to understand that when building an Ada DLL to be used by
19518 other Ada applications, you need two different specs for the packages
19519 contained in the DLL: one for building the DLL and the other for using
19520 the DLL. This is because the @code{DLL} calling convention is needed to
19521 use a variable defined in a DLL, but when building the DLL, the variable
19522 must have either the @code{Ada} or @code{C} calling convention. As an
19523 example consider a DLL comprising the following package @code{API}:
19524
19525 @smallexample
19526 @group
19527 @cartouche
19528 @b{package} API @b{is}
19529    Count : Integer := 0;
19530    ...
19531    --  @i{Remainder of the package omitted.}
19532 @b{end} API;
19533 @end cartouche
19534 @end group
19535 @end smallexample
19536
19537 @noindent
19538 After producing a DLL containing package @code{API}, the spec that
19539 must be used to import @code{API.Count} from Ada code outside of the
19540 DLL is:
19541
19542 @smallexample
19543 @group
19544 @cartouche
19545 @b{package} API @b{is}
19546    Count : Integer;
19547    @b{pragma} Import (DLL, Count);
19548 @b{end} API;
19549 @end cartouche
19550 @end group
19551 @end smallexample
19552
19553 @node Creating the Definition File
19554 @subsection Creating the Definition File
19555
19556 @noindent
19557 The definition file is the last file needed to build the DLL. It lists
19558 the exported symbols. As an example, the definition file for a DLL
19559 containing only package @code{API} (where all the entities are exported
19560 with a @code{C} calling convention) is:
19561
19562 @smallexample
19563 @group
19564 @cartouche
19565 EXPORTS
19566     count
19567     factorial
19568     finalize_api
19569     initialize_api
19570 @end cartouche
19571 @end group
19572 @end smallexample
19573
19574 @noindent
19575 If the @code{C} calling convention is missing from package @code{API},
19576 then the definition file contains the mangled Ada names of the above
19577 entities, which in this case are:
19578
19579 @smallexample
19580 @group
19581 @cartouche
19582 EXPORTS
19583     api__count
19584     api__factorial
19585     api__finalize_api
19586     api__initialize_api
19587 @end cartouche
19588 @end group
19589 @end smallexample
19590
19591 @node Using gnatdll
19592 @subsection Using @code{gnatdll}
19593 @findex gnatdll
19594
19595 @menu
19596 * gnatdll Example::
19597 * gnatdll behind the Scenes::
19598 * Using dlltool::
19599 @end menu
19600
19601 @noindent
19602 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
19603 and non-Ada sources that make up your DLL have been compiled.
19604 @code{gnatdll} is actually in charge of two distinct tasks: build the
19605 static import library for the DLL and the actual DLL. The form of the
19606 @code{gnatdll} command is
19607
19608 @smallexample
19609 @cartouche
19610 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
19611 @end cartouche
19612 @end smallexample
19613
19614 @noindent
19615 where @i{list-of-files} is a list of ALI and object files. The object
19616 file list must be the exact list of objects corresponding to the non-Ada
19617 sources whose services are to be included in the DLL. The ALI file list
19618 must be the exact list of ALI files for the corresponding Ada sources
19619 whose services are to be included in the DLL. If @i{list-of-files} is
19620 missing, only the static import library is generated.
19621
19622 @noindent
19623 You may specify any of the following switches to @code{gnatdll}:
19624
19625 @table @code
19626 @item -a[@var{address}]
19627 @cindex @code{-a} (@code{gnatdll})
19628 Build a non-relocatable DLL at @var{address}. If @var{address} is not
19629 specified the default address @var{0x11000000} will be used. By default,
19630 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
19631 advise the reader to build relocatable DLL.
19632
19633 @item -b @var{address}
19634 @cindex @code{-b} (@code{gnatdll})
19635 Set the relocatable DLL base address. By default the address is
19636 @var{0x11000000}.
19637
19638 @item -d @var{dllfile}
19639 @cindex @code{-d} (@code{gnatdll})
19640 @var{dllfile} is the name of the DLL. This switch must be present for
19641 @code{gnatdll} to do anything. The name of the generated import library is
19642 obtained algorithmically from @var{dllfile} as shown in the following
19643 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
19644 @code{libxyz.a}. The name of the definition file to use (if not specified
19645 by option @code{-e}) is obtained algorithmically from @var{dllfile} as shown in
19646 the following example: if @var{dllfile} is @code{xyz.dll}, the definition
19647 file used is @code{xyz.def}.
19648
19649 @item -e @var{deffile}
19650 @cindex @code{-e} (@code{gnatdll})
19651 @var{deffile} is the name of the definition file.
19652
19653 @item -h
19654 @cindex @code{-h} (@code{gnatdll})
19655 Help mode. Displays @code{gnatdll} switch usage information.
19656
19657 @item -Idir
19658 Direct @code{gnatdll} to search the @var{dir} directory for source and
19659 object files needed to build the DLL.
19660 (@pxref{Search Paths and the Run-Time Library (RTL)}).
19661
19662 @item -k
19663 Removes the @code{@@}@i{nn} suffix from the import library's exported
19664 names. You must specified this option if you want to use a
19665 @code{Stdcall} function in a DLL for which the @code{@@}@i{nn} suffix
19666 has been removed. This is the case for most of the Windows NT DLL for
19667 example. This option has no effect when @code{-n} option is specified.
19668
19669 @item -l @var{file}
19670 @cindex @code{-l} (@code{gnatdll})
19671 The list of ALI and object files used to build the DLL are listed in
19672 @var{file}, instead of being given in the command line. Each line in
19673 @var{file} contains the name of an ALI or object file.
19674
19675 @item -n
19676 @cindex @code{-n} (@code{gnatdll})
19677 No Import. Do not create the import library.
19678
19679 @item -q
19680 @cindex @code{-q} (@code{gnatdll})
19681 Quiet mode. Do not display unnecessary messages.
19682
19683 @item -v
19684 @cindex @code{-v} (@code{gnatdll})
19685 Verbose mode. Display extra information.
19686
19687 @item -largs @var{opts}
19688 @cindex @code{-largs} (@code{gnatdll})
19689 Linker options. Pass @var{opts} to the linker.
19690 @end table
19691
19692 @node gnatdll Example
19693 @subsubsection @code{gnatdll} Example
19694
19695 @noindent
19696 As an example the command to build a relocatable DLL from @file{api.adb}
19697 once @file{api.adb} has been compiled and @file{api.def} created is
19698
19699 @smallexample
19700 $ gnatdll -d api.dll api.ali
19701 @end smallexample
19702
19703 @noindent
19704 The above command creates two files: @file{libapi.a} (the import
19705 library) and @file{api.dll} (the actual DLL). If you want to create
19706 only the DLL, just type:
19707
19708 @smallexample
19709 $ gnatdll -d api.dll -n api.ali
19710 @end smallexample
19711
19712 @noindent
19713 Alternatively if you want to create just the import library, type:
19714
19715 @smallexample
19716 $ gnatdll -d api.dll
19717 @end smallexample
19718
19719 @node gnatdll behind the Scenes
19720 @subsubsection @code{gnatdll} behind the Scenes
19721
19722 @noindent
19723 This section details the steps involved in creating a DLL. @code{gnatdll}
19724 does these steps for you. Unless you are interested in understanding what
19725 goes on behind the scenes, you should skip this section.
19726
19727 We use the previous example of a DLL containing the Ada package @code{API},
19728 to illustrate the steps necessary to build a DLL. The starting point is a
19729 set of objects that will make up the DLL and the corresponding ALI
19730 files. In the case of this example this means that @file{api.o} and
19731 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
19732 the following:
19733
19734 @enumerate
19735 @item
19736 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
19737 the information necessary to generate relocation information for the
19738 DLL.
19739
19740 @smallexample
19741 @group
19742 $ gnatbind -n api
19743 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
19744 @end group
19745 @end smallexample
19746
19747 @noindent
19748 In addition to the base file, the @code{gnatlink} command generates an
19749 output file @file{api.jnk} which can be discarded. The @code{-mdll} switch
19750 asks @code{gnatlink} to generate the routines @code{DllMain} and
19751 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
19752 is loaded into memory.
19753
19754 @item
19755 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
19756 export table (@file{api.exp}). The export table contains the relocation
19757 information in a form which can be used during the final link to ensure
19758 that the Windows loader is able to place the DLL anywhere in memory.
19759
19760 @smallexample
19761 @group
19762 $ dlltool --dllname api.dll --def api.def --base-file api.base \
19763           --output-exp api.exp
19764 @end group
19765 @end smallexample
19766
19767 @item
19768 @code{gnatdll} builds the base file using the new export table. Note that
19769 @code{gnatbind} must be called once again since the binder generated file
19770 has been deleted during the previous call to @code{gnatlink}.
19771
19772 @smallexample
19773 @group
19774 $ gnatbind -n api
19775 $ gnatlink api -o api.jnk api.exp -mdll
19776       -Wl,--base-file,api.base
19777 @end group
19778 @end smallexample
19779
19780 @item
19781 @code{gnatdll} builds the new export table using the new base file and
19782 generates the DLL import library @file{libAPI.a}.
19783
19784 @smallexample
19785 @group
19786 $ dlltool --dllname api.dll --def api.def --base-file api.base \
19787           --output-exp api.exp --output-lib libAPI.a
19788 @end group
19789 @end smallexample
19790
19791 @item
19792 Finally @code{gnatdll} builds the relocatable DLL using the final export
19793 table.
19794
19795 @smallexample
19796 @group
19797 $ gnatbind -n api
19798 $ gnatlink api api.exp -o api.dll -mdll
19799 @end group
19800 @end smallexample
19801 @end enumerate
19802
19803 @node Using dlltool
19804 @subsubsection Using @code{dlltool}
19805
19806 @noindent
19807 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
19808 DLLs and static import libraries. This section summarizes the most
19809 common @code{dlltool} switches. The form of the @code{dlltool} command
19810 is
19811
19812 @smallexample
19813 $ dlltool [@var{switches}]
19814 @end smallexample
19815
19816 @noindent
19817 @code{dlltool} switches include:
19818
19819 @table @code
19820 @item --base-file @var{basefile}
19821 Read the base file @var{basefile} generated by the linker. This switch
19822 is used to create a relocatable DLL.
19823
19824 @item --def @var{deffile}
19825 Read the definition file.
19826
19827 @item --dllname @var{name}
19828 Gives the name of the DLL. This switch is used to embed the name of the
19829 DLL in the static import library generated by @code{dlltool} with switch
19830 @code{--output-lib}.
19831
19832 @item -k
19833 Kill @code{@@}@i{nn} from exported names
19834 (@pxref{Windows Calling Conventions}
19835 for a discussion about @code{Stdcall}-style symbols.
19836
19837 @item --help
19838 Prints the @code{dlltool} switches with a concise description.
19839
19840 @item --output-exp @var{exportfile}
19841 Generate an export file @var{exportfile}. The export file contains the
19842 export table (list of symbols in the DLL) and is used to create the DLL.
19843
19844 @item --output-lib @i{libfile}
19845 Generate a static import library @var{libfile}.
19846
19847 @item -v
19848 Verbose mode.
19849
19850 @item --as @i{assembler-name}
19851 Use @i{assembler-name} as the assembler. The default is @code{as}.
19852 @end table
19853
19854 @node GNAT and Windows Resources
19855 @section GNAT and Windows Resources
19856 @cindex Resources, windows
19857
19858 @menu
19859 * Building Resources::
19860 * Compiling Resources::
19861 * Using Resources::
19862 * Limitations::
19863 @end menu
19864
19865 @noindent
19866 Resources are an easy way to add Windows specific objects to your
19867 application. The objects that can be added as resources include:
19868
19869 @itemize @bullet
19870 @item
19871 menus
19872
19873 @item
19874 accelerators
19875
19876 @item
19877 dialog boxes
19878
19879 @item
19880 string tables
19881
19882 @item
19883 bitmaps
19884
19885 @item
19886 cursors
19887
19888 @item
19889 icons
19890
19891 @item
19892 fonts
19893 @end itemize
19894
19895 @noindent
19896 This section explains how to build, compile and use resources.
19897
19898 @node Building Resources
19899 @subsection Building Resources
19900 @cindex Resources, building
19901
19902 @noindent
19903 A resource file is an ASCII file. By convention resource files have an
19904 @file{.rc} extension.
19905 The easiest way to build a resource file is to use Microsoft tools
19906 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
19907 @code{dlgedit.exe} to build dialogs.
19908 It is always possible to build an @file{.rc} file yourself by writing a
19909 resource script.
19910
19911 It is not our objective to explain how to write a resource file. A
19912 complete description of the resource script language can be found in the
19913 Microsoft documentation.
19914
19915 @node Compiling Resources
19916 @subsection Compiling Resources
19917 @findex rc
19918 @findex rcl
19919 @findex res2coff
19920 @cindex Resources, compiling
19921
19922 @noindent
19923 This section describes how to build a GNAT-compatible (COFF) object file
19924 containing the resources. This is done using the Resource Compiler
19925 @code{rcl} as follows:
19926
19927 @smallexample
19928 $ rcl -i myres.rc -o myres.o
19929 @end smallexample
19930
19931 @noindent
19932 By default @code{rcl} will run @code{gcc} to preprocess the @file{.rc}
19933 file. You can specify an alternate preprocessor (usually named
19934 @file{cpp.exe}) using the @code{rcl} @code{-cpp} parameter. A list of
19935 all possible options may be obtained by entering the command @code{rcl}
19936 with no parameters.
19937
19938 It is also possible to use the Microsoft resource compiler @code{rc.exe}
19939 to produce a @file{.res} file (binary resource file). See the
19940 corresponding Microsoft documentation for further details. In this case
19941 you need to use @code{res2coff} to translate the @file{.res} file to a
19942 GNAT-compatible object file as follows:
19943
19944 @smallexample
19945 $ res2coff -i myres.res -o myres.o
19946 @end smallexample
19947
19948 @node Using Resources
19949 @subsection Using Resources
19950 @cindex Resources, using
19951
19952 @noindent
19953 To include the resource file in your program just add the
19954 GNAT-compatible object file for the resource(s) to the linker
19955 arguments. With @code{gnatmake} this is done by using the @code{-largs}
19956 option:
19957
19958 @smallexample
19959 $ gnatmake myprog -largs myres.o
19960 @end smallexample
19961
19962 @node Limitations
19963 @subsection Limitations
19964 @cindex Resources, limitations
19965
19966 @noindent
19967 In this section we describe the current limitations together with
19968 suggestions for workarounds.
19969
19970 @itemize @bullet
19971 @item
19972 @code{rcl} does not handle the @code{RCINCLUDE} directive.
19973 @*
19974 Workaround: replace @code{RCINCLUDE} by an @code{#include} directive.
19975
19976 @item
19977 @code{rcl} does not handle the brackets as block delimiters.
19978 @*
19979 Workaround: replace character '@{' by @code{BEGIN} and '@}' by
19980 @code{END}. Note that Microsoft's @code{rc} handles both forms of block
19981 delimiters.
19982
19983 @item
19984 @code{rcl} does not handle @code{TypeLib} resources. This type of
19985 resource is used to build COM, DCOM or ActiveX objects.
19986 @*
19987 Workaround: use @code{rc}, the Microsoft resource compiler.
19988
19989 @item
19990 It is not possible to use @code{strip} to remove the debugging symbols
19991 from a program with resources.
19992 @*
19993 Workaround: use linker option @code{-s} to strip debugging symbols from
19994 the final executable.
19995 @end itemize
19996
19997 @node Debugging a DLL
19998 @section Debugging a DLL
19999 @cindex DLL debugging
20000
20001 @menu
20002 * The Program and the DLL Are Built with GCC/GNAT::
20003 * The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT::
20004 @end menu
20005
20006 @noindent
20007 Debugging a DLL is similar to debugging a standard program. But
20008 we have to deal with two different executable parts: the DLL and the
20009 program that uses it. We have the following four possibilities:
20010
20011 @enumerate 1
20012 @item
20013 The program and the DLL are built with @code{GCC/GNAT}.
20014 @item
20015 The program is built with foreign tools and the DLL is built with
20016 @code{GCC/GNAT}.
20017 @item
20018 The program is built with @code{GCC/GNAT} and the DLL is built with
20019 foreign tools.
20020 @item
20021 @end enumerate
20022
20023 @noindent
20024 In this section we address only cases one and two above.
20025 There is no point in trying to debug
20026 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
20027 information in it. To do so you must use a debugger compatible with the
20028 tools suite used to build the DLL.
20029
20030 @node The Program and the DLL Are Built with GCC/GNAT
20031 @subsection The Program and the DLL Are Built with GCC/GNAT
20032
20033 @noindent
20034 This is the simplest case. Both the DLL and the program have @code{GDB}
20035 compatible debugging information. It is then possible to break anywhere in
20036 the process. Let's suppose here that the main procedure is named
20037 @code{ada_main} and that in the DLL there is an entry point named
20038 @code{ada_dll}.
20039
20040 @noindent
20041 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
20042 program must have been built with the debugging information (see GNAT -g
20043 switch). Here are the step-by-step instructions for debugging it:
20044
20045 @enumerate 1
20046 @item Launch @code{GDB} on the main program.
20047
20048 @smallexample
20049 $ gdb -nw ada_main
20050 @end smallexample
20051
20052 @item Break on the main procedure and run the program.
20053
20054 @smallexample
20055 (gdb) break ada_main
20056 (gdb) run
20057 @end smallexample
20058
20059 @noindent
20060 This step is required to be able to set a breakpoint inside the DLL. As long
20061 as the program is not run, the DLL is not loaded. This has the
20062 consequence that the DLL debugging information is also not loaded, so it is not
20063 possible to set a breakpoint in the DLL.
20064
20065 @item Set a breakpoint inside the DLL
20066
20067 @smallexample
20068 (gdb) break ada_dll
20069 (gdb) run
20070 @end smallexample
20071
20072 @end enumerate
20073
20074 @noindent
20075 At this stage a breakpoint is set inside the DLL. From there on
20076 you can use the standard approach to debug the whole program
20077 (@pxref{Running and Debugging Ada Programs}).
20078
20079 @node The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT
20080 @subsection The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT
20081
20082 @menu
20083 * Debugging the DLL Directly::
20084 * Attaching to a Running Process::
20085 @end menu
20086
20087 @noindent
20088 In this case things are slightly more complex because it is not possible to
20089 start the main program and then break at the beginning to load the DLL and the
20090 associated DLL debugging information. It is not possible to break at the
20091 beginning of the program because there is no @code{GDB} debugging information,
20092 and therefore there is no direct way of getting initial control. This
20093 section addresses this issue by describing some methods that can be used
20094 to break somewhere in the DLL to debug it.
20095
20096 @noindent
20097 First suppose that the main procedure is named @code{main} (this is for
20098 example some C code built with Microsoft Visual C) and that there is a
20099 DLL named @code{test.dll} containing an Ada entry point named
20100 @code{ada_dll}.
20101
20102 @noindent
20103 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
20104 been built with debugging information (see GNAT -g option).
20105
20106 @node Debugging the DLL Directly
20107 @subsubsection Debugging the DLL Directly
20108
20109 @enumerate 1
20110 @item
20111 Launch the debugger on the DLL.
20112
20113 @smallexample
20114 $ gdb -nw test.dll
20115 @end smallexample
20116
20117 @item Set a breakpoint on a DLL subroutine.
20118
20119 @smallexample
20120 (gdb) break ada_dll
20121 @end smallexample
20122
20123 @item
20124 Specify the executable file to @code{GDB}.
20125
20126 @smallexample
20127 (gdb) exec-file main.exe
20128 @end smallexample
20129
20130 @item
20131 Run the program.
20132
20133 @smallexample
20134 (gdb) run
20135 @end smallexample
20136
20137 @noindent
20138 This will run the program until it reaches the breakpoint that has been
20139 set. From that point you can use the standard way to debug a program
20140 as described in (@pxref{Running and Debugging Ada Programs}).
20141
20142 @end enumerate
20143
20144 @noindent
20145 It is also possible to debug the DLL by attaching to a running process.
20146
20147 @node Attaching to a Running Process
20148 @subsubsection Attaching to a Running Process
20149 @cindex DLL debugging, attach to process
20150
20151 @noindent
20152 With @code{GDB} it is always possible to debug a running process by
20153 attaching to it. It is possible to debug a DLL this way. The limitation
20154 of this approach is that the DLL must run long enough to perform the
20155 attach operation. It may be useful for instance to insert a time wasting
20156 loop in the code of the DLL to meet this criterion.
20157
20158 @enumerate 1
20159
20160 @item Launch the main program @file{main.exe}.
20161
20162 @smallexample
20163 $ main
20164 @end smallexample
20165
20166 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
20167 that the process PID for @file{main.exe} is 208.
20168
20169 @item Launch gdb.
20170
20171 @smallexample
20172 $ gdb -nw
20173 @end smallexample
20174
20175 @item Attach to the running process to be debugged.
20176
20177 @smallexample
20178 (gdb) attach 208
20179 @end smallexample
20180
20181 @item Load the process debugging information.
20182
20183 @smallexample
20184 (gdb) symbol-file main.exe
20185 @end smallexample
20186
20187 @item Break somewhere in the DLL.
20188
20189 @smallexample
20190 (gdb) break ada_dll
20191 @end smallexample
20192
20193 @item Continue process execution.
20194
20195 @smallexample
20196 (gdb) continue
20197 @end smallexample
20198
20199 @end enumerate
20200
20201 @noindent
20202 This last step will resume the process execution, and stop at
20203 the breakpoint we have set. From there you can use the standard
20204 approach to debug a program as described in
20205 (@pxref{Running and Debugging Ada Programs}).
20206
20207 @node GNAT and COM/DCOM Objects
20208 @section GNAT and COM/DCOM Objects
20209 @findex COM
20210 @findex DCOM
20211
20212 @noindent
20213 This section is temporarily left blank.
20214
20215 @ignore
20216 @reread
20217 ???????????? WE NEED TO DECIDE WHETHER TO DISTRIBUTE IT ??????????????????????
20218
20219 @node gnatreg : Registry Tool for NT
20220 @section @code{gnatreg} : Registry Tool for NT
20221 @findex gnatreg
20222 @cindex Registry
20223
20224 @menu
20225 * Changing the GNAT compiler to Use::
20226 * Adding/Changing a Library Path::
20227 * Removing a Library Path::
20228 * List Current Configuration::
20229 @end menu
20230
20231 @noindent
20232 This tool can be used to switch from one compiler to another and to manage
20233 the list of directories where GNAT must look to find packages. It is
20234 also a convenient way to do network installation of GNAT.
20235
20236 The form of the @code{gnatreg} command is
20237
20238 @smallexample
20239 $ gnatreg [@var{-hqcarf}] parameter
20240 @end smallexample
20241
20242 @noindent
20243 Commons options are
20244
20245 @table @code
20246
20247 @item -h
20248 print a usage message.
20249
20250 @item -q
20251 quiet/terse - display nothing, just do the job.
20252
20253 @item -f
20254 force mode - create the registry keys if they do not
20255 exist. @code{gnatreg} will exit with an error if this option is omitted
20256 and some registry keys are not setup correctly.
20257
20258 @end table
20259
20260 @subsection Changing the GNAT compiler to use
20261
20262 @smallexample
20263 $ gnatreg c:\gnatpro
20264 @end smallexample
20265
20266 @noindent
20267 This will setup the registry to use the GNAT compiler that has been
20268 installed under c:\gnatpro. @code{gnatreg} check that this directory contain
20269 effectively a GNAT compiler. If you want to setup a network installation
20270 and if GNAT has never been installed on this computer you'll have to use
20271 the -f option.
20272
20273 @subsection Adding/Changing a library path
20274
20275 @smallexample
20276 $ gnatreg -a COMPNT=c:\ada\components
20277 @end smallexample
20278
20279 @noindent
20280 Add the directory c:\ada\components to the list of standards libraries. When
20281 running gnatmake the option -Ic:\ada\components is added automatically to the
20282 command line.
20283
20284 The directory c:\ada\components is associated with the name COMPNT. This
20285 name will be used to remove the library path.
20286
20287 @subsection Removing a library path
20288
20289 @smallexample
20290 $ gnatreg -r COMPNT
20291 @end smallexample
20292
20293 @noindent
20294 Remove the library path named COMPNT.
20295
20296 @subsection List current configuration
20297
20298 @smallexample
20299 $ gnatreg -c
20300 @end smallexample
20301
20302 @noindent
20303 @code{gnatreg} will display the GNAT and AdaGIDE path used and
20304 all the standards libraries and their associated names that have been set.
20305
20306 @end ignore
20307
20308
20309
20310 @node Performance Considerations
20311 @chapter Performance Considerations
20312 @cindex Performance
20313
20314 @noindent
20315 The GNAT system provides a number of options that allow a trade-off
20316 between
20317
20318 @itemize @bullet
20319 @item
20320 performance of the generated code
20321
20322 @item
20323 speed of compilation
20324
20325 @item
20326 minimization of dependences and recompilation
20327
20328 @item
20329 the degree of run-time checking.
20330 @end itemize
20331
20332 @noindent
20333 The defaults (if no options are selected) aim at improving the speed
20334 of compilation and minimizing dependences, at the expense of performance
20335 of the generated code:
20336
20337 @itemize @bullet
20338 @item
20339 no optimization
20340
20341 @item
20342 no inlining of subprogram calls
20343
20344 @item
20345 all run-time checks enabled except overflow and elaboration checks
20346 @end itemize
20347
20348 @noindent
20349 These options are suitable for most program development purposes. This
20350 chapter describes how you can modify these choices, and also provides
20351 some guidelines on debugging optimized code.
20352
20353 @menu
20354 * Controlling Run-Time Checks::
20355 * Optimization Levels::
20356 * Debugging Optimized Code::
20357 * Inlining of Subprograms::
20358 @end menu
20359
20360 @node Controlling Run-Time Checks
20361 @section Controlling Run-Time Checks
20362
20363 @noindent
20364 By default, GNAT generates all run-time checks, except arithmetic overflow
20365 checking for integer operations and checks for access before elaboration on
20366 subprogram calls. The latter are not required in default mode, because all
20367 necessary checking is done at compile time.
20368 @cindex @option{-gnatp} (@code{gcc})
20369 @cindex @option{-gnato} (@code{gcc})
20370 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
20371 be modified. @xref{Run-Time Checks}.
20372
20373 Our experience is that the default is suitable for most development
20374 purposes.
20375
20376 We treat integer overflow specially because these
20377 are quite expensive and in our experience are not as important as other
20378 run-time checks in the development process. Note that division by zero
20379 is not considered an overflow check, and divide by zero checks are
20380 generated where required by default.
20381
20382 Elaboration checks are off by default, and also not needed by default, since
20383 GNAT uses a static elaboration analysis approach that avoids the need for
20384 run-time checking. This manual contains a full chapter discussing the issue
20385 of elaboration checks, and if the default is not satisfactory for your use,
20386 you should read this chapter.
20387
20388 For validity checks, the minimal checks required by the Ada Reference
20389 Manual (for case statements and assignments to array elements) are on
20390 by default. These can be suppressed by use of the @option{-gnatVn} switch.
20391 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
20392 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
20393 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
20394 are also suppressed entirely if @option{-gnatp} is used.
20395
20396 @cindex Overflow checks
20397 @cindex Checks, overflow
20398 @findex Suppress
20399 @findex Unsuppress
20400 @cindex pragma Suppress
20401 @cindex pragma Unsuppress
20402 Note that the setting of the switches controls the default setting of
20403 the checks. They may be modified using either @code{pragma Suppress} (to
20404 remove checks) or @code{pragma Unsuppress} (to add back suppressed
20405 checks) in the program source.
20406
20407 @node Optimization Levels
20408 @section Optimization Levels
20409 @cindex @code{-O} (@code{gcc})
20410
20411 @noindent
20412 The default is optimization off. This results in the fastest compile
20413 times, but GNAT makes absolutely no attempt to optimize, and the
20414 generated programs are considerably larger and slower than when
20415 optimization is enabled. You can use the
20416 @code{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
20417 on the @code{gcc} command line to control the optimization level:
20418
20419 @table @code
20420 @item -O0
20421 no optimization (the default)
20422
20423 @item -O1
20424 medium level optimization
20425
20426 @item -O2
20427 full optimization
20428
20429 @item -O3
20430 full optimization, and also attempt automatic inlining of small
20431 subprograms within a unit (@pxref{Inlining of Subprograms}).
20432 @end table
20433
20434 Higher optimization levels perform more global transformations on the
20435 program and apply more expensive analysis algorithms in order to generate
20436 faster and more compact code. The price in compilation time, and the
20437 resulting improvement in execution time,
20438 both depend on the particular application and the hardware environment.
20439 You should experiment to find the best level for your application.
20440
20441 Note: Unlike some other compilation systems, @code{gcc} has
20442 been tested extensively at all optimization levels. There are some bugs
20443 which appear only with optimization turned on, but there have also been
20444 bugs which show up only in @emph{unoptimized} code. Selecting a lower
20445 level of optimization does not improve the reliability of the code
20446 generator, which in practice is highly reliable at all optimization
20447 levels.
20448
20449 Note regarding the use of @code{-O3}: The use of this optimization level
20450 is generally discouraged with GNAT, since it often results in larger
20451 executables which run more slowly. See further discussion of this point
20452 in @pxref{Inlining of Subprograms}.
20453
20454 @node Debugging Optimized Code
20455 @section Debugging Optimized Code
20456
20457 @noindent
20458 Since the compiler generates debugging tables for a compilation unit before
20459 it performs optimizations, the optimizing transformations may invalidate some
20460 of the debugging data.  You therefore need to anticipate certain
20461 anomalous situations that may arise while debugging optimized code.  This
20462 section describes the most common cases.
20463
20464 @enumerate
20465 @item
20466 @i{The "hopping Program Counter":}  Repeated 'step' or 'next' commands show the PC
20467 bouncing back and forth in the code.  This may result from any of the following
20468 optimizations:
20469
20470 @itemize @bullet
20471 @item
20472 @i{Common subexpression elimination:} using a single instance of code for a
20473 quantity that the source computes several times.  As a result you
20474 may not be able to stop on what looks like a statement.
20475
20476 @item
20477 @i{Invariant code motion:} moving an expression that does not change within a
20478 loop, to the beginning of the loop.
20479
20480 @item
20481 @i{Instruction scheduling:} moving instructions so as to
20482 overlap loads and stores (typically) with other code, or in
20483 general to move computations of values closer to their uses. Often
20484 this causes you to pass an assignment statement without the assignment
20485 happening and then later bounce back to the statement when the
20486 value is actually needed.  Placing a breakpoint on a line of code
20487 and then stepping over it may, therefore, not always cause all the
20488 expected side-effects.
20489 @end itemize
20490
20491 @item
20492 @i{The "big leap":} More commonly known as @i{cross-jumping}, in which two
20493 identical pieces of code are merged and the program counter suddenly
20494 jumps to a statement that is not supposed to be executed, simply because
20495 it (and the code following) translates to the same thing as the code
20496 that @emph{was} supposed to be executed.  This effect is typically seen in
20497 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
20498 a @code{break} in a C @code{switch} statement.
20499
20500 @item
20501 @i{The "roving variable":} The symptom is an unexpected value in a variable.
20502 There are various reasons for this effect:
20503
20504 @itemize @bullet
20505 @item
20506 In a subprogram prologue, a parameter may not yet have been moved to its
20507 "home".
20508
20509 @item
20510 A variable may be dead, and its register re-used.  This is
20511 probably the most common cause.
20512
20513 @item
20514 As mentioned above, the assignment of a value to a variable may
20515 have been moved.
20516
20517 @item
20518 A variable may be eliminated entirely by value propagation or
20519 other means.  In this case, GCC may incorrectly generate debugging
20520 information for the variable
20521 @end itemize
20522
20523 @noindent
20524 In general, when an unexpected value appears for a local variable or parameter
20525 you should first ascertain if that value was actually computed by
20526 your program, as opposed to being incorrectly reported by the debugger.
20527 Record fields or
20528 array elements in an object designated by an access value
20529 are generally less of a problem, once you have ascertained that the access value
20530 is sensible.
20531 Typically, this means checking variables in the preceding code and in the
20532 calling subprogram to verify that the value observed is explainable from other
20533 values (one must apply the procedure recursively to those
20534 other values); or re-running the code and stopping a little earlier
20535 (perhaps before the call) and stepping to better see how the variable obtained
20536 the value in question; or continuing to step @emph{from} the point of the
20537 strange value to see if code motion had simply moved the variable's
20538 assignments later.
20539 @end enumerate
20540
20541 @node Inlining of Subprograms
20542 @section Inlining of Subprograms
20543
20544 @noindent
20545 A call to a subprogram in the current unit is inlined if all the
20546 following conditions are met:
20547
20548 @itemize @bullet
20549 @item
20550 The optimization level is at least @code{-O1}.
20551
20552 @item
20553 The called subprogram is suitable for inlining: It must be small enough
20554 and not contain nested subprograms or anything else that @code{gcc}
20555 cannot support in inlined subprograms.
20556
20557 @item
20558 The call occurs after the definition of the body of the subprogram.
20559
20560 @item
20561 @cindex pragma Inline
20562 @findex Inline
20563 Either @code{pragma Inline} applies to the subprogram or it is
20564 small and automatic inlining (optimization level @code{-O3}) is
20565 specified.
20566 @end itemize
20567
20568 @noindent
20569 Calls to subprograms in @code{with}'ed units are normally not inlined.
20570 To achieve this level of inlining, the following conditions must all be
20571 true:
20572
20573 @itemize @bullet
20574 @item
20575 The optimization level is at least @code{-O1}.
20576
20577 @item
20578 The called subprogram is suitable for inlining: It must be small enough
20579 and not contain nested subprograms or anything else @code{gcc} cannot
20580 support in inlined subprograms.
20581
20582 @item
20583 The call appears in a body (not in a package spec).
20584
20585 @item
20586 There is a @code{pragma Inline} for the subprogram.
20587
20588 @item
20589 @cindex @option{-gnatn} (@code{gcc})
20590 The @code{-gnatn} switch
20591 is used in the @code{gcc} command line
20592 @end itemize
20593
20594 Note that specifying the @option{-gnatn} switch causes additional
20595 compilation dependencies. Consider the following:
20596
20597 @smallexample
20598 @group
20599 @cartouche
20600 @b{package} R @b{is}
20601    @b{procedure} Q;
20602    @b{pragma} Inline (Q);
20603 @b{end} R;
20604 @b{package body} R @b{is}
20605    ...
20606 @b{end} R;
20607
20608 @b{with} R;
20609 @b{procedure} Main @b{is}
20610 @b{begin}
20611    ...
20612    R.Q;
20613 @b{end} Main;
20614 @end cartouche
20615 @end group
20616 @end smallexample
20617
20618 @noindent
20619 With the default behavior (no @option{-gnatn} switch specified), the
20620 compilation of the @code{Main} procedure depends only on its own source,
20621 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
20622 means that editing the body of @code{R} does not require recompiling
20623 @code{Main}.
20624
20625 On the other hand, the call @code{R.Q} is not inlined under these
20626 circumstances. If the @option{-gnatn} switch is present when @code{Main}
20627 is compiled, the call will be inlined if the body of @code{Q} is small
20628 enough, but now @code{Main} depends on the body of @code{R} in
20629 @file{r.adb} as well as on the spec. This means that if this body is edited,
20630 the main program must be recompiled. Note that this extra dependency
20631 occurs whether or not the call is in fact inlined by @code{gcc}.
20632
20633 The use of front end inlining with @option{-gnatN} generates similar
20634 additional dependencies.
20635
20636 @cindex @code{-fno-inline} (@code{gcc})
20637 Note: The @code{-fno-inline} switch
20638 can be used to prevent
20639 all inlining. This switch overrides all other conditions and ensures
20640 that no inlining occurs. The extra dependences resulting from
20641 @option{-gnatn} will still be active, even if
20642 this switch is used to suppress the resulting inlining actions.
20643
20644 Note regarding the use of @code{-O3}: There is no difference in inlining
20645 behavior between @code{-O2} and @code{-O3} for subprograms with an explicit
20646 pragma @code{Inline} assuming the use of @option{-gnatn}
20647 or @option{-gnatN} (the switches that activate inlining). If you have used
20648 pragma @code{Inline} in appropriate cases, then it is usually much better
20649 to use @code{-O2} and @option{-gnatn} and avoid the use of @code{-O3} which
20650 in this case only has the effect of inlining subprograms you did not
20651 think should be inlined. We often find that the use of @code{-O3} slows
20652 down code by performing excessive inlining, leading to increased instruction
20653 cache pressure from the increased code size. So the bottom line here is
20654 that you should not automatically assume that @code{-O3} is better than
20655 @code{-O2}, and indeed you should use @code{-O3} only if tests show that
20656 it actually improves performance.
20657
20658
20659 @include fdl.texi
20660 @c GNU Free Documentation License
20661
20662 @node Index,,GNU Free Documentation License, Top
20663 @unnumbered Index
20664
20665 @printindex cp
20666
20667 @contents
20668
20669 @bye