OSDN Git Service

* approved by rth
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ug_vxw.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
59
60 @setfilename gnat_ug_vxw.info
61 @settitle GNAT User's Guide for Cross Platforms
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
73
74 @title GNAT User's Guide
75 @center @titlefont{for Cross Platforms}
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 Cross Platforms'',
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
105
106 GNAT User's Guide for Cross Platforms
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 Cross Platforms'',
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 * Preliminary Note for Cross Platform Users::
129 * Getting Started with GNAT::
130 * The GNAT Compilation Model::
131 * Compiling Using gcc::
132 * Binding Using gnatbind::
133 * Linking Using gnatlink::
134 * The GNAT Make Program gnatmake::
135 * Renaming Files Using gnatchop::
136 * Configuration Pragmas::
137 * Handling Arbitrary File Naming Conventions Using gnatname::
138 * GNAT Project Manager::
139 * Elaboration Order Handling in GNAT::
140 * The Cross-Referencing Tools gnatxref and gnatfind::
141 * File Name Krunching Using gnatkr::
142 * Preprocessing Using gnatprep::
143 * The GNAT Library Browser gnatls::
144 * GNAT and Libraries::
145 * Using the GNU make Utility::
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 * VxWorks Topics::
153 * LynxOS Topics::
154 * Performance Considerations::
155 * GNU Free Documentation License::
156 * Index::
157
158  --- The Detailed Node Listing ---
159
160 About This Guide
161
162 * What This Guide Contains::
163 * What You Should Know before Reading This Guide::
164 * Related Information::
165 * Conventions::
166
167 Preliminary Note for Cross Platform Users::
168
169 Getting Started with GNAT
170
171 * Running GNAT::
172 * Building a Simple Ada Program::
173 * Executing a Program on VxWorks::
174 * Running a Program with Multiple Units::
175 * Using the gnatmake Utility::
176
177 The GNAT Compilation Model
178
179 * Source Representation::
180 * Foreign Language Representation::
181 * File Naming Rules::
182 * Using Other File Names::
183 * Alternative File Naming Schemes::
184 * Generating Object Files::
185 * Source Dependencies::
186 * The Ada Library Information Files::
187 * Binding an Ada Program::
188 * Mixed Language Programming::
189 * Building Mixed Ada & C++ Programs::
190 * Comparison between GNAT and C/C++ Compilation Models::
191 * Comparison between GNAT and Conventional Ada Library Models::
192
193 Foreign Language Representation
194
195 * Latin-1::
196 * Other 8-Bit Codes::
197 * Wide Character Encodings::
198
199 Compiling Ada Programs With gcc
200
201 * Compiling Programs::
202 * Switches for gcc::
203 * Search Paths and the Run-Time Library (RTL)::
204 * Order of Compilation Issues::
205 * Examples::
206
207 Switches for gcc
208
209 * Output and Error Message Control::
210 * Debugging and Assertion Control::
211 * Run-Time Checks::
212 * Stack Overflow Checking::
213 * Run-Time Control::
214 * Validity Checking::
215 * Style Checking::
216 * Using gcc for Syntax Checking::
217 * Using gcc for Semantic Checking::
218 * Compiling Ada 83 Programs::
219 * Character Set Control::
220 * File Naming Control::
221 * Subprogram Inlining Control::
222 * Auxiliary Output Control::
223 * Debugging Control::
224 * Units to Sources Mapping Files::
225
226 Binding Ada Programs With gnatbind
227
228 * Running gnatbind::
229 * Generating the Binder Program in C::
230 * Consistency-Checking Modes::
231 * Binder Error Message Control::
232 * Elaboration Control::
233 * Output Control::
234 * Binding with Non-Ada Main Programs::
235 * Binding Programs with No Main Subprogram::
236 * Summary of Binder Switches::
237 * Command-Line Access::
238 * Search Paths for gnatbind::
239 * Examples of gnatbind Usage::
240
241 Linking Using gnatlink
242
243 * Running gnatlink::
244 * Switches for gnatlink::
245 * Setting Stack Size from gnatlink::
246 * Setting Heap Size from gnatlink::
247
248 The GNAT Make Program gnatmake
249
250 * Running gnatmake::
251 * Switches for gnatmake::
252 * Mode Switches for gnatmake::
253 * Notes on the Command Line::
254 * How gnatmake Works::
255 * Examples of gnatmake Usage::
256
257 Renaming Files Using gnatchop
258
259 * Handling Files with Multiple Units::
260 * Operating gnatchop in Compilation Mode::
261 * Command Line for gnatchop::
262 * Switches for gnatchop::
263 * Examples of gnatchop Usage::
264
265 Configuration Pragmas
266
267 * Handling of Configuration Pragmas::
268 * The Configuration Pragmas Files::
269
270 Handling Arbitrary File Naming Conventions Using gnatname
271
272 * Arbitrary File Naming Conventions::
273 * Running gnatname::
274 * Switches for gnatname::
275 * Examples of gnatname Usage::
276
277 GNAT Project Manager
278
279 * Introduction::
280 * Examples of Project Files::
281 * Project File Syntax::
282 * Objects and Sources in Project Files::
283 * Importing Projects::
284 * Project Extension::
285 * External References in Project Files::
286 * Packages in Project Files::
287 * Variables from Imported Projects::
288 * Naming Schemes::
289 * Library Projects::
290 * Switches Related to Project Files::
291 * Tools Supporting Project Files::
292 * An Extended Example::
293 * Project File Complete Syntax::
294
295 Elaboration Order Handling in GNAT
296
297 * Elaboration Code in Ada 95::
298 * Checking the Elaboration Order in Ada 95::
299 * Controlling the Elaboration Order in Ada 95::
300 * Controlling Elaboration in GNAT - Internal Calls::
301 * Controlling Elaboration in GNAT - External Calls::
302 * Default Behavior in GNAT - Ensuring Safety::
303 * Elaboration Issues for Library Tasks::
304 * Mixing Elaboration Models::
305 * What to Do If the Default Elaboration Behavior Fails::
306 * Elaboration for Access-to-Subprogram Values::
307 * Summary of Procedures for Elaboration Control::
308 * Other Elaboration Order Considerations::
309
310 The Cross-Referencing Tools gnatxref and gnatfind
311
312 * gnatxref Switches::
313 * gnatfind Switches::
314 * Project Files for gnatxref and gnatfind::
315 * Regular Expressions in gnatfind and gnatxref::
316 * Examples of gnatxref Usage::
317 * Examples of gnatfind Usage::
318
319 File Name Krunching Using gnatkr
320
321 * About gnatkr::
322 * Using gnatkr::
323 * Krunching Method::
324 * Examples of gnatkr Usage::
325
326 Preprocessing Using gnatprep
327
328 * Using gnatprep::
329 * Switches for gnatprep::
330 * Form of Definitions File::
331 * Form of Input Text for gnatprep::
332
333
334 The GNAT Library Browser gnatls
335
336 * Running gnatls::
337 * Switches for gnatls::
338 * Examples of gnatls Usage::
339
340
341 GNAT and Libraries
342
343 * Creating an Ada Library::
344 * Installing an Ada Library::
345 * Using an Ada Library::
346 * Creating an Ada Library to be Used in a Non-Ada Context::
347 * Rebuilding the GNAT Run-Time Library::
348
349 Using the GNU make Utility
350
351 * Using gnatmake in a Makefile::
352 * Automatically Creating a List of Directories::
353 * Generating the Command Line Switches::
354 * Overcoming Command Line Length Limits::
355
356
357 Finding Memory Problems with GNAT Debug Pool
358
359 Creating Sample Bodies Using gnatstub
360
361 * Running gnatstub::
362 * Switches for gnatstub::
363
364 Reducing the Size of Ada Executables with gnatelim
365
366 * About gnatelim::
367 * Eliminate Pragma::
368 * Tree Files::
369 * Preparing Tree and Bind Files for gnatelim::
370 * Running gnatelim::
371 * Correcting the List of Eliminate Pragmas::
372 * Making Your Executables Smaller::
373 * Summary of the gnatelim Usage Cycle::
374
375 Other Utility Programs
376
377 * Using Other Utility Programs with GNAT::
378 * The gnatpsta Utility Program::
379 * The External Symbol Naming Scheme of GNAT::
380 * Ada Mode for Glide::
381 * Converting Ada Files to html with gnathtml::
382
383
384 Running and Debugging Ada Programs
385
386 * The GNAT Debugger GDB::
387 * Running GDB::
388 * Introduction to GDB Commands::
389 * Using Ada Expressions::
390 * Calling User-Defined Subprograms::
391 * Using the Next Command in a Function::
392 * Ada Exceptions::
393 * Ada Tasks::
394 * Debugging Generic Units::
395 * GNAT Abnormal Termination or Failure to Terminate::
396 * Naming Conventions for GNAT Source Files::
397 * Getting Internal Debugging Information::
398 * Stack Traceback::
399
400 Inline Assembler
401
402 * Basic Assembler Syntax::
403 * A Simple Example of Inline Assembler::
404 * Output Variables in Inline Assembler::
405 * Input Variables in Inline Assembler::
406 * Inlining Inline Assembler Code::
407 * Other Asm Functionality::
408 * A Complete Example::
409
410
411 VxWorks Topics
412
413 * Kernel Configuration for VxWorks::
414 * Kernel Compilation Issues for VxWorks::
415 * Handling Relocation Issues for PowerPc Targets::
416 * Support for Software Floating Point on PowerPC Processors::
417 * Interrupt Handling for VxWorks::
418 * Simulating Command Line Arguments for VxWorks::
419 * Debugging Issues for VxWorks::
420 * Using GNAT from the Tornado 2 Project Facility::
421 * Frequently Asked Questions for VxWorks::
422
423 LynxOS Topics
424
425 * Getting Started with GNAT on LynxOS::
426 * Kernel Configuration for LynxOS::
427 * Patch Level Issues for LynxOS::
428 * Debugging Issues for LynxOS::
429 * An Example Debugging Session for LynxOS::
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{Preliminary Note for Cross Platform Users}, describes the basic
466 differences between the cross and native versions of GNAT.
467 @item
468 @ref{Getting Started with GNAT}, describes how to get started compiling
469 and running Ada programs with the GNAT Ada programming environment.
470 @item
471 @ref{The GNAT Compilation Model}, describes the compilation model used
472 by GNAT.
473 @item
474 @ref{Compiling Using gcc}, describes how to compile
475 Ada programs with @code{gcc}, the Ada compiler.
476 @item
477 @ref{Binding Using gnatbind}, describes how to
478 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
479 utility.
480 @item
481 @ref{Linking Using gnatlink},
482 describes @code{gnatlink}, a
483 program that provides for linking using the GNAT run-time library to
484 construct a program. @code{gnatlink} can also incorporate foreign language
485 object units into the executable.
486 @item
487 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
488 utility that automatically determines the set of sources
489 needed by an Ada compilation unit, and executes the necessary compilations
490 binding and link.
491 @item
492 @ref{Renaming Files Using gnatchop}, describes
493 @code{gnatchop}, a utility that allows you to preprocess a file that
494 contains Ada source code, and split it into one or more new files, one
495 for each compilation unit.
496 @item
497 @ref{Configuration Pragmas}, describes the configuration pragmas handled by GNAT.
498 @item
499 @ref{Handling Arbitrary File Naming Conventions Using gnatname}, shows how to override
500 the default GNAT file naming conventions, either for an individual unit or globally.
501 @item
502 @ref{GNAT Project Manager}, describes how to use project files to organize large projects.
503 @item
504 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps you deal with
505 elaboration order issues.
506 @item
507 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
508 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
509 way to navigate through sources.
510 @item
511 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
512 file name krunching utility, used to handle shortened
513 file names on operating systems with a limit on the length of names.
514 @item
515 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
516 preprocessor utility that allows a single source file to be used to
517 generate multiple or parameterized source files, by means of macro
518 substitution.
519 @item
520 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
521 utility that displays information about compiled units, including dependences
522 on the corresponding sources files, and consistency of compilations.
523 @item
524 @ref{GNAT and Libraries}, describes the process of creating and using
525 Libraries with GNAT. It also describes how to recompile the GNAT run-time
526 library.
527
528 @item
529 @ref{Using the GNU make Utility}, describes some techniques for using
530 the GNAT toolset in Makefiles.
531
532 @item
533 @ref{Finding Memory Problems with GNAT Debug Pool}, describes how to
534 use the GNAT-specific Debug Pool in order to detect as early as possible
535 the use of incorrect memory references.
536
537 @item
538 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
539 a utility that generates empty but compilable bodies for library units.
540
541 @item
542 @ref{Reducing the Size of Ada Executables with gnatelim}, describes
543 @code{gnatelim}, a tool which detects unused subprograms and helps
544 the compiler to create a smaller executable for the program.
545
546 @item
547 @ref{Other Utility Programs}, discusses several other GNAT utilities,
548 including @code{gnatpsta}.
549
550 @item
551 @ref{Running and Debugging Ada Programs}, describes how to run and debug
552 Ada programs.
553
554 @item
555 @ref{Inline Assembler}, shows how to use the inline assembly facility in an Ada program.
556
557 @item
558 @ref{VxWorks Topics}, presents information relevant to the VxWorks target for cross-compilation
559 configurations.
560
561 @item
562 @ref{LynxOS Topics}, presents information relevant to the LynxOS target for cross-compilation
563 configurations.
564
565 @item
566 @ref{Performance Considerations}, reviews the trade offs between using
567 defaults or options in program development.
568 @end itemize
569
570 @node What You Should Know before Reading This Guide
571 @unnumberedsec What You Should Know before Reading This Guide
572
573 @cindex Ada 95 Language Reference Manual
574 @noindent
575 This user's guide assumes that you are familiar with Ada 95 language, as
576 described in the International Standard ANSI/ISO/IEC-8652:1995, Jan
577 1995.
578
579 @node Related Information
580 @unnumberedsec Related Information
581
582 @noindent
583 For further information about related tools, refer to the following
584 documents:
585
586 @itemize @bullet
587 @item
588 @cite{GNAT Reference Manual}, which contains all reference
589 material for the GNAT implementation of Ada 95.
590
591 @item
592 @cite{Ada 95 Language Reference Manual}, which contains all reference
593 material for the Ada 95 programming language.
594
595 @item
596 @cite{Debugging with GDB}
597 contains all details on the use of the GNU source-level debugger.
598
599 @item
600 @cite{GNU Emacs Manual}
601 contains full information on the extensible editor and programming
602 environment Emacs.
603
604 @end itemize
605
606 @node Conventions
607 @unnumberedsec Conventions
608 @cindex Conventions
609 @cindex Typographical conventions
610
611 @noindent
612 Following are examples of the typographical and graphic conventions used
613 in this guide:
614
615 @itemize @bullet
616 @item
617 @code{Functions}, @code{utility program names}, @code{standard names},
618 and @code{classes}.
619
620 @item
621 @samp{Option flags}
622
623 @item
624 @file{File Names}, @file{button names}, and @file{field names}.
625
626 @item
627 @var{Variables}.
628
629 @item
630 @emph{Emphasis}.
631
632 @item
633 [optional information or parameters]
634
635 @item
636 Examples are described by text
637 @smallexample
638 and then shown this way.
639 @end smallexample
640 @end itemize
641
642 @noindent
643 Commands that are entered by the user are preceded in this manual by the
644 characters @w{"@code{$ }"} (dollar sign followed by space). If your system
645 uses this sequence as a prompt, then the commands will appear exactly as
646 you see them in the manual. If your system uses some other prompt, then
647 the command will appear with the @code{$} replaced by whatever prompt
648 character you are using.
649
650 @node Preliminary Note for Cross Platform Users
651 @chapter Preliminary Note for Cross Platform Users
652
653 @noindent
654 The use of GNAT in a cross environment is very similar to its use in a
655 native environment. Most of the tools described in this manual have
656 similar functions and options in both modes. The major
657 difference is that the name of the cross tools includes the target for
658 which the cross compiler is configured. For instance, the cross @command{gnatmake}
659 tool is called @command{@i{target}-gnatmake} where @code{@i{target}} stands for the name of
660 the cross target. Thus, in an environment configured for the
661 target @code{powerpc-wrs-vxworks}, the @command{gnatmake} command is
662 @code{powerpc-wrs-vxworks-gnatmake}. This convention allows the
663 installation of a native and one or several cross development
664 environments at the same location.
665
666 The tools that are most relevant in a cross environment are:
667 @code{@i{target}-gcc}, @code{@i{target}-gnatmake},
668 @code{@i{target}-gnatbind}, @code{@i{target}-gnatlink} to build cross
669 applications and @code{@i{target}-gnatls} for cross library
670 browsing. @code{@i{target}-gdb} is also usually available for cross
671 debugging in text mode. The graphical debugger interface
672 @code{gvd} is always a native tool but it can be configured to drive
673 the above mentioned cross debugger, thus allowing graphical cross debugging
674 sessions. Some other tools such as  @code{@i{target}-gnatchop},
675 @code{@i{target}-gnatkr}, @code{@i{target}-gnatprep},
676 @code{@i{target}-gnatpsta}, @code{@i{target}-gnatxref}, @code{@i{target}-gnatfind}
677 and @code{@i{target}-gnatname} are also provided for completeness
678 even though they do not differ greatly from their native counterpart.
679
680 In the rest of this manual, the tools are sometimes designated with
681 their full cross name, and sometimes with their simplified native
682 name.
683
684
685 @node Getting Started with GNAT
686 @chapter Getting Started with GNAT
687
688 @noindent
689 This introduction is a starting point for using GNAT to develop
690 and execute Ada 95 programs in a cross environment.
691 It provides some specifics
692 about the GNAT toolchain targeted to the Wind River Sytems' VxWorks/Tornado platform;
693 for other targets please refer to the corresponding chapter later in this manual.
694
695 Basic familiarity with use of GNAT in a native environment is
696 presumed. For the VxWorks specific part, a knowledge of how to start
697 Tornado's @code{windsh} tool is also presumed.
698
699 @menu
700 * Running GNAT::
701 * Building a Simple Ada Program::
702 * Executing a Program on VxWorks::
703
704 * Running a Program with Multiple Units::
705
706 * Using the gnatmake Utility::
707 * Introduction to Glide and GVD::
708 @end menu
709
710 @node Running GNAT
711 @section Running GNAT
712
713 @noindent
714 Three steps are needed to create an executable file from an Ada source
715 file:
716
717 @enumerate
718 @item
719 The source file(s) must be compiled.
720 @item
721 The file(s) must be bound using the GNAT binder.
722 @item
723 All appropriate object files must be linked to produce a loadable module.
724 @end enumerate
725
726 @noindent
727 All three steps are most commonly handled by using the @code{gnatmake}
728 utility program that, given the name of the main program, automatically
729 performs the necessary compilation, binding and linking steps.
730
731 @node Building a Simple Ada Program
732 @section Building a Simple Ada Program
733
734 @noindent
735 Any text editor may be used to prepare an Ada program. If @code{Glide} is
736 used, the optional Ada mode may be helpful in laying out the program. The
737 program text is a normal text file. We will suppose in our initial
738 example that you have used your editor to prepare the following
739 standard format text file:
740
741 @smallexample
742 @group
743 @cartouche
744 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
745 @b{procedure} Hello @b{is}
746 @b{begin}
747    Put_Line ("Hello WORLD!");
748 @b{end} Hello;
749 @end cartouche
750 @end group
751 @end smallexample
752
753 @noindent
754 This file should be named @file{hello.adb}.
755 With the normal default file naming conventions, GNAT requires
756 that each file
757 contain a single compilation unit whose file name is the
758 unit name,
759 with periods replaced by hyphens; the
760 extension is @file{ads} for a
761 spec and @file{adb} for a body.
762 You can override this default file naming convention by use of the
763 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
764 Alternatively, if you want to rename your files according to this default
765 convention, which is probably more convenient if you will be using GNAT
766 for all your compilations, then the @code{gnatchop} utility
767 can be used to generate correctly-named source files
768 (@pxref{Renaming Files Using gnatchop}).
769
770 You can compile the program using the following command (@code{$} is used
771 as the command prompt in the examples in this document):
772
773
774 @smallexample
775 $ @i{target}-gcc -c hello.adb
776 @end smallexample
777
778 @noindent
779 @code{gcc} is the command used to run the compiler. This compiler is
780 capable of compiling programs in several languages, including Ada 95 and
781 C. It assumes that you have given it an Ada program if the file extension is
782 either @file{.ads} or @file{.adb}, and it will then call the GNAT compiler to compile
783 the specified file.
784
785 The @option{-c} switch is required. It tells @command{gcc} to only do a
786 compilation. (For C programs, @command{gcc} can also do linking, but this
787 capability is not used directly for Ada programs, so the @option{-c}
788 switch must always be present.)
789
790 This compile command generates a file
791 @file{hello.o}, which is the object
792 file corresponding to your Ada program. It also generates an "Ada Library Information" file
793 @file{hello.ali},
794 which contains additional information used to check
795 that an Ada program is consistent.
796 To build a downloadable module,
797 use @code{gnatbind} to bind the program
798 and @code{gnatlink} to link it. The
799 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
800 @file{ali} file, but the default extension of @file{.ali} can
801 be omitted. This means that in the most common case, the argument
802 is simply the name of the main program:
803
804
805 @smallexample
806 $ @i{target}-gnatbind hello
807 $ @i{target}-gnatlink hello
808 @end smallexample
809
810 @noindent
811 A simpler method of carrying out these steps is to use
812 @command{gnatmake},
813 a master program that invokes all the required
814 compilation, binding and linking tools in the correct order. In particular,
815 @command{gnatmake} automatically recompiles any sources that have been modified
816 since they were last compiled, or sources that depend
817 on such modified sources, so that "version skew" is avoided.
818 @cindex Version skew (avoided by @command{gnatmake})
819
820
821 @smallexample
822 $ @i{target}-gnatmake hello.adb
823 @end smallexample
824
825
826 @noindent
827 The result is a relocatable object called @file{hello}.
828
829 @emph{Technical note:} the result of the linking stage is a
830 relocatable partially-linked object containing all the relevant GNAT
831 run-time units, in contrast with the executable-format object file found in
832 native environments.
833
834
835 @node Executing a Program on VxWorks
836 @section Executing a Program on VxWorks
837
838 @noindent
839 Getting a program to execute involves loading it onto the target, running it, and then (if re-execution is needed) unloading it.
840
841 @menu
842 * Loading and Running the Program::
843 * Unloading the Program::
844 @end menu
845
846 @node Loading and Running the Program
847 @subsection Loading and Running the Program
848
849 @noindent
850 An Ada program is loaded and run in the same way as a C program.
851 Details may be found in the @cite{Tornado User's Guide}.
852
853 In order to load and run our simple "Hello World" example, we assume that
854 the target has access to the disk of the host containing this object and
855 that its working directory has been set to the directory containing this
856 object. The commands are typed in Tornado's Windshell. The @code{windsh} prompt
857 is the @code{->} sequence.
858
859 @smallexample
860 -> vf0=open("/vio/0",2,0)
861 new symbol "vf0" added to symbol table.
862 vf0 = 0x2cab48: value = 12 = 0xc
863 -> ioGlobalStdSet(1,vf0)
864 value = 1 = 0x1
865 -> ld < hello
866 value = 665408 = 0xa2740
867 -> hello
868 Hello World
869 value = 0 = 0x0
870 ->
871 @end smallexample
872
873 @noindent
874 The first two commands redirect output to the shell window.
875 They are only needed if the target server was started without the
876 @code{-C} option.  The third command loads the module, which is the file
877 @file{hello} created previously by the @code{@i{target}-gnatmake} command.
878 Note that for Tornado AE, the @command{ml} command replaces @command{ld}."
879
880 The "Hello World" program comprises a procedure named @code{hello}, and this
881 is the name entered for the procedure in the target server's symbol table
882 when the module is loaded.  To execute the procedure, type the symbol name @code{hello}
883 into @code{windsh} as shown in the last command above.
884
885 Note that by default the entry point of an Ada program is the name of the main
886 Ada subprogram in a VxWorks environment. It is possible to use an alternative
887 name; see the description of @code{gnatbind} options for details.
888
889 @node Unloading the Program
890 @subsection Unloading the Program
891
892 @noindent
893 It is important to remember that
894 you must unload a program once you have run it. You
895 cannot load it once and run it several times. If you don't follow
896 this rule, your program's behavior can be unpredictable, and will most
897 probably crash.
898
899 This effect is due to the implementation of Ada 95's @emph{elaboration} semantics.
900 The unit elaboration phase comprises a @emph{static} elaboration and a
901 @emph{dynamic} elaboration. On a native platform they both take place
902 when the program is run. Thus rerunning the program will repeat the complete
903 elaboration phase, and the program will run correctly.
904
905 On VxWorks, the process is a bit different.
906 The static elaboration phase is handled by
907 the loader (typically when you type @code{ld < program_name} in
908 @code{windsh}). The dynamic phase takes place when the program is run. If the
909 program is run twice and has not been unloaded and then reloaded, the
910 second time it is run, the static elaboration phase is skipped.
911 Variables initialized during the static elaboration phase
912 may have been modified during the first execution of the program. Thus the
913 second execution isn't performed on a completely initialized environment.
914
915 Note that in C programs, elaboration isn't systematic. Multiple runs without reload
916 might work, but, even with C programs, if there is an elaboration
917 phase, you will have to unload your program before re-running it.
918
919
920 @node Running a Program with Multiple Units
921 @section Running a Program with Multiple Units
922
923 @noindent
924 Consider a slightly more complicated example that has three files: a
925 main program, and the spec and body of a package:
926
927 @smallexample
928 @cartouche
929 @group
930 @b{package} Greetings @b{is}
931    @b{procedure} Hello;
932    @b{procedure} Goodbye;
933 @b{end} Greetings;
934
935 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
936 @b{package} @b{body} Greetings @b{is}
937    @b{procedure} Hello @b{is}
938    @b{begin}
939       Put_Line ("Hello WORLD!");
940    @b{end} Hello;
941
942    @b{procedure} Goodbye @b{is}
943    @b{begin}
944       Put_Line ("Goodbye WORLD!");
945    @b{end} Goodbye;
946 @b{end} Greetings;
947 @end group
948
949 @group
950 @b{with} Greetings;
951 @b{procedure} Gmain @b{is}
952 @b{begin}
953    Greetings.Hello;
954    Greetings.Goodbye;
955 @b{end} Gmain;
956 @end group
957 @end cartouche
958 @end smallexample
959
960 @noindent
961 Following the one-unit-per-file rule, place this program in the
962 following three separate files:
963
964 @table @file
965 @item greetings.ads
966 spec of package @code{Greetings}
967
968 @item greetings.adb
969 body of package @code{Greetings}
970
971 @item gmain.adb
972 body of main program
973 @end table
974
975 @noindent
976 To build an executable version of
977 this program, we could use four separate steps to compile, bind, and link
978 the program, as follows:
979
980
981 @smallexample
982 $ @i{target}-gcc -c gmain.adb
983 $ @i{target}-gcc -c greetings.adb
984 $ @i{target}-gnatbind gmain
985 $ @i{target}-gnatlink gmain
986 @end smallexample
987
988 @noindent
989 Note that there is no required order of compilation when using GNAT.
990 In particular it is perfectly fine to compile the main program first.
991 Also, it is not necessary to compile package specs in the case where
992 there is an accompanying body; you only need to compile the body. If you want
993 to submit these files to the compiler for semantic checking and not code generation,
994 then use the
995 @option{-gnatc} switch:
996
997
998 @smallexample
999 $ @i{target}-gcc -c greetings.ads -gnatc
1000 @end smallexample
1001
1002 @noindent
1003 Although the compilation can be done in separate steps as in the
1004 above example, in practice it is almost always more convenient
1005 to use the @code{gnatmake} tool. All you need to know in this case
1006 is the name of the main program's source file. The effect of the above four
1007 commands can be achieved with a single one:
1008
1009
1010 @smallexample
1011 $ @i{target}-gnatmake gmain.adb
1012 @end smallexample
1013
1014 @noindent
1015 In the next section we discuss the advantages of using @code{gnatmake} in
1016 more detail.
1017
1018 @node Using the gnatmake Utility
1019 @section Using the @command{gnatmake} Utility
1020
1021 @noindent
1022 If you work on a program by compiling single components at a time using
1023 @code{gcc}, you typically keep track of the units you modify. In order to
1024 build a consistent system, you compile not only these units, but also any
1025 units that depend on the units you have modified.
1026 For example, in the preceding case,
1027 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1028 you edit @file{greetings.ads}, you must recompile both
1029 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1030 units that depend on @file{greetings.ads}.
1031
1032 @code{gnatbind} will warn you if you forget one of these compilation
1033 steps, so that it is impossible to generate an inconsistent program as a
1034 result of forgetting to do a compilation. Nevertheless it is tedious and
1035 error-prone to keep track of dependencies among units.
1036 One approach to handle the dependency-bookkeeping is to use a
1037 makefile. However, makefiles present maintenance problems of their own:
1038 if the dependencies change as you change the program, you must make
1039 sure that the makefile is kept up-to-date manually, which is also an
1040 error-prone process.
1041
1042 The @code{gnatmake} utility takes care of these details automatically.
1043 Invoke it using either one of the following forms:
1044
1045
1046 @smallexample
1047 $ @i{target}-gnatmake gmain.adb
1048 $ @i{target}-gnatmake gmain
1049 @end smallexample
1050
1051 @noindent
1052 The argument is the name of the file containing the main program;
1053 you may omit the extension. @code{gnatmake}
1054 examines the environment, automatically recompiles any files that need
1055 recompiling, and binds and links the resulting set of object files,
1056 generating the executable file, @file{gmain}.
1057 In a large program, it
1058 can be extremely helpful to use @code{gnatmake}, because working out by hand
1059 what needs to be recompiled can be difficult.
1060
1061 Note that @code{gnatmake}
1062 takes into account all the Ada 95 rules that
1063 establish dependencies among units. These include dependencies that result
1064 from inlining subprogram bodies, and from
1065 generic instantiation. Unlike some other
1066 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1067 found by the compiler on a previous compilation, which may possibly
1068 be wrong when sources change. @code{gnatmake} determines the exact set of
1069 dependencies from scratch each time it is run.
1070
1071
1072 @node Introduction to Glide and GVD
1073 @section Introduction to Glide and GVD
1074 @cindex Glide
1075 @cindex GVD
1076 @noindent
1077 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.
1078
1079 @menu
1080 * Building a New Program with Glide::
1081 * Simple Debugging with GVD::
1082 * Other Glide Features::
1083 @end menu
1084
1085 @node Building a New Program with Glide
1086 @subsection Building a New Program with Glide
1087 @noindent
1088 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:
1089
1090 @smallexample
1091 $ glide&
1092 @end smallexample
1093
1094 @noindent
1095 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
1096 @itemize @bullet
1097 @item @code{Buffers}
1098 @item @code{Files}
1099 @item @code{Tools}
1100 @item @code{Edit}
1101 @item @code{Search}
1102 @item @code{Mule}
1103 @item @code{Glide}
1104 @item @code{Help}
1105 @end itemize
1106
1107 @noindent
1108 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.
1109
1110 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.
1111
1112 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:
1113 @smallexample
1114 with Ada.Text_IO; use Ada.Text_IO;
1115 procedure Hello is
1116 begin
1117 @end smallexample
1118
1119 @noindent
1120 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.
1121
1122 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.
1123
1124 Next enter the statement (with an intentional error, a missing semicolon) that will form the body of the loop:
1125 @smallexample
1126 Put_Line("Hello, World" & Integer'Image(I))
1127 @end smallexample
1128
1129 @noindent
1130 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.
1131
1132 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.
1133
1134 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.
1135
1136 To execute the program, choose @code{Ada} and then @code{Run}.  You should see the program's output displayed in the bottom window:
1137
1138 @smallexample
1139 Hello, world 1
1140 Hello, world 2
1141 Hello, world 3
1142 Hello, world 4
1143 Hello, world 5
1144 @end smallexample
1145
1146 @node Simple Debugging with GVD
1147 @subsection Simple Debugging with GVD
1148
1149 @noindent
1150 This section describes how to set breakpoints, examine/modify variables, and step through execution.
1151
1152 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:
1153
1154 @smallexample
1155 $ gvd hello
1156 @end smallexample
1157
1158 @noindent
1159 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}.
1160
1161 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.
1162
1163 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.
1164
1165 For this example, set a breakpoint at the statement where @code{Put_Line} is invoked.
1166
1167 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.
1168
1169 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.
1170
1171 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.
1172
1173 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}.
1174
1175 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.
1176
1177
1178 @node Other Glide Features
1179 @subsection Other Glide Features
1180
1181 @noindent
1182 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...}.
1183
1184 To abort a Glide command, type @key{Ctrl-g}.
1185
1186 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:
1187
1188 @smallexample
1189 $ glide hello.adb&
1190 @end smallexample
1191
1192 @noindent
1193 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.
1194
1195 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}.
1196
1197 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:
1198 @itemize @bullet
1199 @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)
1200 @item With the focus in one of the windows, select the desired buffer from the @code{Buffers} menu
1201 @end itemize
1202
1203 @noindent
1204 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1205
1206 @node The GNAT Compilation Model
1207 @chapter The GNAT Compilation Model
1208 @cindex GNAT compilation model
1209 @cindex Compilation model
1210
1211 @menu
1212 * Source Representation::
1213 * Foreign Language Representation::
1214 * File Naming Rules::
1215 * Using Other File Names::
1216 * Alternative File Naming Schemes::
1217 * Generating Object Files::
1218 * Source Dependencies::
1219 * The Ada Library Information Files::
1220 * Binding an Ada Program::
1221 * Mixed Language Programming::
1222 * Building Mixed Ada & C++ Programs::
1223 * Comparison between GNAT and C/C++ Compilation Models::
1224 * Comparison between GNAT and Conventional Ada Library Models::
1225 @end menu
1226
1227 @noindent
1228 This chapter describes the compilation model used by GNAT. Although
1229 similar to that used by other languages, such as C and C++, this model
1230 is substantially different from the traditional Ada compilation models,
1231 which are based on a library. The model is initially described without
1232 reference to the library-based model. If you have not previously used an
1233 Ada compiler, you need only read the first part of this chapter. The
1234 last section describes and discusses the differences between the GNAT
1235 model and the traditional Ada compiler models. If you have used other
1236 Ada compilers, this section will help you to understand those
1237 differences, and the advantages of the GNAT model.
1238
1239 @node Source Representation
1240 @section Source Representation
1241 @cindex Latin-1
1242
1243 @noindent
1244 Ada source programs are represented in standard text files, using
1245 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1246 7-bit ASCII set, plus additional characters used for
1247 representing foreign languages (@pxref{Foreign Language Representation}
1248 for support of non-USA character sets). The format effector characters
1249 are represented using their standard ASCII encodings, as follows:
1250
1251 @table @code
1252 @item VT
1253 @findex VT
1254 Vertical tab, @code{16#0B#}
1255
1256 @item HT
1257 @findex HT
1258 Horizontal tab, @code{16#09#}
1259
1260 @item CR
1261 @findex CR
1262 Carriage return, @code{16#0D#}
1263
1264 @item LF
1265 @findex LF
1266 Line feed, @code{16#0A#}
1267
1268 @item FF
1269 @findex FF
1270 Form feed, @code{16#0C#}
1271 @end table
1272
1273 @noindent
1274 Source files are in standard text file format. In addition, GNAT will
1275 recognize a wide variety of stream formats, in which the end of physical
1276 physical lines is marked by any of the following sequences:
1277 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1278 in accommodating files that are imported from other operating systems.
1279
1280 @cindex End of source file
1281 @cindex Source file, end
1282 @findex SUB
1283 The end of a source file is normally represented by the physical end of
1284 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1285 recognized as signalling the end of the source file. Again, this is
1286 provided for compatibility with other operating systems where this
1287 code is used to represent the end of file.
1288
1289 Each file contains a single Ada compilation unit, including any pragmas
1290 associated with the unit. For example, this means you must place a
1291 package declaration (a package @dfn{spec}) and the corresponding body in
1292 separate files. An Ada @dfn{compilation} (which is a sequence of
1293 compilation units) is represented using a sequence of files. Similarly,
1294 you will place each subunit or child unit in a separate file.
1295
1296 @node Foreign Language Representation
1297 @section Foreign Language Representation
1298
1299 @noindent
1300 GNAT supports the standard character sets defined in Ada 95 as well as
1301 several other non-standard character sets for use in localized versions
1302 of the compiler (@pxref{Character Set Control}).
1303 @menu
1304 * Latin-1::
1305 * Other 8-Bit Codes::
1306 * Wide Character Encodings::
1307 @end menu
1308
1309 @node Latin-1
1310 @subsection Latin-1
1311 @cindex Latin-1
1312
1313 @noindent
1314 The basic character set is Latin-1. This character set is defined by ISO
1315 standard 8859, part 1. The lower half (character codes @code{16#00#}
1316 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half is
1317 used to represent additional characters. These include extended letters
1318 used by European languages, such as French accents, the vowels with umlauts
1319 used in German, and the extra letter A-ring used in Swedish.
1320
1321 @findex Ada.Characters.Latin_1
1322 For a complete list of Latin-1 codes and their encodings, see the source
1323 file of library unit @code{Ada.Characters.Latin_1} in file
1324 @file{a-chlat1.ads}.
1325 You may use any of these extended characters freely in character or
1326 string literals. In addition, the extended characters that represent
1327 letters can be used in identifiers.
1328
1329 @node Other 8-Bit Codes
1330 @subsection Other 8-Bit Codes
1331
1332 @noindent
1333 GNAT also supports several other 8-bit coding schemes:
1334
1335 @table @asis
1336 @cindex Latin-2
1337 @item Latin-2
1338 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1339 equivalence.
1340
1341 @item Latin-3
1342 @cindex Latin-3
1343 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1344 equivalence.
1345
1346 @item Latin-4
1347 @cindex Latin-4
1348 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1349 equivalence.
1350
1351 @item Latin-5
1352 @cindex Latin-5
1353 @cindex Cyrillic
1354 Latin-4 letters (Cyrillic) allowed in identifiers, with uppercase and lowercase
1355 equivalence.
1356
1357 @item IBM PC (code page 437)
1358 @cindex code page 437
1359 This code page is the normal default for PCs in the U.S. It corresponds
1360 to the original IBM PC character set. This set has some, but not all, of
1361 the extended Latin-1 letters, but these letters do not have the same
1362 encoding as Latin-1. In this mode, these letters are allowed in
1363 identifiers with uppercase and lowercase equivalence.
1364
1365 @item IBM PC (code page 850)
1366 @cindex code page 850
1367 This code page is a modification of 437 extended to include all the
1368 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1369 mode, all these letters are allowed in identifiers with uppercase and
1370 lowercase equivalence.
1371
1372 @item Full Upper 8-bit
1373 Any character in the range 80-FF allowed in identifiers, and all are
1374 considered distinct. In other words, there are no uppercase and lowercase
1375 equivalences in this range. This is useful in conjunction with
1376 certain encoding schemes used for some foreign character sets (e.g.
1377 the typical method of representing Chinese characters on the PC).
1378
1379 @item No Upper-Half
1380 No upper-half characters in the range 80-FF are allowed in identifiers.
1381 This gives Ada 83 compatibility for identifier names.
1382 @end table
1383
1384 @noindent
1385 For precise data on the encodings permitted, and the uppercase and lowercase
1386 equivalences that are recognized, see the file @file{csets.adb} in
1387 the GNAT compiler sources. You will need to obtain a full source release
1388 of GNAT to obtain this file.
1389
1390 @node Wide Character Encodings
1391 @subsection Wide Character Encodings
1392
1393 @noindent
1394 GNAT allows wide character codes to appear in character and string
1395 literals, and also optionally in identifiers, by means of the following
1396 possible encoding schemes:
1397
1398 @table @asis
1399
1400 @item Hex Coding
1401 In this encoding, a wide character is represented by the following five
1402 character sequence:
1403
1404 @smallexample
1405 ESC a b c d
1406 @end smallexample
1407
1408 @noindent
1409 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1410 characters (using uppercase letters) of the wide character code. For
1411 example, ESC A345 is used to represent the wide character with code
1412 @code{16#A345#}.
1413 This scheme is compatible with use of the full Wide_Character set.
1414
1415 @item Upper-Half Coding
1416 @cindex Upper-Half Coding
1417 The wide character with encoding @code{16#abcd#} where the upper bit is on (in
1418 other words, "a" is in the range 8-F) is represented as two bytes,
1419 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1420 character, but is not required to be in the upper half. This method can
1421 be also used for shift-JIS or EUC, where the internal coding matches the
1422 external coding.
1423
1424 @item Shift JIS Coding
1425 @cindex Shift JIS Coding
1426 A wide character is represented by a two-character sequence,
1427 @code{16#ab#} and
1428 @code{16#cd#}, with the restrictions described for upper-half encoding as
1429 described above. The internal character code is the corresponding JIS
1430 character according to the standard algorithm for Shift-JIS
1431 conversion. Only characters defined in the JIS code set table can be
1432 used with this encoding method.
1433
1434 @item EUC Coding
1435 @cindex EUC Coding
1436 A wide character is represented by a two-character sequence
1437 @code{16#ab#} and
1438 @code{16#cd#}, with both characters being in the upper half. The internal
1439 character code is the corresponding JIS character according to the EUC
1440 encoding algorithm. Only characters defined in the JIS code set table
1441 can be used with this encoding method.
1442
1443 @item UTF-8 Coding
1444 A wide character is represented using
1445 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1446 10646-1/Am.2. Depending on the character value, the representation
1447 is a one, two, or three byte sequence:
1448 @smallexample
1449 @iftex
1450 @leftskip=.7cm
1451 @end iftex
1452 16#0000#-16#007f#: 2#0xxxxxxx#
1453 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1454 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1455
1456 @end smallexample
1457
1458 @noindent
1459 where the xxx bits correspond to the left-padded bits of the
1460 16-bit character value. Note that all lower half ASCII characters
1461 are represented as ASCII bytes and all upper half characters and
1462 other wide characters are represented as sequences of upper-half
1463 (The full UTF-8 scheme allows for encoding 31-bit characters as
1464 6-byte sequences, but in this implementation, all UTF-8 sequences
1465 of four or more bytes length will be treated as illegal).
1466 @item Brackets Coding
1467 In this encoding, a wide character is represented by the following eight
1468 character sequence:
1469
1470 @smallexample
1471 [ " a b c d " ]
1472 @end smallexample
1473
1474 @noindent
1475 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1476 characters (using uppercase letters) of the wide character code. For
1477 example, ["A345"] is used to represent the wide character with code
1478 @code{16#A345#}. It is also possible (though not required) to use the
1479 Brackets coding for upper half characters. For example, the code
1480 @code{16#A3#} can be represented as @code{["A3"]}.
1481
1482 This scheme is compatible with use of the full Wide_Character set,
1483 and is also the method used for wide character encoding in the standard
1484 ACVC (Ada Compiler Validation Capability) test suite distributions.
1485
1486 @end table
1487
1488 @noindent
1489 Note: Some of these coding schemes do not permit the full use of the
1490 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
1491 use of the upper half of the Latin-1 set.
1492
1493 @node File Naming Rules
1494 @section File Naming Rules
1495
1496 @noindent
1497 The default file name is determined by the name of the unit that the
1498 file contains. The name is formed by taking the full expanded name of
1499 the unit and replacing the separating dots with hyphens and using
1500 lowercase for all letters.
1501
1502 An exception arises if the file name generated by the above rules starts
1503 with one of the characters
1504 a,g,i, or s,
1505 and the second character is a
1506 minus. In this case, the character tilde is used in place
1507 of the minus. The reason for this special rule is to avoid clashes with
1508 the standard names for child units of the packages System, Ada,
1509 Interfaces, and GNAT, which use the prefixes
1510 s- a- i- and g-
1511 respectively.
1512
1513 The file extension is @file{.ads} for a spec and
1514 @file{.adb} for a body. The following list shows some
1515 examples of these rules.
1516
1517 @table @file
1518 @item main.ads
1519 Main (spec)
1520 @item main.adb
1521 Main (body)
1522 @item arith_functions.ads
1523 Arith_Functions (package spec)
1524 @item arith_functions.adb
1525 Arith_Functions (package body)
1526 @item func-spec.ads
1527 Func.Spec (child package spec)
1528 @item func-spec.adb
1529 Func.Spec (child package body)
1530 @item main-sub.adb
1531 Sub (subunit of Main)
1532 @item a~bad.adb
1533 A.Bad (child package body)
1534 @end table
1535
1536 @noindent
1537 Following these rules can result in excessively long
1538 file names if corresponding
1539 unit names are long (for example, if child units or subunits are
1540 heavily nested). An option is available to shorten such long file names
1541 (called file name "krunching"). This may be particularly useful when
1542 programs being developed with GNAT are to be used on operating systems
1543 with limited file name lengths. @xref{Using gnatkr}.
1544
1545 Of course, no file shortening algorithm can guarantee uniqueness over
1546 all possible unit names; if file name krunching is used, it is your
1547 responsibility to ensure no name clashes occur. Alternatively you
1548 can specify the exact file names that you want used, as described
1549 in the next section. Finally, if your Ada programs are migrating from a
1550 compiler with a different naming convention, you can use the gnatchop
1551 utility to produce source files that follow the GNAT naming conventions.
1552 (For details @pxref{Renaming Files Using gnatchop}.)
1553
1554 @node Using Other File Names
1555 @section Using Other File Names
1556 @cindex File names
1557
1558 @noindent
1559 In the previous section, we have described the default rules used by
1560 GNAT to determine the file name in which a given unit resides. It is
1561 often convenient to follow these default rules, and if you follow them,
1562 the compiler knows without being explicitly told where to find all
1563 the files it needs.
1564
1565 However, in some cases, particularly when a program is imported from
1566 another Ada compiler environment, it may be more convenient for the
1567 programmer to specify which file names contain which units. GNAT allows
1568 arbitrary file names to be used by means of the Source_File_Name pragma.
1569 The form of this pragma is as shown in the following examples:
1570 @cindex Source_File_Name pragma
1571
1572 @smallexample
1573 @group
1574 @cartouche
1575 @b{pragma} Source_File_Name (My_Utilities.Stacks,
1576   Spec_File_Name => "myutilst_a.ada");
1577 @b{pragma} Source_File_name (My_Utilities.Stacks,
1578   Body_File_Name => "myutilst.ada");
1579 @end cartouche
1580 @end group
1581 @end smallexample
1582
1583 @noindent
1584 As shown in this example, the first argument for the pragma is the unit
1585 name (in this example a child unit). The second argument has the form
1586 of a named association. The identifier
1587 indicates whether the file name is for a spec or a body;
1588 the file name itself is given by a string literal.
1589
1590 The source file name pragma is a configuration pragma, which means that
1591 normally it will be placed in the @file{gnat.adc}
1592 file used to hold configuration
1593 pragmas that apply to a complete compilation environment.
1594 For more details on how the @file{gnat.adc} file is created and used
1595 @pxref{Handling of Configuration Pragmas}
1596 @cindex @file{gnat.adc}
1597
1598 GNAT allows completely arbitrary file names to be specified using the
1599 source file name pragma. However, if the file name specified has an
1600 extension other than @file{.ads} or @file{.adb} it is necessary to use a special
1601 syntax when compiling the file. The name in this case must be preceded
1602 by the special sequence @code{-x} followed by a space and the name of the
1603 language, here @code{ada}, as in:
1604
1605 @smallexample
1606 $ gcc -c -x ada peculiar_file_name.sim
1607 @end smallexample
1608
1609 @noindent
1610 @code{gnatmake} handles non-standard file names in the usual manner (the
1611 non-standard file name for the main program is simply used as the
1612 argument to gnatmake). Note that if the extension is also non-standard,
1613 then it must be included in the gnatmake command, it may not be omitted.
1614
1615 @node Alternative File Naming Schemes
1616 @section Alternative File Naming Schemes
1617 @cindex File naming schemes, alternative
1618 @cindex File names
1619
1620 In the previous section, we described the use of the @code{Source_File_Name}
1621 pragma to allow arbitrary names to be assigned to individual source files.
1622 However, this approach requires one pragma for each file, and especially in
1623 large systems can result in very long @file{gnat.adc} files, and also create
1624 a maintenance problem.
1625
1626 GNAT also provides a facility for specifying systematic file naming schemes
1627 other than the standard default naming scheme previously described. An
1628 alternative scheme for naming is specified by the use of
1629 @code{Source_File_Name} pragmas having the following format:
1630 @cindex Source_File_Name pragma
1631
1632 @smallexample
1633 pragma Source_File_Name (
1634    Spec_File_Name  => FILE_NAME_PATTERN
1635  [,Casing          => CASING_SPEC]
1636  [,Dot_Replacement => STRING_LITERAL]);
1637
1638 pragma Source_File_Name (
1639    Body_File_Name  => FILE_NAME_PATTERN
1640  [,Casing          => CASING_SPEC]
1641  [,Dot_Replacement => STRING_LITERAL]);
1642
1643 pragma Source_File_Name (
1644    Subunit_File_Name  => FILE_NAME_PATTERN
1645  [,Casing             => CASING_SPEC]
1646  [,Dot_Replacement    => STRING_LITERAL]);
1647
1648 FILE_NAME_PATTERN ::= STRING_LITERAL
1649 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1650
1651 @end smallexample
1652
1653 @noindent
1654 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1655 It contains a single asterisk character, and the unit name is substituted
1656 systematically for this asterisk. The optional parameter
1657 @code{Casing} indicates
1658 whether the unit name is to be all upper-case letters, all lower-case letters,
1659 or mixed-case. If no
1660 @code{Casing} parameter is used, then the default is all
1661 lower-case.
1662
1663 The optional @code{Dot_Replacement} string is used to replace any periods
1664 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1665 argument is used then separating dots appear unchanged in the resulting
1666 file name.
1667 Although the above syntax indicates that the
1668 @code{Casing} argument must appear
1669 before the @code{Dot_Replacement} argument, but it
1670 is also permissible to write these arguments in the opposite order.
1671
1672 As indicated, it is possible to specify different naming schemes for
1673 bodies, specs, and subunits. Quite often the rule for subunits is the
1674 same as the rule for bodies, in which case, there is no need to give
1675 a separate @code{Subunit_File_Name} rule, and in this case the
1676 @code{Body_File_name} rule is used for subunits as well.
1677
1678 The separate rule for subunits can also be used to implement the rather
1679 unusual case of a compilation environment (e.g. a single directory) which
1680 contains a subunit and a child unit with the same unit name. Although
1681 both units cannot appear in the same partition, the Ada Reference Manual
1682 allows (but does not require) the possibility of the two units coexisting
1683 in the same environment.
1684
1685 The file name translation works in the following steps:
1686
1687 @itemize @bullet
1688
1689 @item
1690 If there is a specific @code{Source_File_Name} pragma for the given unit,
1691 then this is always used, and any general pattern rules are ignored.
1692
1693 @item
1694 If there is a pattern type @code{Source_File_Name} pragma that applies to
1695 the unit, then the resulting file name will be used if the file exists. If
1696 more than one pattern matches, the latest one will be tried first, and the
1697 first attempt resulting in a reference to a file that exists will be used.
1698
1699 @item
1700 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1701 for which the corresponding file exists, then the standard GNAT default
1702 naming rules are used.
1703
1704 @end itemize
1705
1706 @noindent
1707 As an example of the use of this mechanism, consider a commonly used scheme
1708 in which file names are all lower case, with separating periods copied
1709 unchanged to the resulting file name, and specs end with ".1.ada", and
1710 bodies end with ".2.ada". GNAT will follow this scheme if the following
1711 two pragmas appear:
1712
1713 @smallexample
1714 pragma Source_File_Name
1715   (Spec_File_Name => "*.1.ada");
1716 pragma Source_File_Name
1717   (Body_File_Name => "*.2.ada");
1718 @end smallexample
1719
1720 @noindent
1721 The default GNAT scheme is actually implemented by providing the following
1722 default pragmas internally:
1723
1724 @smallexample
1725 pragma Source_File_Name
1726   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1727 pragma Source_File_Name
1728   (Body_File_Name => "*.adb", Dot_Replacement => "-");
1729 @end smallexample
1730
1731 @noindent
1732 Our final example implements a scheme typically used with one of the
1733 Ada 83 compilers, where the separator character for subunits was "__"
1734 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1735 by adding @file{.ADA}, and subunits by
1736 adding @file{.SEP}. All file names were
1737 upper case. Child units were not present of course since this was an
1738 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1739 the same double underscore separator for child units.
1740
1741 @smallexample
1742 pragma Source_File_Name
1743   (Spec_File_Name => "*_.ADA",
1744    Dot_Replacement => "__",
1745    Casing = Uppercase);
1746 pragma Source_File_Name
1747   (Body_File_Name => "*.ADA",
1748    Dot_Replacement => "__",
1749    Casing = Uppercase);
1750 pragma Source_File_Name
1751   (Subunit_File_Name => "*.SEP",
1752    Dot_Replacement => "__",
1753    Casing = Uppercase);
1754 @end smallexample
1755
1756 @node Generating Object Files
1757 @section Generating Object Files
1758
1759 @noindent
1760 An Ada program consists of a set of source files, and the first step in
1761 compiling the program is to generate the corresponding object files.
1762 These are generated by compiling a subset of these source files.
1763 The files you need to compile are the following:
1764
1765 @itemize @bullet
1766 @item
1767 If a package spec has no body, compile the package spec to produce the
1768 object file for the package.
1769
1770 @item
1771 If a package has both a spec and a body, compile the body to produce the
1772 object file for the package. The source file for the package spec need
1773 not be compiled in this case because there is only one object file, which
1774 contains the code for both the spec and body of the package.
1775
1776 @item
1777 For a subprogram, compile the subprogram body to produce the object file
1778 for the subprogram. The spec, if one is present, is as usual in a
1779 separate file, and need not be compiled.
1780
1781 @item
1782 @cindex Subunits
1783 In the case of subunits, only compile the parent unit. A single object
1784 file is generated for the entire subunit tree, which includes all the
1785 subunits.
1786
1787 @item
1788 Compile child units independently of their parent units
1789 (though, of course, the spec of all the ancestor unit must be present in order
1790 to compile a child unit).
1791
1792 @item
1793 @cindex Generics
1794 Compile generic units in the same manner as any other units. The object
1795 files in this case are small dummy files that contain at most the
1796 flag used for elaboration checking. This is because GNAT always handles generic
1797 instantiation by means of macro expansion. However, it is still necessary to
1798 compile generic units, for dependency checking and elaboration purposes.
1799 @end itemize
1800
1801 @noindent
1802 The preceding rules describe the set of files that must be compiled to
1803 generate the object files for a program. Each object file has the same
1804 name as the corresponding source file, except that the extension is
1805 @file{.o} as usual.
1806
1807 You may wish to compile other files for the purpose of checking their
1808 syntactic and semantic correctness. For example, in the case where a
1809 package has a separate spec and body, you would not normally compile the
1810 spec. However, it is convenient in practice to compile the spec to make
1811 sure it is error-free before compiling clients of this spec, because such
1812 compilations will fail if there is an error in the spec.
1813
1814 GNAT provides an option for compiling such files purely for the
1815 purposes of checking correctness; such compilations are not required as
1816 part of the process of building a program. To compile a file in this
1817 checking mode, use the @option{-gnatc} switch.
1818
1819 @node Source Dependencies
1820 @section Source Dependencies
1821
1822 @noindent
1823 A given object file clearly depends on the source file which is compiled
1824 to produce it. Here we are using @dfn{depends} in the sense of a typical
1825 @code{make} utility; in other words, an object file depends on a source
1826 file if changes to the source file require the object file to be
1827 recompiled.
1828 In addition to this basic dependency, a given object may depend on
1829 additional source files as follows:
1830
1831 @itemize @bullet
1832 @item
1833 If a file being compiled @code{with}'s a unit @var{X}, the object file
1834 depends on the file containing the spec of unit @var{X}. This includes
1835 files that are @code{with}'ed implicitly either because they are parents
1836 of @code{with}'ed child units or they are run-time units required by the
1837 language constructs used in a particular unit.
1838
1839 @item
1840 If a file being compiled instantiates a library level generic unit, the
1841 object file depends on both the spec and body files for this generic
1842 unit.
1843
1844 @item
1845 If a file being compiled instantiates a generic unit defined within a
1846 package, the object file depends on the body file for the package as
1847 well as the spec file.
1848
1849 @item
1850 @findex Inline
1851 @cindex @option{-gnatn} switch
1852 If a file being compiled contains a call to a subprogram for which
1853 pragma @code{Inline} applies and inlining is activated with the
1854 @option{-gnatn} switch, the object file depends on the file containing the
1855 body of this subprogram as well as on the file containing the spec. Note
1856 that for inlining to actually occur as a result of the use of this switch,
1857 it is necessary to compile in optimizing mode.
1858
1859 @cindex @option{-gnatN} switch
1860 The use of @option{-gnatN} activates a more extensive inlining optimization
1861 that is performed by the front end of the compiler. This inlining does
1862 not require that the code generation be optimized. Like @option{-gnatn},
1863 the use of this switch generates additional dependencies.
1864
1865 @item
1866 If an object file O  depends on the proper body of a subunit through inlining
1867 or instantiation, it depends on the parent unit of the subunit. This means that
1868 any modification of the parent unit or one of its subunits affects the
1869 compilation of O.
1870
1871 @item
1872 The object file for a parent unit depends on all its subunit body files.
1873
1874 @item
1875 The previous two rules meant that for purposes of computing dependencies and
1876 recompilation, a body and all its subunits are treated as an indivisible whole.
1877
1878 @noindent
1879 These rules are applied transitively: if unit @code{A} @code{with}'s
1880 unit @code{B}, whose elaboration calls an inlined procedure in package
1881 @code{C}, the object file for unit @code{A} will depend on the body of
1882 @code{C}, in file @file{c.adb}.
1883
1884 The set of dependent files described by these rules includes all the
1885 files on which the unit is semantically dependent, as described in the
1886 Ada 95 Language Reference Manual. However, it is a superset of what the
1887 ARM describes, because it includes generic, inline, and subunit dependencies.
1888
1889 An object file must be recreated by recompiling the corresponding source
1890 file if any of the source files on which it depends are modified. For
1891 example, if the @code{make} utility is used to control compilation,
1892 the rule for an Ada object file must mention all the source files on
1893 which the object file depends, according to the above definition.
1894 The determination of the necessary
1895 recompilations is done automatically when one uses @code{gnatmake}.
1896 @end itemize
1897
1898 @node The Ada Library Information Files
1899 @section The Ada Library Information Files
1900 @cindex Ada Library Information files
1901 @cindex @file{ali} files
1902
1903 @noindent
1904 Each compilation actually generates two output files. The first of these
1905 is the normal object file that has a @file{.o} extension. The second is a
1906 text file containing full dependency information. It has the same
1907 name as the source file, but an @file{.ali} extension.
1908 This file is known as the Ada Library Information (@file{ali}) file.
1909 The following information is contained in the @file{ali} file.
1910
1911 @itemize @bullet
1912 @item
1913 Version information (indicates which version of GNAT was used to compile
1914 the unit(s) in question)
1915
1916 @item
1917 Main program information (including priority and time slice settings,
1918 as well as the wide character encoding used during compilation).
1919
1920 @item
1921 List of arguments used in the @code{gcc} command for the compilation
1922
1923 @item
1924 Attributes of the unit, including configuration pragmas used, an indication
1925 of whether the compilation was successful, exception model used etc.
1926
1927 @item
1928 A list of relevant restrictions applying to the unit (used for consistency)
1929 checking.
1930
1931 @item
1932 Categorization information (e.g. use of pragma @code{Pure}).
1933
1934 @item
1935 Information on all @code{with}'ed units, including presence of
1936 @code{Elaborate} or @code{Elaborate_All} pragmas.
1937
1938 @item
1939 Information from any @code{Linker_Options} pragmas used in the unit
1940
1941 @item
1942 Information on the use of @code{Body_Version} or @code{Version}
1943 attributes in the unit.
1944
1945 @item
1946 Dependency information. This is a list of files, together with
1947 time stamp and checksum information. These are files on which
1948 the unit depends in the sense that recompilation is required
1949 if any of these units are modified.
1950
1951 @item
1952 Cross-reference data. Contains information on all entities referenced
1953 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
1954 provide cross-reference information.
1955
1956 @end itemize
1957
1958 @noindent
1959 For a full detailed description of the format of the @file{ali} file,
1960 see the source of the body of unit @code{Lib.Writ}, contained in file
1961 @file{lib-writ.adb} in the GNAT compiler sources.
1962
1963 @node Binding an Ada Program
1964 @section Binding an Ada Program
1965
1966 @noindent
1967 When using languages such as C and C++, once the source files have been
1968 compiled the only remaining step in building an executable program
1969 is linking the object modules together. This means that it is possible to
1970 link an inconsistent version of a program, in which two units have
1971 included different versions of the same header.
1972
1973 The rules of Ada do not permit such an inconsistent program to be built.
1974 For example, if two clients have different versions of the same package,
1975 it is illegal to build a program containing these two clients.
1976 These rules are enforced by the GNAT binder, which also determines an
1977 elaboration order consistent with the Ada rules.
1978
1979 The GNAT binder is run after all the object files for a program have
1980 been created. It is given the name of the main program unit, and from
1981 this it determines the set of units required by the program, by reading the
1982 corresponding ALI files. It generates error messages if the program is
1983 inconsistent or if no valid order of elaboration exists.
1984
1985 If no errors are detected, the binder produces a main program, in Ada by
1986 default, that contains calls to the elaboration procedures of those
1987 compilation unit that require them, followed by
1988 a call to the main program. This Ada program is compiled to generate the
1989 object file for the main program. The name of
1990 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
1991 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
1992 main program unit.
1993
1994 Finally, the linker is used to build the resulting executable program,
1995 using the object from the main program from the bind step as well as the
1996 object files for the Ada units of the program.
1997
1998 @node Mixed Language Programming
1999 @section Mixed Language Programming
2000 @cindex Mixed Language Programming
2001
2002 @menu
2003 * Interfacing to C::
2004 * Calling Conventions::
2005 @end menu
2006
2007 @node Interfacing to C
2008 @subsection Interfacing to C
2009 @noindent
2010 There are two ways to
2011 build a program that contains some Ada files and some other language
2012 files depending on whether the main program is in Ada or not.
2013 If the main program is in Ada, you should proceed as follows:
2014
2015 @enumerate
2016 @item
2017 Compile the other language files to generate object files. For instance:
2018 @smallexample
2019 gcc -c file1.c
2020 gcc -c file2.c
2021 @end smallexample
2022
2023 @item
2024 Compile the Ada units to produce a set of object files and ALI
2025 files. For instance:
2026 @smallexample
2027 gnatmake -c my_main.adb
2028 @end smallexample
2029
2030 @item
2031 Run the Ada binder on the Ada main program. For instance:
2032 @smallexample
2033 gnatbind my_main.ali
2034 @end smallexample
2035
2036 @item
2037 Link the Ada main program, the Ada objects and the other language
2038 objects. For instance:
2039 @smallexample
2040 gnatlink my_main.ali file1.o file2.o
2041 @end smallexample
2042 @end enumerate
2043
2044 The three last steps can be grouped in a single command:
2045 @smallexample
2046 gnatmake my_main.adb -largs file1.o file2.o
2047 @end smallexample
2048
2049 @cindex Binder output file
2050 @noindent
2051 If the main program is in some language other than Ada, Then you may
2052 have more than one entry point in the Ada subsystem. You must use a
2053 special option of the binder to generate callable routines to initialize
2054 and finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2055 Calls to the initialization and finalization routines must be inserted in
2056 the main program, or some other appropriate point in the code. The call to
2057 initialize the Ada units must occur before the first Ada subprogram is
2058 called, and the call to finalize the Ada units must occur after the last
2059 Ada subprogram returns. You use the same procedure for building the
2060 program as described previously. In this case, however, the binder
2061 only places the initialization and finalization subprograms into file
2062 @file{b~@var{xxx}.adb} instead of the main program.
2063 So, if the main program is not in Ada, you should proceed as follows:
2064
2065 @enumerate
2066 @item
2067 Compile the other language files to generate object files. For instance:
2068 @smallexample
2069 gcc -c file1.c
2070 gcc -c file2.c
2071 @end smallexample
2072
2073 @item
2074 Compile the Ada units to produce a set of object files and ALI
2075 files. For instance:
2076 @smallexample
2077 gnatmake -c entry_point1.adb
2078 gnatmake -c entry_point2.adb
2079 @end smallexample
2080
2081 @item
2082 Run the Ada binder on the Ada main program. For instance:
2083 @smallexample
2084 gnatbind -n entry_point1.ali entry_point2.ali
2085 @end smallexample
2086
2087 @item
2088 Link the Ada main program, the Ada objects and the other language
2089 objects. You only need to give the last entry point here. For instance:
2090 @smallexample
2091 gnatlink entry_point2.ali file1.o file2.o
2092 @end smallexample
2093 @end enumerate
2094
2095 @node Calling Conventions
2096 @subsection Calling Conventions
2097 @cindex Foreign Languages
2098 @cindex Calling Conventions
2099 GNAT follows standard calling sequence conventions and will thus interface
2100 to any other language that also follows these conventions. The following
2101 Convention identifiers are recognized by GNAT:
2102
2103 @itemize @bullet
2104 @cindex Interfacing to Ada
2105 @cindex Other Ada compilers
2106 @cindex Convention Ada
2107 @item
2108 Ada. This indicates that the standard Ada calling sequence will be
2109 used and all Ada data items may be passed without any limitations in the
2110 case where GNAT is used to generate both the caller and callee. It is also
2111 possible to mix GNAT generated code and code generated by another Ada
2112 compiler. In this case, the data types should be restricted to simple
2113 cases, including primitive types. Whether complex data types can be passed
2114 depends on the situation. Probably it is safe to pass simple arrays, such
2115 as arrays of integers or floats. Records may or may not work, depending
2116 on whether both compilers lay them out identically. Complex structures
2117 involving variant records, access parameters, tasks, or protected types,
2118 are unlikely to be able to be passed.
2119
2120 Note that in the case of GNAT running
2121 on a platform that supports DEC Ada 83, a higher degree of compatibility
2122 can be guaranteed, and in particular records are layed out in an identical
2123 manner in the two compilers. Note also that if output from two different
2124 compilers is mixed, the program is responsible for dealing with elaboration
2125 issues. Probably the safest approach is to write the main program in the
2126 version of Ada other than GNAT, so that it takes care of its own elaboration
2127 requirements, and then call the GNAT-generated adainit procedure to ensure
2128 elaboration of the GNAT components. Consult the documentation of the other
2129 Ada compiler for further details on elaboration.
2130
2131 However, it is not possible to mix the tasking run time of GNAT and
2132 DEC Ada 83, All the tasking operations must either be entirely within
2133 GNAT compiled sections of the program, or entirely within DEC Ada 83
2134 compiled sections of the program.
2135
2136 @cindex Interfacing to Assembly
2137 @cindex Convention Assembler
2138 @item
2139 Assembler. Specifies assembler as the convention. In practice this has the
2140 same effect as convention Ada (but is not equivalent in the sense of being
2141 considered the same convention).
2142
2143 @cindex Convention Asm
2144 @findex Asm
2145 @item
2146 Asm. Equivalent to Assembler.
2147
2148 @cindex Convention Asm
2149 @findex Asm
2150 @item
2151 Asm. Equivalent to Assembly.
2152
2153 @cindex Interfacing to COBOL
2154 @cindex Convention COBOL
2155 @findex COBOL
2156 @item
2157 COBOL. Data will be passed according to the conventions described
2158 in section B.4 of the Ada 95 Reference Manual.
2159
2160 @findex C
2161 @cindex Interfacing to C
2162 @cindex Convention C
2163 @item
2164 C. Data will be passed according to the conventions described
2165 in section B.3 of the Ada 95 Reference Manual.
2166
2167 @cindex Convention Default
2168 @findex Default
2169 @item
2170 Default. Equivalent to C.
2171
2172 @cindex Convention External
2173 @findex External
2174 @item
2175 External. Equivalent to C.
2176
2177 @findex C++
2178 @cindex Interfacing to C++
2179 @cindex Convention C++
2180 @item
2181 CPP. This stands for C++. For most purposes this is identical to C.
2182 See the separate description of the specialized GNAT pragmas relating to
2183 C++ interfacing for further details.
2184
2185 @findex Fortran
2186 @cindex Interfacing to Fortran
2187 @cindex Convention Fortran
2188 @item
2189 Fortran. Data will be passed according to the conventions described
2190 in section B.5 of the Ada 95 Reference Manual.
2191
2192 @item
2193 Intrinsic. This applies to an intrinsic operation, as defined in the Ada 95
2194 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
2195 this means that the body of the subprogram is provided by the compiler itself,
2196 usually by means of an efficient code sequence, and that the user does not
2197 supply an explicit body for it. In an application program, the pragma can only
2198 be applied to the following two sets of names, which the GNAT compiler
2199 recognizes.
2200 @itemize @bullet
2201 @item
2202 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
2203 Arithmetic.  The corresponding subprogram declaration must have
2204 two formal parameters. The
2205 first one must be a signed integer type or a modular type with a binary
2206 modulus, and the second parameter must be of type Natural.
2207 The return type must be the same as the type of the first argument. The size
2208 of this type can only be 8, 16, 32, or 64.
2209 @item binary arithmetic operators: "+", "-", "*", "/"
2210 The corresponding operator declaration must have parameters and result type
2211 that have the same root numeric type (for example, all three are long_float
2212 types). This simplifies the definition of operations that use type checking
2213 to perform dimensional checks:
2214 @smallexample
2215 type Distance is new Long_Float;
2216 type Time     is new Long_Float;
2217 type Velocity is new Long_Float;
2218 function "/" (D : Distance; T : Time)
2219   return Velocity;
2220 pragma Import (Intrinsic, "/");
2221 @end smallexample
2222 @noindent
2223 This common idiom is often programmed with a generic definition and an explicit
2224 body. The pragma makes it simpler to introduce such declarations. It incurs
2225 no overhead in compilation time or code size, because it is implemented as a
2226 single machine instruction.
2227 @end itemize
2228 @noindent
2229
2230 @findex Stdcall
2231 @cindex Convention Stdcall
2232 @item
2233 Stdcall. This is relevant only to NT/Win95 implementations of GNAT,
2234 and specifies that the Stdcall calling sequence will be used, as defined
2235 by the NT API.
2236
2237 @findex DLL
2238 @cindex Convention DLL
2239 @item
2240 DLL. This is equivalent to Stdcall.
2241
2242 @findex Win32
2243 @cindex Convention Win32
2244 @item
2245 Win32. This is equivalent to Stdcall.
2246
2247 @findex Stubbed
2248 @cindex Convention Stubbed
2249 @item
2250 Stubbed. This is a special convention that indicates that the compiler
2251 should provide a stub body that raises @code{Program_Error}.
2252 @end itemize
2253
2254 @noindent
2255 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2256 that can be used to parametrize conventions and allow additional synonyms
2257 to be specified. For example if you have legacy code in which the convention
2258 identifier Fortran77 was used for Fortran, you can use the configuration
2259 pragma:
2260
2261 @smallexample
2262    pragma Convention_Identifier (Fortran77, Fortran);
2263 @end smallexample
2264
2265 @noindent
2266 And from now on the identifier Fortran77 may be used as a convention
2267 identifier (for example in an @code{Import} pragma) with the same
2268 meaning as Fortran.
2269
2270 @node Building Mixed Ada & C++ Programs
2271 @section Building Mixed Ada & C++ Programs
2272
2273 @noindent
2274 Building a mixed application containing both Ada and C++ code may be a
2275 challenge for the unaware programmer. As a matter of fact, this
2276 interfacing has not been standardized in the Ada 95 reference manual due
2277 to the immaturity and lack of standard of C++ at the time. This
2278 section gives a few hints that should make this task easier. In
2279 particular the first section addresses the differences with
2280 interfacing with C. The second section looks into the delicate problem
2281 of linking the complete application from its Ada and C++ parts. The last
2282 section give some hints on how the GNAT run time can be adapted in order
2283 to allow inter-language dispatching with a new C++ compiler.
2284
2285 @menu
2286 * Interfacing to C++::
2287 * Linking a Mixed C++ & Ada Program::
2288 * A Simple Example::
2289 * Adapting the Run Time to a New C++ Compiler::
2290 @end menu
2291
2292 @node Interfacing to C++
2293 @subsection Interfacing to C++
2294
2295 @noindent
2296 GNAT supports interfacing with C++ compilers generating code that is
2297 compatible with the standard Application Binary Interface of the given
2298 platform.
2299
2300 @noindent
2301 Interfacing can be done at 3 levels: simple data, subprograms and
2302 classes. In the first 2 cases, GNAT offer a specific @var{Convention
2303 CPP} that behaves exactly like @var{Convention C}. Usually C++ mangle
2304 names of subprograms and currently GNAT does not provide any help to
2305 solve the demangling problem. This problem can be addressed in 2 ways:
2306 @itemize @bullet
2307 @item
2308 by modifying the C++ code in order to force a C convention using
2309 the @var{extern "C"} syntax.
2310
2311 @item
2312 by figuring out the mangled name and use it as the Link_Name argument of
2313 the pragma import.
2314 @end itemize
2315
2316 @noindent
2317 Interfacing at the class level can be achieved by using the GNAT specific
2318 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
2319 Reference Manual for additional information.
2320
2321 @node Linking a Mixed C++ & Ada Program
2322 @subsection Linking a Mixed C++ & Ada Program
2323
2324 @noindent
2325 Usually the linker of the C++ development system must be used to link
2326 mixed applications because most C++ systems will resolve elaboration
2327 issues (such as calling constructors on global class instances)
2328 transparently during the link phase. GNAT has been adapted to ease the
2329 use of a foreign linker for the last phase. Three cases can be
2330 considered:
2331 @enumerate
2332
2333 @item
2334 Using GNAT and G++ (GNU C++ compiler) from the same GCC
2335 installation. The c++ linker can simply be called by using the c++
2336 specific driver called @code{c++}. Note that this setup is not
2337 very common because it may request recompiling the whole GCC
2338 tree from sources and it does not allow to upgrade easily to a new
2339 version of one compiler for one of the two languages without taking the
2340 risk of destabilizing the other.
2341
2342 @smallexample
2343 $ c++ -c file1.C
2344 $ c++ -c file2.C
2345 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
2346 @end smallexample
2347
2348 @item
2349 Using GNAT and G++ from 2 different GCC installations. If both compilers
2350 are on the PATH, the same method can be used. It is important to be
2351 aware that environment variables such as C_INCLUDE_PATH,
2352 GCC_EXEC_PREFIX, BINUTILS_ROOT or GCC_ROOT will affect both compilers at
2353 the same time and thus may make one of the 2 compilers operate
2354 improperly if they are set for the other. In particular it is important
2355 that the link command has access to the proper gcc library @file{libgcc.a},
2356 that is to say the one that is part of the C++ compiler
2357 installation. The implicit link command as suggested in the gnatmake
2358 command from the former example can be replaced by an explicit link
2359 command with full verbosity in order to verify which library is used:
2360 @smallexample
2361 $ gnatbind ada_unit
2362 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2363 @end smallexample
2364 If there is a problem due to interfering environment variables, it can
2365 be workaround by using an intermediate script. The following example
2366 shows the proper script to use when GNAT has not been installed at its
2367 default location and g++ has been installed at its default location:
2368
2369 @smallexample
2370 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2371 $ cat ./my_script
2372 #!/bin/sh
2373 unset BINUTILS_ROOT
2374 unset GCC_ROOT
2375 c++ $*
2376 @end smallexample
2377
2378 @item
2379 Using a non GNU C++ compiler. The same set of command as previously
2380 described can be used to insure that the c++ linker is
2381 used. Nonetheless, you need to add the path to libgcc explicitely, since some
2382 libraries needed by GNAT are located in this directory:
2383
2384 @smallexample
2385
2386 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2387 $ cat ./my_script
2388 #!/bin/sh
2389 CC $* `gcc -print-libgcc-file-name`
2390
2391 @end smallexample
2392
2393 Where CC is the name of the non GNU C++ compiler.
2394
2395 @end enumerate
2396
2397 @node A Simple Example
2398 @subsection  A Simple Example
2399 @noindent
2400 The following example, provided as part of the GNAT examples, show how
2401 to achieve procedural interfacing between Ada and C++ in both
2402 directions. The C++ class A has 2 methods. The first method is exported
2403 to Ada by the means of an extern C wrapper function. The second method
2404 calls an Ada subprogram. On the Ada side, The C++ calls is modelized by
2405 a limited record with a layout comparable to the C++ class. The Ada
2406 subprogram, in turn, calls the c++ method. So from the C++ main program
2407 the code goes back and forth between the 2 languages.
2408
2409 @noindent
2410 Here are the compilation commands
2411 for a GNAT VxWorks/PowerPC  configuration:
2412 @smallexample
2413 $ powerpc-wrs-vxworks-gnatmake -c simple_cpp_interface
2414 $ powerpc-wrs-vxworks-gnatbind -n simple_cpp_interface
2415 $ gnatlink simple_cpp_interface -o ada_part
2416 $ c++ppc -c -DCPU=PPC604  -I/usr/windppc/target/h  cpp_main.C
2417 $ c++ppc -c -DCPU=PPC604  -I/usr/windppc/target/h  ex7.C
2418 $ ldppc -r -o my_main my_main.o ex7.o ada_part
2419 @end smallexample
2420 @noindent
2421 Here are the corresponding sources:
2422 @smallexample
2423
2424 //cpp_main.C
2425
2426 #include "ex7.h"
2427
2428 extern "C" @{
2429   void adainit (void);
2430   void adafinal (void);
2431   void method1 (A *t);
2432 @}
2433
2434 void method1 (A *t)
2435 @{
2436   t->method1 ();
2437 @}
2438
2439 int main ()
2440 @{
2441   A obj;
2442   adainit ();
2443   obj.method2 (3030);
2444   adafinal ();
2445 @}
2446
2447 //ex7.h
2448
2449 class Origin @{
2450  public:
2451   int o_value;
2452 @};
2453 class A : public Origin @{
2454  public:
2455   void method1 (void);
2456   virtual void method2 (int v);
2457   A();
2458   int   a_value;
2459 @};
2460
2461 //ex7.C
2462
2463 #include "ex7.h"
2464 #include <stdio.h>
2465
2466 extern "C" @{ void ada_method2 (A *t, int v);@}
2467
2468 void A::method1 (void)
2469 @{
2470   a_value = 2020;
2471   printf ("in A::method1, a_value = %d \n",a_value);
2472
2473 @}
2474
2475 void A::method2 (int v)
2476 @{
2477    ada_method2 (this, v);
2478    printf ("in A::method2, a_value = %d \n",a_value);
2479
2480 @}
2481
2482 A::A(void)
2483 @{
2484    a_value = 1010;
2485   printf ("in A::A, a_value = %d \n",a_value);
2486 @}
2487
2488 -- Ada sources
2489 @b{package} @b{body} Simple_Cpp_Interface @b{is}
2490
2491    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
2492    @b{begin}
2493       Method1 (This);
2494       This.A_Value := V;
2495    @b{end} Ada_Method2;
2496
2497 @b{end} Simple_Cpp_Interface;
2498
2499 @b{package} Simple_Cpp_Interface @b{is}
2500    @b{type} A @b{is} @b{limited}
2501       @b{record}
2502          O_Value : Integer;
2503          A_Value : Integer;
2504       @b{end} @b{record};
2505    @b{pragma} Convention (C, A);
2506
2507    @b{procedure} Method1 (This : @b{in} @b{out} A);
2508    @b{pragma} Import (C, Method1);
2509
2510    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
2511    @b{pragma} Export (C, Ada_Method2);
2512
2513 @b{end} Simple_Cpp_Interface;
2514 @end smallexample
2515
2516 @node Adapting the Run Time to a New C++ Compiler
2517 @subsection Adapting the Run Time to a New C++ Compiler
2518 @noindent
2519 GNAT offers the capability to derive Ada 95 tagged types directly from
2520 preexisting C++ classes and . See "Interfacing with C++" in the GNAT
2521 reference manual. The mechanism used by GNAT for achieving such a goal
2522 has been made user configurable through a GNAT library unit
2523 @code{Interfaces.CPP}. The default version of this file is adapted to
2524 the GNU c++ compiler. Internal knowledge of the virtual
2525 table layout used by the new C++ compiler is needed to configure
2526 properly this unit. The Interface of this unit is known by the compiler
2527 and cannot be changed except for the value of the constants defining the
2528 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
2529 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
2530 of this unit for more details.
2531
2532 @node Comparison between GNAT and C/C++ Compilation Models
2533 @section Comparison between GNAT and C/C++ Compilation Models
2534
2535 @noindent
2536 The GNAT model of compilation is close to the C and C++ models. You can
2537 think of Ada specs as corresponding to header files in C. As in C, you
2538 don't need to compile specs; they are compiled when they are used. The
2539 Ada @code{with} is similar in effect to the @code{#include} of a C
2540 header.
2541
2542 One notable difference is that, in Ada, you may compile specs separately
2543 to check them for semantic and syntactic accuracy. This is not always
2544 possible with C headers because they are fragments of programs that have
2545 less specific syntactic or semantic rules.
2546
2547 The other major difference is the requirement for running the binder,
2548 which performs two important functions. First, it checks for
2549 consistency. In C or C++, the only defense against assembling
2550 inconsistent programs lies outside the compiler, in a makefile, for
2551 example. The binder satisfies the Ada requirement that it be impossible
2552 to construct an inconsistent program when the compiler is used in normal
2553 mode.
2554
2555 @cindex Elaboration order control
2556 The other important function of the binder is to deal with elaboration
2557 issues. There are also elaboration issues in C++ that are handled
2558 automatically. This automatic handling has the advantage of being
2559 simpler to use, but the C++ programmer has no control over elaboration.
2560 Where @code{gnatbind} might complain there was no valid order of
2561 elaboration, a C++ compiler would simply construct a program that
2562 malfunctioned at run time.
2563
2564 @node Comparison between GNAT and Conventional Ada Library Models
2565 @section Comparison between GNAT and Conventional Ada Library Models
2566
2567 @noindent
2568 This section is intended to be useful to Ada programmers who have
2569 previously used an Ada compiler implementing the traditional Ada library
2570 model, as described in the Ada 95 Language Reference Manual. If you
2571 have not used such a system, please go on to the next section.
2572
2573 @cindex GNAT library
2574 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
2575 source files themselves acts as the library. Compiling Ada programs does
2576 not generate any centralized information, but rather an object file and
2577 a ALI file, which are of interest only to the binder and linker.
2578 In a traditional system, the compiler reads information not only from
2579 the source file being compiled, but also from the centralized library.
2580 This means that the effect of a compilation depends on what has been
2581 previously compiled. In particular:
2582
2583 @itemize @bullet
2584 @item
2585 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2586 to the version of the unit most recently compiled into the library.
2587
2588 @item
2589 Inlining is effective only if the necessary body has already been
2590 compiled into the library.
2591
2592 @item
2593 Compiling a unit may obsolete other units in the library.
2594 @end itemize
2595
2596 @noindent
2597 In GNAT, compiling one unit never affects the compilation of any other
2598 units because the compiler reads only source files. Only changes to source
2599 files can affect the results of a compilation. In particular:
2600
2601 @itemize @bullet
2602 @item
2603 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2604 to the source version of the unit that is currently accessible to the
2605 compiler.
2606
2607 @item
2608 @cindex Inlining
2609 Inlining requires the appropriate source files for the package or
2610 subprogram bodies to be available to the compiler. Inlining is always
2611 effective, independent of the order in which units are complied.
2612
2613 @item
2614 Compiling a unit never affects any other compilations. The editing of
2615 sources may cause previous compilations to be out of date if they
2616 depended on the source file being modified.
2617 @end itemize
2618
2619 @noindent
2620 The most important result of these differences is that order of compilation
2621 is never significant in GNAT. There is no situation in which one is
2622 required to do one compilation before another. What shows up as order of
2623 compilation requirements in the traditional Ada library becomes, in
2624 GNAT, simple source dependencies; in other words, there is only a set
2625 of rules saying what source files must be present when a file is
2626 compiled.
2627
2628 @node Compiling Using gcc
2629 @chapter Compiling Using @code{gcc}
2630
2631 @noindent
2632 This chapter discusses how to compile Ada programs using the @code{gcc}
2633 command. It also describes the set of switches
2634 that can be used to control the behavior of the compiler.
2635 @menu
2636 * Compiling Programs::
2637 * Switches for gcc::
2638 * Search Paths and the Run-Time Library (RTL)::
2639 * Order of Compilation Issues::
2640 * Examples::
2641 @end menu
2642
2643 @node Compiling Programs
2644 @section Compiling Programs
2645
2646 @noindent
2647 The first step in creating an executable program is to compile the units
2648 of the program using the @code{gcc} command. You must compile the
2649 following files:
2650
2651 @itemize @bullet
2652 @item
2653 the body file (@file{.adb}) for a library level subprogram or generic
2654 subprogram
2655
2656 @item
2657 the spec file (@file{.ads}) for a library level package or generic
2658 package that has no body
2659
2660 @item
2661 the body file (@file{.adb}) for a library level package
2662 or generic package that has a body
2663
2664 @end itemize
2665
2666 @noindent
2667 You need @emph{not} compile the following files
2668
2669 @itemize @bullet
2670
2671 @item
2672 the spec of a library unit which has a body
2673
2674 @item
2675 subunits
2676 @end itemize
2677
2678 @noindent
2679 because they are compiled as part of compiling related units. GNAT
2680 package specs
2681 when the corresponding body is compiled, and subunits when the parent is
2682 compiled.
2683 @cindex No code generated
2684 If you attempt to compile any of these files, you will get one of the
2685 following error messages (where fff is the name of the file you compiled):
2686
2687 @smallexample
2688 No code generated for file @var{fff} (@var{package spec})
2689 No code generated for file @var{fff} (@var{subunit})
2690 @end smallexample
2691
2692 @noindent
2693 The basic command for compiling a file containing an Ada unit is
2694
2695 @smallexample
2696 $ gcc -c [@var{switches}] @file{file name}
2697 @end smallexample
2698
2699 @noindent
2700 where @var{file name} is the name of the Ada file (usually
2701 having an extension
2702 @file{.ads} for a spec or @file{.adb} for a body).
2703 You specify the
2704 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
2705 The result of a successful compilation is an object file, which has the
2706 same name as the source file but an extension of @file{.o} and an Ada
2707 Library Information (ALI) file, which also has the same name as the
2708 source file, but with @file{.ali} as the extension. GNAT creates these
2709 two output files in the current directory, but you may specify a source
2710 file in any directory using an absolute or relative path specification
2711 containing the directory information.
2712
2713 @findex gnat1
2714 @code{gcc} is actually a driver program that looks at the extensions of
2715 the file arguments and loads the appropriate compiler. For example, the
2716 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
2717 These programs are in directories known to the driver program (in some
2718 configurations via environment variables you set), but need not be in
2719 your path. The @code{gcc} driver also calls the assembler and any other
2720 utilities needed to complete the generation of the required object
2721 files.
2722
2723 It is possible to supply several file names on the same @code{gcc}
2724 command. This causes @code{gcc} to call the appropriate compiler for
2725 each file. For example, the following command lists three separate
2726 files to be compiled:
2727
2728 @smallexample
2729 $ gcc -c x.adb y.adb z.c
2730 @end smallexample
2731
2732 @noindent
2733 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
2734 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
2735 The compiler generates three object files @file{x.o}, @file{y.o} and
2736 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
2737 Ada compilations. Any switches apply to all the files listed,
2738 except for
2739 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
2740
2741 @node Switches for gcc
2742 @section Switches for @code{gcc}
2743
2744 @noindent
2745 The @code{gcc} command accepts switches that control the
2746 compilation process. These switches are fully described in this section.
2747 First we briefly list all the switches, in alphabetical order, then we
2748 describe the switches in more detail in functionally grouped sections.
2749
2750 @menu
2751 * Output and Error Message Control::
2752 * Debugging and Assertion Control::
2753 * Run-Time Checks::
2754 * Stack Overflow Checking::
2755 * Run-Time Control::
2756 * Validity Checking::
2757 * Style Checking::
2758 * Using gcc for Syntax Checking::
2759 * Using gcc for Semantic Checking::
2760 * Compiling Ada 83 Programs::
2761 * Character Set Control::
2762 * File Naming Control::
2763 * Subprogram Inlining Control::
2764 * Auxiliary Output Control::
2765 * Debugging Control::
2766 * Units to Sources Mapping Files::
2767 @end menu
2768
2769 @table @code
2770 @cindex @code{-b} (@code{gcc})
2771 @item -b @var{target}
2772 Compile your program to run on @var{target}, which is the name of a
2773 system configuration. You must have a GNAT cross-compiler built if
2774 @var{target} is not the same as your host system.
2775
2776 @item -B@var{dir}
2777 @cindex @code{-B} (@code{gcc})
2778 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
2779 from @var{dir} instead of the default location. Only use this switch
2780 when multiple versions of the GNAT compiler are available. See the
2781 @code{gcc} manual page for further details. You would normally use the
2782 @code{-b} or @code{-V} switch instead.
2783
2784 @item -c
2785 @cindex @code{-c} (@code{gcc})
2786 Compile. Always use this switch when compiling Ada programs.
2787
2788 Note: for some other languages when using @code{gcc}, notably in
2789 the case of C and C++, it is possible to use
2790 use @code{gcc} without a @code{-c} switch to
2791 compile and link in one step. In the case of GNAT, you
2792 cannot use this approach, because the binder must be run
2793 and @code{gcc} cannot be used to run the GNAT binder.
2794
2795 @item -g
2796 @cindex @code{-g} (@code{gcc})
2797 Generate debugging information. This information is stored in the object
2798 file and copied from there to the final executable file by the linker,
2799 where it can be read by the debugger. You must use the
2800 @code{-g} switch if you plan on using the debugger.
2801
2802 @item -I@var{dir}
2803 @cindex @code{-I} (@code{gcc})
2804 @cindex RTL
2805 Direct GNAT to search the @var{dir} directory for source files needed by
2806 the current compilation
2807 (@pxref{Search Paths and the Run-Time Library (RTL)}).
2808
2809 @item -I-
2810 @cindex @code{-I-} (@code{gcc})
2811 @cindex RTL
2812 Except for the source file named in the command line, do not look for source files
2813 in the directory containing the source file named in the command line
2814 (@pxref{Search Paths and the Run-Time Library (RTL)}).
2815
2816 @item -o @var{file}
2817 @cindex @code{-o} (@code{gcc})
2818 This switch is used in @code{gcc} to redirect the generated object file
2819 and its associated ALI file. Beware of this switch with GNAT, because it may
2820 cause the object file and ALI file to have different names which in turn
2821 may confuse the binder and the linker.
2822
2823 @item -O[@var{n}]
2824 @cindex @code{-O} (@code{gcc})
2825 @var{n} controls the optimization level.
2826
2827 @table @asis
2828 @item n = 0
2829 No optimization, the default setting if no @code{-O} appears
2830
2831 @item n = 1
2832 Normal optimization, the default if you specify @code{-O} without
2833 an operand.
2834
2835 @item n = 2
2836 Extensive optimization
2837
2838 @item n = 3
2839 Extensive optimization with automatic inlining. This applies only to
2840 inlining within a unit. For details on control of inter-unit inlining
2841 see @xref{Subprogram Inlining Control}.
2842 @end table
2843
2844
2845 @item --RTS=@var{rts-path}
2846 @cindex @code{--RTS} (@code{gcc})
2847 Specifies the default location of the runtime library. Same meaning as the
2848 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
2849
2850 @item -S
2851 @cindex @code{-S} (@code{gcc})
2852 Used in place of @code{-c} to
2853 cause the assembler source file to be
2854 generated, using @file{.s} as the extension,
2855 instead of the object file.
2856 This may be useful if you need to examine the generated assembly code.
2857
2858 @item -v
2859 @cindex @code{-v} (@code{gcc})
2860 Show commands generated by the @code{gcc} driver. Normally used only for
2861 debugging purposes or if you need to be sure what version of the
2862 compiler you are executing.
2863
2864 @item -V @var{ver}
2865 @cindex @code{-V} (@code{gcc})
2866 Execute @var{ver} version of the compiler. This is the @code{gcc}
2867 version, not the GNAT version.
2868
2869 @item -gnata
2870 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
2871 activated.
2872
2873 @item -gnatA
2874 Avoid processing @file{gnat.adc}. If a gnat.adc file is present, it will be ignored.
2875
2876 @item -gnatb
2877 Generate brief messages to @file{stderr} even if verbose mode set.
2878
2879 @item -gnatc
2880 Check syntax and semantics only (no code generation attempted).
2881
2882 @item -gnatC
2883 Compress debug information and external symbol name table entries.
2884
2885 @item -gnatD
2886 Output expanded source files for source level debugging. This switch
2887 also suppress generation of cross-reference information (see -gnatx).
2888
2889 @item -gnatec@var{path}
2890 Specify a configuration pragma file. (see @ref{The Configuration Pragmas Files})
2891
2892 @item -gnatem@var{path}
2893 Specify a mapping file. (see @ref{Units to Sources Mapping Files})
2894
2895 @item -gnatE
2896 Full dynamic elaboration checks.
2897
2898 @item -gnatf
2899 Full errors. Multiple errors per line, all undefined references.
2900
2901 @item -gnatF
2902 Externals names are folded to all uppercase.
2903
2904 @item -gnatg
2905 Internal GNAT implementation mode. This should not be used for
2906 applications programs, it is intended only for use by the compiler
2907 and its run-time library. For documentation, see the GNAT sources.
2908
2909 @item -gnatG
2910 List generated expanded code in source form.
2911
2912 @item -gnati@var{c}
2913 Identifier character set
2914 (@var{c}=1/2/3/4/8/9/p/f/n/w).
2915
2916 @item -gnath
2917 Output usage information. The output is written to @file{stdout}.
2918
2919 @item -gnatk@var{n}
2920 Limit file names to @var{n} (1-999) characters (@code{k} = krunch).
2921
2922 @item -gnatl
2923 Output full source listing with embedded error messages.
2924
2925 @item -gnatm@var{n}
2926 Limit number of detected errors to @var{n} (1-999).
2927
2928 @item -gnatn
2929 Activate inlining across unit boundaries for subprograms for which
2930 pragma @code{inline} is specified.
2931
2932 @item -gnatN
2933 Activate front end inlining.
2934
2935 @item -fno-inline
2936 Suppresses all inlining, even if other optimization or inlining switches
2937 are set.
2938
2939 @item -fstack-check
2940 Activates stack checking. See separate section on stack checking for
2941 details of the use of this option.
2942
2943 @item -gnato
2944 Enable numeric overflow checking (which is not normally enabled by
2945 default). Not that division by zero is a separate check that is not
2946 controlled by this switch (division by zero checking is on by default).
2947
2948 @item -gnatp
2949 Suppress all checks.
2950
2951 @item -gnatq
2952 Don't quit; try semantics, even if parse errors.
2953
2954 @item -gnatQ
2955 Don't quit; generate @file{ali} and tree files even if illegalities.
2956
2957 @item -gnatP
2958 Enable polling. This is required on some systems (notably Windows NT) to
2959 obtain asynchronous abort and asynchronous transfer of control capability.
2960 See the description of pragma Polling in the GNAT Reference Manual for
2961 full details.
2962
2963 @item -gnatR[0/1/2/3][s]
2964 Output representation information for declared types and objects.
2965
2966 @item -gnats
2967 Syntax check only.
2968
2969 @item -gnatt
2970 Tree output file to be generated.
2971
2972 @item -gnatT nnn
2973 Set time slice to specified number of microseconds
2974
2975 @item -gnatu
2976 List units for this compilation.
2977
2978 @item -gnatU
2979 Tag all error messages with the unique string "error:"
2980
2981 @item -gnatv
2982 Verbose mode. Full error output with source lines to @file{stdout}.
2983
2984 @item -gnatV
2985 Control level of validity checking. See separate section describing
2986 this feature.
2987
2988 @item -gnatwxxx@var{xxx}
2989 Warning mode where
2990 @var{xxx} is a string of options describing the exact warnings that
2991 are enabled or disabled. See separate section on warning control.
2992
2993 @item -gnatW@var{e}
2994 Wide character encoding method
2995 (@var{e}=n/h/u/s/e/8).
2996
2997 @item -gnatx
2998 Suppress generation of cross-reference information.
2999
3000 @item -gnaty
3001 Enable built-in style checks. See separate section describing this feature.
3002
3003 @item -gnatz@var{m}
3004 Distribution stub generation and compilation
3005 (@var{m}=r/c for receiver/caller stubs).
3006
3007 @item -gnat83
3008 Enforce Ada 83 restrictions.
3009
3010 @item -pass-exit-codes
3011 Catch exit codes from the compiler and use the most meaningful as
3012 exit status.
3013 @end table
3014
3015 You may combine a sequence of GNAT switches into a single switch. For
3016 example, the combined switch
3017
3018 @cindex Combining GNAT switches
3019 @smallexample
3020 -gnatofi3
3021 @end smallexample
3022
3023 @noindent
3024 is equivalent to specifying the following sequence of switches:
3025
3026 @smallexample
3027 -gnato -gnatf -gnati3
3028 @end smallexample
3029
3030 @noindent
3031 The following restrictions apply to the combination of switches
3032 in this manner:
3033
3034 @itemize @bullet
3035 @item
3036 The switch @option{-gnatc} if combined with other switches must come
3037 first in the string.
3038
3039 @item
3040 The switch @option{-gnats} if combined with other switches must come
3041 first in the string.
3042
3043 @item
3044 Once a "y" appears in the string (that is a use of the @option{-gnaty}
3045 switch), then all further characters in the switch are interpreted
3046 as style modifiers (see description of @option{-gnaty}).
3047
3048 @item
3049 Once a "d" appears in the string (that is a use of the @option{-gnatd}
3050 switch), then all further characters in the switch are interpreted
3051 as debug flags (see description of @option{-gnatd}).
3052
3053 @item
3054 Once a "w" appears in the string (that is a use of the @option{-gnatw}
3055 switch), then all further characters in the switch are interpreted
3056 as warning mode modifiers (see description of @option{-gnatw}).
3057
3058 @item
3059 Once a "V" appears in the string (that is a use of the @option{-gnatV}
3060 switch), then all further characters in the switch are interpreted
3061 as validity checking options (see description of @option{-gnatV}).
3062
3063 @end itemize
3064
3065 @node Output and Error Message Control
3066 @subsection Output and Error Message Control
3067 @findex stderr
3068
3069 @noindent
3070 The standard default format for error messages is called "brief format."
3071 Brief format messages are written to @file{stderr} (the standard error
3072 file) and have the following form:
3073
3074 @smallexample
3075 @iftex
3076 @leftskip=.7cm
3077 @end iftex
3078 e.adb:3:04: Incorrect spelling of keyword "function"
3079 e.adb:4:20: ";" should be "is"
3080 @end smallexample
3081
3082 @noindent
3083 The first integer after the file name is the line number in the file,
3084 and the second integer is the column number within the line.
3085 @code{glide} can parse the error messages
3086 and point to the referenced character.
3087 The following switches provide control over the error message
3088 format:
3089
3090 @table @code
3091 @item -gnatv
3092 @cindex @option{-gnatv} (@code{gcc})
3093 @findex stdout
3094 The v stands for verbose.
3095 The effect of this setting is to write long-format error
3096 messages to @file{stdout} (the standard output file.
3097 The same program compiled with the
3098 @option{-gnatv} switch would generate:
3099
3100 @smallexample
3101 @group
3102 @cartouche
3103 3. funcion X (Q : Integer)
3104    |
3105 >>> Incorrect spelling of keyword "function"
3106 4. return Integer;
3107                  |
3108 >>> ";" should be "is"
3109 @end cartouche
3110 @end group
3111 @end smallexample
3112
3113 @noindent
3114 The vertical bar indicates the location of the error, and the @samp{>>>}
3115 prefix can be used to search for error messages. When this switch is
3116 used the only source lines output are those with errors.
3117
3118 @item -gnatl
3119 @cindex @option{-gnatl} (@code{gcc})
3120 The @code{l} stands for list.
3121 This switch causes a full listing of
3122 the file to be generated. The output might look as follows:
3123
3124 @smallexample
3125 @group
3126 @cartouche
3127  1. procedure E is
3128  2.    V : Integer;
3129  3.    funcion X (Q : Integer)
3130        |
3131     >>> Incorrect spelling of keyword "function"
3132  4.     return Integer;
3133                       |
3134     >>> ";" should be "is"
3135  5.    begin
3136  6.       return Q + Q;
3137  7.    end;
3138  8. begin
3139  9.    V := X + X;
3140 10.end E;
3141 @end cartouche
3142 @end group
3143 @end smallexample
3144
3145 @noindent
3146 @findex stderr
3147 When you specify the @option{-gnatv} or @option{-gnatl} switches and
3148 standard output is redirected, a brief summary is written to
3149 @file{stderr} (standard error) giving the number of error messages and
3150 warning messages generated.
3151
3152 @item -gnatU
3153 @cindex @option{-gnatU} (@code{gcc})
3154 This switch forces all error messages to be preceded by the unique
3155 string "error:". This means that error messages take a few more
3156 characters in space, but allows easy searching for and identification
3157 of error messages.
3158
3159 @item -gnatb
3160 @cindex @option{-gnatb} (@code{gcc})
3161 The @code{b} stands for brief.
3162 This switch causes GNAT to generate the
3163 brief format error messages to @file{stderr} (the standard error
3164 file) as well as the verbose
3165 format message or full listing (which as usual is written to
3166 @file{stdout} (the standard output file).
3167
3168 @item -gnatm@var{n}
3169 @cindex @option{-gnatm} (@code{gcc})
3170 The @code{m} stands for maximum.
3171 @var{n} is a decimal integer in the
3172 range of 1 to 999 and limits the number of error messages to be
3173 generated. For example, using @option{-gnatm2} might yield
3174
3175 @smallexample
3176 @iftex
3177 @leftskip=.7cm
3178 @end iftex
3179 e.adb:3:04: Incorrect spelling of keyword "function"
3180 e.adb:5:35: missing ".."
3181 fatal error: maximum errors reached
3182 compilation abandoned
3183 @end smallexample
3184
3185 @item -gnatf
3186 @cindex @option{-gnatf} (@code{gcc})
3187 @cindex Error messages, suppressing
3188 The @code{f} stands for full.
3189 Normally, the compiler suppresses error messages that are likely to be
3190 redundant. This switch causes all error
3191 messages to be generated. In particular, in the case of
3192 references to undefined variables. If a given variable is referenced
3193 several times, the normal format of messages is
3194 @smallexample
3195 @iftex
3196 @leftskip=.7cm
3197 @end iftex
3198 e.adb:7:07: "V" is undefined (more references follow)
3199 @end smallexample
3200
3201 @noindent
3202 where the parenthetical comment warns that there are additional
3203 references to the variable @code{V}. Compiling the same program with the
3204 @option{-gnatf} switch yields
3205
3206 @smallexample
3207 e.adb:7:07: "V" is undefined
3208 e.adb:8:07: "V" is undefined
3209 e.adb:8:12: "V" is undefined
3210 e.adb:8:16: "V" is undefined
3211 e.adb:9:07: "V" is undefined
3212 e.adb:9:12: "V" is undefined
3213 @end smallexample
3214
3215 @item -gnatq
3216 @cindex @option{-gnatq} (@code{gcc})
3217 The @code{q} stands for quit (really "don't quit").
3218 In normal operation mode, the compiler first parses the program and
3219 determines if there are any syntax errors. If there are, appropriate
3220 error messages are generated and compilation is immediately terminated.
3221 This switch tells
3222 GNAT to continue with semantic analysis even if syntax errors have been
3223 found. This may enable the detection of more errors in a single run. On
3224 the other hand, the semantic analyzer is more likely to encounter some
3225 internal fatal error when given a syntactically invalid tree.
3226
3227 @item -gnatQ
3228 In normal operation mode, the @file{ali} file is not generated if any
3229 illegalities are detected in the program. The use of @option{-gnatQ} forces
3230 generation of the @file{ali} file. This file is marked as being in
3231 error, so it cannot be used for binding purposes, but it does contain
3232 reasonably complete cross-reference information, and thus may be useful
3233 for use by tools (e.g. semantic browsing tools or integrated development
3234 environments) that are driven from the @file{ali} file.
3235
3236 In addition, if @option{-gnatt} is also specified, then the tree file is
3237 generated even if there are illegalities. It may be useful in this case
3238 to also specify @option{-gnatq} to ensure that full semantic processing
3239 occurs. The resulting tree file can be processed by ASIS, for the purpose
3240 of providing partial information about illegal units, but if the error
3241 causes the tree to be badly malformed, then ASIS may crash during the
3242 analysis.
3243
3244 @end table
3245
3246 @noindent
3247 In addition to error messages, which correspond to illegalities as defined
3248 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
3249 situations.
3250
3251 @cindex Warning messages
3252 First, the compiler considers some constructs suspicious and generates a
3253 warning message to alert you to a possible error. Second, if the
3254 compiler detects a situation that is sure to raise an exception at
3255 run time, it generates a warning message. The following shows an example
3256 of warning messages:
3257 @smallexample
3258 @iftex
3259 @leftskip=.2cm
3260 @end iftex
3261 e.adb:4:24: warning: creation of object may raise Storage_Error
3262 e.adb:10:17: warning: static value out of range
3263 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
3264
3265 @end smallexample
3266
3267 @noindent
3268 GNAT considers a large number of situations as appropriate
3269 for the generation of warning messages. As always, warnings are not
3270 definite indications of errors. For example, if you do an out-of-range
3271 assignment with the deliberate intention of raising a
3272 @code{Constraint_Error} exception, then the warning that may be
3273 issued does not indicate an error. Some of the situations for which GNAT
3274 issues warnings (at least some of the time) are given in the following
3275 list, which is not necessarily complete.
3276
3277 @itemize @bullet
3278 @item
3279 Possible infinitely recursive calls
3280
3281 @item
3282 Out-of-range values being assigned
3283
3284 @item
3285 Possible order of elaboration problems
3286
3287 @item
3288 Unreachable code
3289
3290 @item
3291 Fixed-point type declarations with a null range
3292
3293 @item
3294 Variables that are never assigned a value
3295
3296 @item
3297 Variables that are referenced before being initialized
3298
3299 @item
3300 Task entries with no corresponding accept statement
3301
3302 @item
3303 Duplicate accepts for the same task entry in a select
3304
3305 @item
3306 Objects that take too much storage
3307
3308 @item
3309 Unchecked conversion between types of differing sizes
3310
3311 @item
3312 Missing return statements along some execution paths in a function
3313
3314 @item
3315 Incorrect (unrecognized) pragmas
3316
3317 @item
3318 Incorrect external names
3319
3320 @item
3321 Allocation from empty storage pool
3322
3323 @item
3324 Potentially blocking operations in protected types
3325
3326 @item
3327 Suspicious parenthesization of expressions
3328
3329 @item
3330 Mismatching bounds in an aggregate
3331
3332 @item
3333 Attempt to return local value by reference
3334
3335 @item
3336 Unrecognized pragmas
3337
3338 @item
3339 Premature instantiation of a generic body
3340
3341 @item
3342 Attempt to pack aliased components
3343
3344 @item
3345 Out of bounds array subscripts
3346
3347 @item
3348 Wrong length on string assignment
3349
3350 @item
3351 Violations of style rules if style checking is enabled
3352
3353 @item
3354 Unused with clauses
3355
3356 @item
3357 Bit_Order usage that does not have any effect
3358
3359 @item
3360 Compile time biased rounding of floating-point constant
3361
3362 @item
3363 Standard.Duration used to resolve universal fixed expression
3364
3365 @item
3366 Dereference of possibly null value
3367
3368 @item
3369 Declaration that is likely to cause storage error
3370
3371 @item
3372 Internal GNAT unit with'ed by application unit
3373
3374 @item
3375 Values known to be out of range at compile time
3376
3377 @item
3378 Unreferenced labels and variables
3379
3380 @item
3381 Address overlays that could clobber memory
3382
3383 @item
3384 Unexpected initialization when address clause present
3385
3386 @item
3387 Bad alignment for address clause
3388
3389 @item
3390 Useless type conversions
3391
3392 @item
3393 Redundant assignment statements
3394
3395 @item
3396 Accidental hiding of name by child unit
3397
3398 @item
3399 Unreachable code
3400
3401 @item
3402 Access before elaboration detected at compile time
3403
3404 @item
3405 A range in a @code{for} loop that is known to be null or might be null
3406
3407 @end itemize
3408
3409 @noindent
3410 The following switches are available to control the handling of
3411 warning messages:
3412
3413 @table @code
3414 @item -gnatwa (activate all optional errors)
3415 @cindex @option{-gnatwa} (@code{gcc})
3416 This switch activates most optional warning messages, see remaining list
3417 in this section for details on optional warning messages that can be
3418 individually controlled. The warnings that are not turned on by this
3419 switch are @option{-gnatwb} (biased rounding),
3420 @option{-gnatwd} (implicit dereferencing),
3421 and @option{-gnatwh} (hiding). All other optional warnings are
3422 turned on.
3423
3424 @item -gnatwA (suppress all optional errors)
3425 @cindex @option{-gnatwA} (@code{gcc})
3426 This switch suppresses all optional warning messages, see remaining list
3427 in this section for details on optional warning messages that can be
3428 individually controlled.
3429
3430 @item -gnatwb (activate warnings on biased rounding)
3431 @cindex @option{-gnatwb} (@code{gcc})
3432 @cindex Rounding, biased
3433 @cindex Biased rounding
3434 If a static floating-point expression has a value that is exactly half
3435 way between two adjacent machine numbers, then the rules of Ada
3436 (Ada Reference Manual, section 4.9(38)) require that this rounding
3437 be done away from zero, even if the normal unbiased rounding rules
3438 at run time would require rounding towards zero. This warning message
3439 alerts you to such instances where compile-time rounding and run-time
3440 rounding are not equivalent. If it is important to get proper run-time
3441 rounding, then you can force this by making one of the operands into
3442 a variable. The default is that such warnings are not generated.
3443 Note that @option{-gnatwa} does not affect the setting of
3444 this warning option.
3445
3446 @item -gnatwB (suppress warnings on biased rounding)
3447 @cindex @option{-gnatwB} (@code{gcc})
3448 This switch disables warnings on biased rounding.
3449
3450 @item -gnatwc (activate warnings on conditionals)
3451 @cindex @option{-gnatwc} (@code{gcc})
3452 @cindex Conditionals, constant
3453 This switch activates warnings for conditional expressions used in
3454 tests that are known to be True or False at compile time. The default
3455 is that such warnings are not generated.
3456 This warning can also be turned on using @option{-gnatwa}.
3457
3458 @item -gnatwC (suppress warnings on conditionals)
3459 @cindex @option{-gnatwC} (@code{gcc})
3460 This switch suppresses warnings for conditional expressions used in
3461 tests that are known to be True or False at compile time.
3462
3463 @item -gnatwd (activate warnings on implicit dereferencing)
3464 @cindex @option{-gnatwd} (@code{gcc})
3465 If this switch is set, then the use of a prefix of an access type
3466 in an indexed component, slice, or selected component without an
3467 explicit @code{.all} will generate a warning. With this warning
3468 enabled, access checks occur only at points where an explicit
3469 @code{.all} appears in the source code (assuming no warnings are
3470 generated as a result of this switch). The default is that such
3471 warnings are not generated.
3472 Note that @option{-gnatwa} does not affect the setting of
3473 this warning option.
3474
3475 @item -gnatwD (suppress warnings on implicit dereferencing)
3476 @cindex @option{-gnatwD} (@code{gcc})
3477 @cindex Implicit dereferencing
3478 @cindex Dereferencing, implicit
3479 This switch suppresses warnings for implicit deferences in
3480 indexed components, slices, and selected components.
3481
3482 @item -gnatwe (treat warnings as errors)
3483 @cindex @option{-gnatwe} (@code{gcc})
3484 @cindex Warnings, treat as error
3485 This switch causes warning messages to be treated as errors.
3486 The warning string still appears, but the warning messages are counted
3487 as errors, and prevent the generation of an object file.
3488
3489 @item -gnatwf (activate warnings on unreferenced formals)
3490 @cindex @option{-gnatwf} (@code{gcc})
3491 @cindex Formals, unreferenced
3492 This switch causes a warning to be generated if a formal parameter
3493 is not referenced in the body of the subprogram. This warning can
3494 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
3495
3496 @item -gnatwF (suppress warnings on unreferenced formals)
3497 @cindex @option{-gnatwF} (@code{gcc})
3498 This switch suppresses warnings for unreferenced formal
3499 parameters. Note that the
3500 combination @option{-gnatwu} followed by @option{-gnatwF} has the
3501 effect of warning on unreferenced entities other than subprogram
3502 formals.
3503
3504 @item -gnatwh (activate warnings on hiding)
3505 @cindex @option{-gnatwh} (@code{gcc})
3506 @cindex Hiding of Declarations
3507 This switch activates warnings on hiding declarations.
3508 A declaration is considered hiding
3509 if it is for a non-overloadable entity, and it declares an entity with the
3510 same name as some other entity that is directly or use-visible. The default
3511 is that such warnings are not generated.
3512 Note that @option{-gnatwa} does not affect the setting of this warning option.
3513
3514 @item -gnatwH (suppress warnings on hiding)
3515 @cindex @option{-gnatwH} (@code{gcc})
3516 This switch suppresses warnings on hiding declarations.
3517
3518 @item -gnatwi (activate warnings on implementation units).
3519 @cindex @option{-gnatwi} (@code{gcc})
3520 This switch activates warnings for a @code{with} of an internal GNAT
3521 implementation unit, defined as any unit from the @code{Ada},
3522 @code{Interfaces}, @code{GNAT},
3523  or @code{System}
3524 hierarchies that is not
3525 documented in either the Ada Reference Manual or the GNAT
3526 Programmer's Reference Manual. Such units are intended only
3527 for internal implementation purposes and should not be @code{with}'ed
3528 by user programs. The default is that such warnings are generated
3529 This warning can also be turned on using @option{-gnatwa}.
3530
3531 @item -gnatwI (disable warnings on implementation units).
3532 @cindex @option{-gnatwI} (@code{gcc})
3533 This switch disables warnings for a @code{with} of an internal GNAT
3534 implementation unit.
3535
3536 @item -gnatwl (activate warnings on elaboration pragmas)
3537 @cindex @option{-gnatwl} (@code{gcc})
3538 @cindex Elaboration, warnings
3539 This switch activates warnings on missing pragma Elaborate_All statements.
3540 See the section in this guide on elaboration checking for details on
3541 when such pragma should be used. The default is that such warnings
3542 are not generated.
3543 This warning can also be turned on using @option{-gnatwa}.
3544
3545 @item -gnatwL (suppress warnings on elaboration pragmas)
3546 @cindex @option{-gnatwL} (@code{gcc})
3547 This switch suppresses warnings on missing pragma Elaborate_All statements.
3548 See the section in this guide on elaboration checking for details on
3549 when such pragma should be used.
3550
3551 @item -gnatwo (activate warnings on address clause overlays)
3552 @cindex @option{-gnatwo} (@code{gcc})
3553 @cindex Address Clauses, warnings
3554 This switch activates warnings for possibly unintended initialization
3555 effects of defining address clauses that cause one variable to overlap
3556 another. The default is that such warnings are generated.
3557 This warning can also be turned on using @option{-gnatwa}.
3558
3559 @item -gnatwO (suppress warnings on address clause overlays)
3560 @cindex @option{-gnatwO} (@code{gcc})
3561 This switch suppresses warnings on possibly unintended initialization
3562 effects of defining address clauses that cause one variable to overlap
3563 another.
3564
3565 @item -gnatwp (activate warnings on ineffective pragma Inlines)
3566 @cindex @option{-gnatwp} (@code{gcc})
3567 @cindex Inlining, warnings
3568 This switch activates warnings for failure of front end inlining
3569 (activated by @option{-gnatN}) to inline a particular call. There are
3570 many reasons for not being able to inline a call, including most
3571 commonly that the call is too complex to inline.
3572 This warning can also be turned on using @option{-gnatwa}.
3573
3574 @item -gnatwP (suppress warnings on ineffective pragma Inlines)
3575 @cindex @option{-gnatwP} (@code{gcc})
3576 This switch suppresses warnings on ineffective pragma Inlines. If the
3577 inlining mechanism cannot inline a call, it will simply ignore the
3578 request silently.
3579
3580 @item -gnatwr (activate warnings on redundant constructs)
3581 @cindex @option{-gnatwr} (@code{gcc})
3582 This switch activates warnings for redundant constructs. The following
3583 is the current list of constructs regarded as redundant:
3584 This warning can also be turned on using @option{-gnatwa}.
3585
3586 @itemize @bullet
3587 @item
3588 Assignment of an item to itself.
3589 @item
3590 Type conversion that converts an expression to its own type.
3591 @item
3592 Use of the attribute @code{Base} where @code{typ'Base} is the same
3593 as @code{typ}.
3594 @item
3595 Use of pragma @code{Pack} when all components are placed by a record
3596 representation clause.
3597 @end itemize
3598
3599 @item -gnatwR (suppress warnings on redundant constructs)
3600 @cindex @option{-gnatwR} (@code{gcc})
3601 This switch suppresses warnings for redundant constructs.
3602
3603 @item -gnatws (suppress all warnings)
3604 @cindex @option{-gnatws} (@code{gcc})
3605 This switch completely suppresses the
3606 output of all warning messages from the GNAT front end.
3607 Note that it does not suppress warnings from the @code{gcc} back end.
3608 To suppress these back end warnings as well, use the switch @code{-w}
3609 in addition to @option{-gnatws}.
3610
3611 @item -gnatwu (activate warnings on unused entities)
3612 @cindex @option{-gnatwu} (@code{gcc})
3613 This switch activates warnings to be generated for entities that
3614 are defined but not referenced, and for units that are @code{with}'ed
3615 and not
3616 referenced. In the case of packages, a warning is also generated if
3617 no entities in the package are referenced. This means that if the package
3618 is referenced but the only references are in @code{use}
3619 clauses or @code{renames}
3620 declarations, a warning is still generated. A warning is also generated
3621 for a generic package that is @code{with}'ed but never instantiated.
3622 In the case where a package or subprogram body is compiled, and there
3623 is a @code{with} on the corresponding spec
3624 that is only referenced in the body,
3625 a warning is also generated, noting that the
3626 @code{with} can be moved to the body. The default is that
3627 such warnings are not generated.
3628 This switch also activates warnings on unreferenced formals
3629 (it is includes the effect of @option{-gnatwf}).
3630 This warning can also be turned on using @option{-gnatwa}.
3631
3632 @item -gnatwU (suppress warnings on unused entities)
3633 @cindex @option{-gnatwU} (@code{gcc})
3634 This switch suppresses warnings for unused entities and packages.
3635 It also turns off warnings on unreferenced formals (and thus includes
3636 the effect of @option{-gnatwF}).
3637
3638 @noindent
3639 A string of warning parameters can be used in the same parameter. For example:
3640
3641 @smallexample
3642 -gnatwaLe
3643 @end smallexample
3644
3645 @noindent
3646 Would turn on all optional warnings except for elaboration pragma warnings,
3647 and also specify that warnings should be treated as errors.
3648
3649 @item -w
3650 @cindex @code{-w}
3651 This switch suppresses warnings from the @code{gcc} backend. It may be
3652 used in conjunction with @option{-gnatws} to ensure that all warnings
3653 are suppressed during the entire compilation process.
3654
3655 @end table
3656
3657 @node Debugging and Assertion Control
3658 @subsection Debugging and Assertion Control
3659
3660 @table @code
3661 @item -gnata
3662 @cindex @option{-gnata} (@code{gcc})
3663 @findex Assert
3664 @findex Debug
3665 @cindex Assertions
3666
3667 @noindent
3668 The pragmas @code{Assert} and @code{Debug} normally have no effect and
3669 are ignored. This switch, where @samp{a} stands for assert, causes
3670 @code{Assert} and @code{Debug} pragmas to be activated.
3671
3672 The pragmas have the form:
3673
3674 @smallexample
3675 @group
3676 @cartouche
3677    @b{pragma} Assert (@var{Boolean-expression} [,
3678                       @var{static-string-expression}])
3679    @b{pragma} Debug (@var{procedure call})
3680 @end cartouche
3681 @end group
3682 @end smallexample
3683
3684 @noindent
3685 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
3686 If the result is @code{True}, the pragma has no effect (other than
3687 possible side effects from evaluating the expression). If the result is
3688 @code{False}, the exception @code{Assert_Failure} declared in the package
3689 @code{System.Assertions} is
3690 raised (passing @var{static-string-expression}, if present, as the
3691 message associated with the exception). If no string expression is
3692 given the default is a string giving the file name and line number
3693 of the pragma.
3694
3695 The @code{Debug} pragma causes @var{procedure} to be called. Note that
3696 @code{pragma Debug} may appear within a declaration sequence, allowing
3697 debugging procedures to be called between declarations.
3698
3699 @end table
3700
3701 @node Validity Checking
3702 @subsection Validity Checking
3703 @findex Validity Checking
3704
3705 @noindent
3706 The Ada 95 Reference Manual has specific requirements for checking
3707 for invalid values. In particular, RM 13.9.1 requires that the
3708 evaluation of invalid values (for example from unchecked conversions),
3709 not result in erroneous execution. In GNAT, the result of such an
3710 evaluation in normal default mode is to either use the value
3711 unmodified, or to raise Constraint_Error in those cases where use
3712 of the unmodified value would cause erroneous execution. The cases
3713 where unmodified values might lead to erroneous execution are case
3714 statements (where a wild jump might result from an invalid value),
3715 and subscripts on the left hand side (where memory corruption could
3716 occur as a result of an invalid value).
3717
3718 The @option{-gnatVx} switch allows more control over the validity checking
3719 mode. The @code{x} argument here is a string of letters which control which
3720 validity checks are performed in addition to the default checks described
3721 above.
3722
3723 @itemize @bullet
3724 @item
3725 @option{-gnatVc} Validity checks for copies
3726
3727 The right hand side of assignments, and the initializing values of
3728 object declarations are validity checked.
3729
3730 @item
3731 @option{-gnatVd} Default (RM) validity checks
3732
3733 Some validity checks are done by default following normal Ada semantics
3734 (RM 13.9.1 (9-11)).
3735 A check is done in case statements that the expression is within the range
3736 of the subtype. If it is not, Constraint_Error is raised.
3737 For assignments to array components, a check is done that the expression used
3738 as index is within the range. If it is not, Constraint_Error is raised.
3739 Both these validity checks may be turned off using switch @option{-gnatVD}.
3740 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
3741 switch @option{-gnatVd} will leave the checks turned on.
3742 Switch @option{-gnatVD} should be used only if you are sure that all such
3743 expressions have valid values. If you use this switch and invalid values
3744 are present, then the program is erroneous, and wild jumps or memory
3745 overwriting may occur.
3746
3747 @item
3748 @option{-gnatVi} Validity checks for @code{in} mode parameters
3749
3750 Arguments for parameters of mode @code{in} are validity checked in function
3751 and procedure calls at the point of call.
3752
3753 @item
3754 @option{-gnatVm} Validity checks for @code{in out} mode parameters
3755
3756 Arguments for parameters of mode @code{in out} are validity checked in
3757 procedure calls at the point of call. The @code{'m'} here stands for
3758 modify, since this concerns parameters that can be modified by the call.
3759 Note that there is no specific option to test @code{out} parameters,
3760 but any reference within the subprogram will be tested in the usual
3761 manner, and if an invalid value is copied back, any reference to it
3762 will be subject to validity checking.
3763
3764 @item
3765 @option{-gnatVo} Validity checks for operator and attribute operands
3766
3767 Arguments for predefined operators and attributes are validity checked.
3768 This includes all operators in package @code{Standard},
3769 the shift operators defined as intrinsic in package @code{Interfaces}
3770 and operands for attributes such as @code{Pos}.
3771
3772 @item
3773 @option{-gnatVr} Validity checks for function returns
3774
3775 The expression in @code{return} statements in functions is validity
3776 checked.
3777
3778 @item
3779 @option{-gnatVs} Validity checks for subscripts
3780
3781 All subscripts expressions are checked for validity, whether they appear
3782 on the right side or left side (in default mode only left side subscripts
3783 are validity checked).
3784
3785 @item
3786 @option{-gnatVt} Validity checks for tests
3787
3788 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
3789 statements are checked, as well as guard expressions in entry calls.
3790
3791 @item
3792 @option{-gnatVf} Validity checks for floating-point values
3793
3794 In the absence of this switch, validity checking occurs only for discrete
3795 values. If @option{-gnatVf} is specified, then validity checking also applies
3796 for floating-point values, and NaN's and infinities are considered invalid,
3797 as well as out of range values for constrained types. Note that this means
3798 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
3799 in which floating-point values are checked depends on the setting of other
3800 options. For example @option{-gnatVif} or @option{-gnatVfi} (the order does
3801 not matter) specifies that floating-point parameters of mode @code{in} should
3802 be validity checked.
3803
3804 @item
3805 @option{-gnatVa} All validity checks
3806
3807 All the above validity checks are turned on. That is @option{-gnatVa} is
3808 equivalent to @code{gnatVcdfimorst}.
3809
3810 @item
3811 @option{-gnatVn} No validity checks
3812
3813 This switch turns off all validity checking, including the default checking
3814 for case statements and left hand side subscripts. Note that the use of
3815 the switch @option{-gnatp} supresses all run-time checks, including
3816 validity checks, and thus implies @option{-gnatVn}.
3817
3818 @end itemize
3819
3820 The @option{-gnatV} switch may be followed by a string of letters to turn on
3821 a series of validity checking options. For example, @option{-gnatVcr} specifies
3822 that in addition to the default validity checking, copies and function
3823 return expressions be validity checked. In order to make it easier to specify
3824 a set of options, the upper case letters @code{CDFIMORST} may be used to turn
3825 off the corresponding lower case option, so for example @option{-gnatVaM} turns
3826 on all validity checking options except for checking of @code{in out}
3827 procedure arguments.
3828
3829 The specification of additional validity checking generates extra code (and
3830 in the case of @option{-gnatva} the code expansion can be substantial. However,
3831 these additional checks can be very useful in smoking out cases of
3832 uninitialized variables, incorrect use of unchecked conversion, and other
3833 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
3834 is useful in conjunction with the extra validity checking, since this
3835 ensures that wherever possible uninitialized variables have invalid values.
3836
3837 See also the pragma @code{Validity_Checks} which allows modification of
3838 the validity checking mode at the program source level, and also allows for
3839 temporary disabling of validity checks.
3840
3841 @node Style Checking
3842 @subsection Style Checking
3843 @findex Style checking
3844
3845 @noindent
3846 The -gnaty@var{x} switch causes the compiler to
3847 enforce specified style rules. A limited set of style rules has been used
3848 in writing the GNAT sources themselves. This switch allows user programs
3849 to activate all or some of these checks. If the source program fails a
3850 specified style check, an appropriate warning message is given, preceded by
3851 the character sequence "(style)".
3852 The string @var{x} is a sequence of letters or digits
3853 indicating the particular style
3854 checks to be performed. The following checks are defined:
3855
3856 @table @code
3857 @item 1-9 (specify indentation level)
3858 If a digit from 1-9 appears in the string after @option{-gnaty} then proper
3859 indentation is checked, with the digit indicating the indentation level
3860 required. The general style of required indentation is as specified by
3861 the examples in the Ada Reference Manual. Full line comments must be
3862 aligned with the @code{--} starting on a column that is a multiple of
3863 the alignment level.
3864
3865 @item a (check attribute casing)
3866 If the letter a appears in the string after @option{-gnaty} then
3867 attribute names, including the case of keywords such as @code{digits}
3868 used as attributes names, must be written in mixed case, that is, the
3869 initial letter and any letter following an underscore must be uppercase.
3870 All other letters must be lowercase.
3871
3872 @item b (blanks not allowed at statement end)
3873 If the letter b appears in the string after @option{-gnaty} then
3874 trailing blanks are not allowed at the end of statements. The purpose of this
3875 rule, together with h (no horizontal tabs), is to enforce a canonical format
3876 for the use of blanks to separate source tokens.
3877
3878 @item c (check comments)
3879 If the letter c appears in the string after @option{-gnaty} then
3880 comments must meet the following set of rules:
3881
3882 @itemize @bullet
3883
3884 @item
3885 The "--" that starts the column must either start in column one, or else
3886 at least one blank must precede this sequence.
3887
3888 @item
3889 Comments that follow other tokens on a line must have at least one blank
3890 following the "--" at the start of the comment.
3891
3892 @item
3893 Full line comments must have two blanks following the "--" that starts
3894 the comment, with the following exceptions.
3895
3896 @item
3897 A line consisting only of the "--" characters, possibly preceded by blanks
3898 is permitted.
3899
3900 @item
3901 A comment starting with "--x" where x is a special character is permitted.
3902 This alows proper processing of the output generated by specialized tools
3903 including @code{gnatprep} (where --! is used) and the SPARK annnotation
3904 language (where --# is used). For the purposes of this rule, a special
3905 character is defined as being in one of the ASCII ranges
3906 16#21#..16#2F# or 16#3A#..16#3F#.
3907
3908 @item
3909 A line consisting entirely of minus signs, possibly preceded by blanks, is
3910 permitted. This allows the construction of box comments where lines of minus
3911 signs are used to form the top and bottom of the box.
3912
3913 @item
3914 If a comment starts and ends with "--" is permitted as long as at least
3915 one blank follows the initial "--". Together with the preceding rule,
3916 this allows the construction of box comments, as shown in the following
3917 example:
3918 @smallexample
3919 ---------------------------
3920 -- This is a box comment --
3921 -- with two text lines.  --
3922 ---------------------------
3923 @end smallexample
3924 @end itemize
3925
3926 @item e (check end/exit labels)
3927 If the letter e appears in the string after @option{-gnaty} then
3928 optional labels on @code{end} statements ending subprograms and on
3929 @code{exit} statements exiting named loops, are required to be present.
3930
3931 @item f (no form feeds or vertical tabs)
3932 If the letter f appears in the string after @option{-gnaty} then
3933 neither form feeds nor vertical tab characters are not permitted
3934 in the source text.
3935
3936 @item h (no horizontal tabs)
3937 If the letter h appears in the string after @option{-gnaty} then
3938 horizontal tab characters are not permitted in the source text.
3939 Together with the b (no blanks at end of line) check, this
3940 enforces a canonical form for the use of blanks to separate
3941 source tokens.
3942
3943 @item i (check if-then layout)
3944 If the letter i appears in the string after @option{-gnaty},
3945 then the keyword @code{then} must appear either on the same
3946 line as corresponding @code{if}, or on a line on its own, lined
3947 up under the @code{if} with at least one non-blank line in between
3948 containing all or part of the condition to be tested.
3949
3950 @item k (check keyword casing)
3951 If the letter k appears in the string after @option{-gnaty} then
3952 all keywords must be in lower case (with the exception of keywords
3953 such as @code{digits} used as attribute names to which this check
3954 does not apply).
3955
3956 @item l (check layout)
3957 If the letter l appears in the string after @option{-gnaty} then
3958 layout of statement and declaration constructs must follow the
3959 recommendations in the Ada Reference Manual, as indicated by the
3960 form of the syntax rules. For example an @code{else} keyword must
3961 be lined up with the corresponding @code{if} keyword.
3962
3963 There are two respects in which the style rule enforced by this check
3964 option are more liberal than those in the Ada Reference Manual. First
3965 in the case of record declarations, it is permissible to put the
3966 @code{record} keyword on the same line as the @code{type} keyword, and
3967 then the @code{end} in @code{end record} must line up under @code{type}.
3968 For example, either of the following two layouts is acceptable:
3969
3970 @smallexample
3971 @group
3972 @cartouche
3973 @b{type} q @b{is record}
3974    a : integer;
3975    b : integer;
3976 @b{end record};
3977
3978 @b{type} q @b{is}
3979    @b{record}
3980       a : integer;
3981       b : integer;
3982    @b{end record};
3983 @end cartouche
3984 @end group
3985 @end smallexample
3986
3987 @noindent
3988 Second, in the case of a block statement, a permitted alternative
3989 is to put the block label on the same line as the @code{declare} or
3990 @code{begin} keyword, and then line the @code{end} keyword up under
3991 the block label. For example both the following are permitted:
3992
3993 @smallexample
3994 @group
3995 @cartouche
3996 Block : @b{declare}
3997    A : Integer := 3;
3998 @b{begin}
3999    Proc (A, A);
4000 @b{end} Block;
4001
4002 Block :
4003    @b{declare}
4004       A : Integer := 3;
4005    @b{begin}
4006       Proc (A, A);
4007    @b{end} Block;
4008 @end cartouche
4009 @end group
4010 @end smallexample
4011
4012 @noindent
4013 The same alternative format is allowed for loops. For example, both of
4014 the following are permitted:
4015
4016 @smallexample
4017 @group
4018 @cartouche
4019 Clear : @b{while} J < 10 @b{loop}
4020    A (J) := 0;
4021 @b{end loop} Clear;
4022
4023 Clear :
4024    @b{while} J < 10 @b{loop}
4025       A (J) := 0;
4026    @b{end loop} Clear;
4027 @end cartouche
4028 @end group
4029 @end smallexample
4030
4031 @item m (check maximum line length)
4032 If the letter m appears in the string after @option{-gnaty}
4033 then the length of source lines must not exceed 79 characters, including
4034 any trailing blanks. The value of 79 allows convenient display on an
4035 80 character wide device or window, allowing for possible special
4036 treatment of 80 character lines.
4037
4038 @item Mnnn (set maximum line length)
4039 If the sequence Mnnn, where nnn is a decimal number, appears in
4040 the string after @option{-gnaty} then the length of lines must not exceed the
4041 given value.
4042
4043 @item n (check casing of entities in Standard)
4044 If the letter n appears in the string
4045 after @option{-gnaty} then any identifier from Standard must be cased
4046 to match the presentation in the Ada Reference Manual (for example,
4047 @code{Integer} and @code{ASCII.NUL}).
4048
4049 @item o (check order of subprogram bodies)
4050 If the letter o appears in the string
4051 after @option{-gnaty} then all subprogram bodies in a given scope
4052 (e.g. a package body) must be in alphabetical order. The ordering
4053 rule uses normal Ada rules for comparing strings, ignoring casing
4054 of letters, except that if there is a trailing numeric suffix, then
4055 the value of this suffix is used in the ordering (e.g. Junk2 comes
4056 before Junk10).
4057
4058 @item p (check pragma casing)
4059 If the letter p appears in the string after @option{-gnaty} then
4060 pragma names must be written in mixed case, that is, the
4061 initial letter and any letter following an underscore must be uppercase.
4062 All other letters must be lowercase.
4063
4064 @item r (check references)
4065 If the letter r appears in the string after @option{-gnaty}
4066 then all identifier references must be cased in the same way as the
4067 corresponding declaration. No specific casing style is imposed on
4068 identifiers. The only requirement is for consistency of references
4069 with declarations.
4070
4071 @item s (check separate specs)
4072 If the letter s appears in the string after @option{-gnaty} then
4073 separate declarations ("specs") are required for subprograms (a
4074 body is not allowed to serve as its own declaration). The only
4075 exception is that parameterless library level procedures are
4076 not required to have a separate declaration. This exception covers
4077 the most frequent form of main program procedures.
4078
4079 @item t (check token spacing)
4080 If the letter t appears in the string after @option{-gnaty} then
4081 the following token spacing rules are enforced:
4082
4083 @itemize @bullet
4084
4085 @item
4086 The keywords @code{abs} and @code{not} must be followed by a space.
4087
4088 @item
4089 The token @code{=>} must be surrounded by spaces.
4090
4091 @item
4092 The token @code{<>} must be preceded by a space or a left parenthesis.
4093
4094 @item
4095 Binary operators other than @code{**} must be surrounded by spaces.
4096 There is no restriction on the layout of the @code{**} binary operator.
4097
4098 @item
4099 Colon must be surrounded by spaces.
4100
4101 @item
4102 Colon-equal (assignment) must be surrounded by spaces.
4103
4104 @item
4105 Comma must be the first non-blank character on the line, or be
4106 immediately preceded by a non-blank character, and must be followed
4107 by a space.
4108
4109 @item
4110 If the token preceding a left paren ends with a letter or digit, then
4111 a space must separate the two tokens.
4112
4113 @item
4114 A right parenthesis must either be the first non-blank character on
4115 a line, or it must be preceded by a non-blank character.
4116
4117 @item
4118 A semicolon must not be preceded by a space, and must not be followed by
4119 a non-blank character.
4120
4121 @item
4122 A unary plus or minus may not be followed by a space.
4123
4124 @item
4125 A vertical bar must be surrounded by spaces.
4126 @end itemize
4127
4128 @noindent
4129 In the above rules, appearing in column one is always permitted, that is,
4130 counts as meeting either a requirement for a required preceding space,
4131 or as meeting a requirement for no preceding space.
4132
4133 Appearing at the end of a line is also always permitted, that is, counts
4134 as meeting either a requirement for a following space, or as meeting
4135 a requirement for no following space.
4136
4137 @end table
4138
4139 @noindent
4140 If any of these style rules is violated, a message is generated giving
4141 details on the violation. The initial characters of such messages are
4142 always "(style)". Note that these messages are treated as warning
4143 messages, so they normally do not prevent the generation of an object
4144 file. The @option{-gnatwe} switch can be used to treat warning messages,
4145 including style messages, as fatal errors.
4146
4147 @noindent
4148 The switch
4149 @option{-gnaty} on its own (that is not followed by any letters or digits),
4150 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
4151 options are enabled with
4152 the exception of -gnatyo,
4153 with an indentation level of 3. This is the standard
4154 checking option that is used for the GNAT sources.
4155
4156 @node Run-Time Checks
4157 @subsection Run-Time Checks
4158 @cindex Division by zero
4159 @cindex Access before elaboration
4160 @cindex Checks, division by zero
4161 @cindex Checks, access before elaboration
4162
4163 @noindent
4164 If you compile with the default options, GNAT will insert many run-time
4165 checks into the compiled code, including code that performs range
4166 checking against constraints, but not arithmetic overflow checking for
4167 integer operations (including division by zero) or checks for access
4168 before elaboration on subprogram calls. All other run-time checks, as
4169 required by the Ada 95 Reference Manual, are generated by default.
4170 The following @code{gcc} switches refine this default behavior:
4171
4172 @table @code
4173 @item -gnatp
4174 @cindex @option{-gnatp} (@code{gcc})
4175 @cindex Suppressing checks
4176 @cindex Checks, suppressing
4177 @findex Suppress
4178 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
4179 had been present in the source. Validity checks are also suppressed (in
4180 other words @option{-gnatp} also implies @option{-gnatVn}.
4181 Use this switch to improve the performance
4182 of the code at the expense of safety in the presence of invalid data or
4183 program bugs.
4184
4185 @item -gnato
4186 @cindex @option{-gnato} (@code{gcc})
4187 @cindex Overflow checks
4188 @cindex Check, overflow
4189 Enables overflow checking for integer operations.
4190 This causes GNAT to generate slower and larger executable
4191 programs by adding code to check for overflow (resulting in raising
4192 @code{Constraint_Error} as required by standard Ada
4193 semantics). These overflow checks correspond to situations in which
4194 the true value of the result of an operation may be outside the base
4195 range of the result type. The following example shows the distinction:
4196
4197 @smallexample
4198 X1 : Integer := Integer'Last;
4199 X2 : Integer range 1 .. 5 := 5;
4200 ...
4201 X1 := X1 + 1;   -- @option{-gnato} required to catch the Constraint_Error
4202 X2 := X2 + 1;   -- range check, @option{-gnato} has no effect here
4203 @end smallexample
4204
4205 @noindent
4206 Here the first addition results in a value that is outside the base range
4207 of Integer, and hence requires an overflow check for detection of the
4208 constraint error. The second increment operation results in a violation
4209 of the explicit range constraint, and such range checks are always
4210 performed. Basically the compiler can assume that in the absence of
4211 the @option{-gnato} switch that any value of type @code{xxx} is
4212 in range of the base type of @code{xxx}.
4213
4214 @findex Machine_Overflows
4215 Note that the @option{-gnato} switch does not affect the code generated
4216 for any floating-point operations; it applies only to integer
4217 semantics).
4218 For floating-point, GNAT has the @code{Machine_Overflows}
4219 attribute set to @code{False} and the normal mode of operation is to
4220 generate IEEE NaN and infinite values on overflow or invalid operations
4221 (such as dividing 0.0 by 0.0).
4222
4223 The reason that we distinguish overflow checking from other kinds of
4224 range constraint checking is that a failure of an overflow check can
4225 generate an incorrect value, but cannot cause erroneous behavior. This
4226 is unlike the situation with a constraint check on an array subscript,
4227 where failure to perform the check can result in random memory description,
4228 or the range check on a case statement, where failure to perform the check
4229 can cause a wild jump.
4230
4231 Note again that @option{-gnato} is off by default, so overflow checking is
4232 not performed in default mode. This means that out of the box, with the
4233 default settings, GNAT does not do all the checks expected from the
4234 language description in the Ada Reference Manual. If you want all constraint
4235 checks to be performed, as described in this Manual, then you must
4236 explicitly use the -gnato switch either on the @code{gnatmake} or
4237 @code{gcc} command.
4238
4239 @item -gnatE
4240 @cindex @option{-gnatE} (@code{gcc})
4241 @cindex Elaboration checks
4242 @cindex Check, elaboration
4243 Enables dynamic checks for access-before-elaboration
4244 on subprogram calls and generic instantiations.
4245 For full details of the effect and use of this switch,
4246 @xref{Compiling Using gcc}.
4247 @end table
4248
4249 @findex Unsuppress
4250 @noindent
4251 The setting of these switches only controls the default setting of the
4252 checks. You may modify them using either @code{Suppress} (to remove
4253 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
4254 the program source.
4255
4256 @node Stack Overflow Checking
4257 @subsection Stack Overflow Checking
4258 @cindex Stack Overflow Checking
4259 @cindex -fstack-check
4260
4261 @noindent
4262 For most operating systems, @code{gcc} does not perform stack overflow
4263 checking by default. This means that if the main environment task or
4264 some other task exceeds the available stack space, then unpredictable
4265 behavior will occur.
4266
4267 To activate stack checking, compile all units with the gcc option
4268 @code{-fstack-check}. For example:
4269
4270 @smallexample
4271 gcc -c -fstack-check package1.adb
4272 @end smallexample
4273
4274 @noindent
4275 Units compiled with this option will generate extra instructions to check
4276 that any use of the stack (for procedure calls or for declaring local
4277 variables in declare blocks) do not exceed the available stack space.
4278 If the space is exceeded, then a @code{Storage_Error} exception is raised.
4279
4280 For declared tasks, the stack size is always controlled by the size
4281 given in an applicable @code{Storage_Size} pragma (or is set to
4282 the default size if no pragma is used.
4283
4284 For the environment task, the stack size depends on
4285 system defaults and is unknown to the compiler. The stack
4286 may even dynamically grow on some systems, precluding the
4287 normal Ada semantics for stack overflow. In the worst case,
4288 unbounded stack usage, causes unbounded stack expansion
4289 resulting in the system running out of virtual memory.
4290
4291 The stack checking may still work correctly if a fixed
4292 size stack is allocated, but this cannot be guaranteed.
4293 To ensure that a clean exception is signalled for stack
4294 overflow, set the environment variable
4295 @code{GNAT_STACK_LIMIT} to indicate the maximum
4296 stack area that can be used, as in:
4297 @cindex GNAT_STACK_LIMIT
4298
4299 @smallexample
4300 SET GNAT_STACK_LIMIT 1600
4301 @end smallexample
4302
4303 @noindent
4304 The limit is given in kilobytes, so the above declaration would
4305 set the stack limit of the environment task to 1.6 megabytes.
4306 Note that the only purpose of this usage is to limit the amount
4307 of stack used by the environment task. If it is necessary to
4308 increase the amount of stack for the environment task, then this
4309 is an operating systems issue, and must be addressed with the
4310 appropriate operating systems commands.
4311
4312 @node Run-Time Control
4313 @subsection Run-Time Control
4314
4315 @table @code
4316 @item -gnatT nnn
4317 @cindex @option{-gnatT} (@code{gcc})
4318 @cindex Time Slicing
4319
4320 @noindent
4321 The @code{gnatT} switch can be used to specify the time-slicing value
4322 to be used for task switching between equal priority tasks. The value
4323 @code{nnn} is given in microseconds as a decimal integer.
4324
4325 Setting the time-slicing value is only effective if the underlying thread
4326 control system can accommodate time slicing. Check the documentation of
4327 your operating system for details. Note that the time-slicing value can
4328 also be set by use of pragma @code{Time_Slice} or by use of the
4329 @code{t} switch in the gnatbind step. The pragma overrides a command
4330 line argument if both are present, and the @code{t} switch for gnatbind
4331 overrides both the pragma and the @code{gcc} command line switch.
4332 @end table
4333
4334 @node Using gcc for Syntax Checking
4335 @subsection Using @code{gcc} for Syntax Checking
4336 @table @code
4337 @item -gnats
4338 @cindex @option{-gnats} (@code{gcc})
4339
4340 @noindent
4341 The @code{s} stands for syntax.
4342
4343 Run GNAT in syntax checking only mode. For
4344 example, the command
4345
4346 @smallexample
4347 $ gcc -c -gnats x.adb
4348 @end smallexample
4349
4350 @noindent
4351 compiles file @file{x.adb} in syntax-check-only mode. You can check a
4352 series of files in a single command
4353 , and can use wild cards to specify such a group of files.
4354 Note that you must specify the @code{-c} (compile
4355 only) flag in addition to the @option{-gnats} flag.
4356 .
4357
4358 You may use other switches in conjunction with @option{-gnats}. In
4359 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
4360 format of any generated error messages.
4361
4362 The output is simply the error messages, if any. No object file or ALI
4363 file is generated by a syntax-only compilation. Also, no units other
4364 than the one specified are accessed. For example, if a unit @code{X}
4365 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
4366 check only mode does not access the source file containing unit
4367 @code{Y}.
4368
4369 @cindex Multiple units, syntax checking
4370 Normally, GNAT allows only a single unit in a source file. However, this
4371 restriction does not apply in syntax-check-only mode, and it is possible
4372 to check a file containing multiple compilation units concatenated
4373 together. This is primarily used by the @code{gnatchop} utility
4374 (@pxref{Renaming Files Using gnatchop}).
4375 @end table
4376
4377 @node Using gcc for Semantic Checking
4378 @subsection Using @code{gcc} for Semantic Checking
4379 @table @code
4380 @item -gnatc
4381 @cindex @option{-gnatc} (@code{gcc})
4382
4383 @noindent
4384 The @code{c} stands for check.
4385 Causes the compiler to operate in semantic check mode,
4386 with full checking for all illegalities specified in the
4387 Ada 95 Reference Manual, but without generation of any object code
4388 (no object file is generated).
4389
4390 Because dependent files must be accessed, you must follow the GNAT
4391 semantic restrictions on file structuring to operate in this mode:
4392
4393 @itemize @bullet
4394 @item
4395 The needed source files must be accessible
4396 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4397
4398 @item
4399 Each file must contain only one compilation unit.
4400
4401 @item
4402 The file name and unit name must match (@pxref{File Naming Rules}).
4403 @end itemize
4404
4405 The output consists of error messages as appropriate. No object file is
4406 generated. An @file{ALI} file is generated for use in the context of
4407 cross-reference tools, but this file is marked as not being suitable
4408 for binding (since no object file is generated).
4409 The checking corresponds exactly to the notion of
4410 legality in the Ada 95 Reference Manual.
4411
4412 Any unit can be compiled in semantics-checking-only mode, including
4413 units that would not normally be compiled (subunits,
4414 and specifications where a separate body is present).
4415 @end table
4416
4417 @node Compiling Ada 83 Programs
4418 @subsection Compiling Ada 83 Programs
4419 @table @code
4420 @cindex Ada 83 compatibility
4421 @item -gnat83
4422 @cindex @option{-gnat83} (@code{gcc})
4423 @cindex ACVC, Ada 83 tests
4424
4425 @noindent
4426 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
4427 specify that an Ada 83 program is to be compiled in Ada83 mode. If you specify
4428 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
4429 where this can be done easily.
4430 It is not possible to guarantee this switch does a perfect
4431 job; for example, some subtle tests, such as are
4432 found in earlier ACVC tests (that have been removed from the ACVC suite for Ada
4433 95), may not compile correctly. However, for most purposes, using
4434 this switch should help to ensure that programs that compile correctly
4435 under the @option{-gnat83} switch can be ported easily to an Ada 83
4436 compiler. This is the main use of the switch.
4437
4438 With few exceptions (most notably the need to use @code{<>} on
4439 @cindex Generic formal parameters
4440 unconstrained generic formal parameters, the use of the new Ada 95
4441 keywords, and the use of packages
4442 with optional bodies), it is not necessary to use the
4443 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
4444 exceptions, Ada 95 is upwardly compatible with Ada 83. This
4445 means that a correct Ada 83 program is usually also a correct Ada 95
4446 program.
4447
4448 @end table
4449
4450 @node Character Set Control
4451 @subsection Character Set Control
4452 @table @code
4453 @item -gnati@var{c}
4454 @cindex @code{-gnati} (@code{gcc})
4455
4456 @noindent
4457 Normally GNAT recognizes the Latin-1 character set in source program
4458 identifiers, as described in the Ada 95 Reference Manual.
4459 This switch causes
4460 GNAT to recognize alternate character sets in identifiers. @var{c} is a
4461 single character  indicating the character set, as follows:
4462
4463 @table @code
4464 @item 1
4465 Latin-1 identifiers
4466
4467 @item 2
4468 Latin-2 letters allowed in identifiers
4469
4470 @item 3
4471 Latin-3 letters allowed in identifiers
4472
4473 @item 4
4474 Latin-4 letters allowed in identifiers
4475
4476 @item 5
4477 Latin-5 (Cyrillic) letters allowed in identifiers
4478
4479 @item 9
4480 Latin-9 letters allowed in identifiers
4481
4482 @item p
4483 IBM PC letters (code page 437) allowed in identifiers
4484
4485 @item 8
4486 IBM PC letters (code page 850) allowed in identifiers
4487
4488 @item f
4489 Full upper-half codes allowed in identifiers
4490
4491 @item n
4492 No upper-half codes allowed in identifiers
4493
4494 @item w
4495 Wide-character codes (that is, codes greater than 255)
4496 allowed in identifiers
4497 @end table
4498
4499 @xref{Foreign Language Representation}, for full details on the
4500 implementation of these character sets.
4501
4502 @item -gnatW@var{e}
4503 @cindex @code{-gnatW} (@code{gcc})
4504 Specify the method of encoding for wide characters.
4505 @var{e} is one of the following:
4506
4507 @table @code
4508
4509 @item h
4510 Hex encoding (brackets coding also recognized)
4511
4512 @item u
4513 Upper half encoding (brackets encoding also recognized)
4514
4515 @item s
4516 Shift/JIS encoding (brackets encoding also recognized)
4517
4518 @item e
4519 EUC encoding (brackets encoding also recognized)
4520
4521 @item 8
4522 UTF-8 encoding (brackets encoding also recognized)
4523
4524 @item b
4525 Brackets encoding only (default value)
4526 @end table
4527 For full details on the these encoding
4528 methods see @xref{Wide Character Encodings}.
4529 Note that brackets coding is always accepted, even if one of the other
4530 options is specified, so for example @option{-gnatW8} specifies that both
4531 brackets and @code{UTF-8} encodings will be recognized. The units that are
4532 with'ed directly or indirectly will be scanned using the specified
4533 representation scheme, and so if one of the non-brackets scheme is
4534 used, it must be used consistently throughout the program. However,
4535 since brackets encoding is always recognized, it may be conveniently
4536 used in standard libraries, allowing these libraries to be used with
4537 any of the available coding schemes.
4538 scheme. If no @option{-gnatW?} parameter is present, then the default
4539 representation is Brackets encoding only.
4540
4541 Note that the wide character representation that is specified (explicitly
4542 or by default) for the main program also acts as the default encoding used
4543 for Wide_Text_IO files if not specifically overridden by a WCEM form
4544 parameter.
4545
4546 @end table
4547 @node File Naming Control
4548 @subsection File Naming Control
4549
4550 @table @code
4551 @item -gnatk@var{n}
4552 @cindex @option{-gnatk} (@code{gcc})
4553 Activates file name "krunching". @var{n}, a decimal integer in the range
4554 1-999, indicates the maximum allowable length of a file name (not
4555 including the @file{.ads} or @file{.adb} extension). The default is not
4556 to enable file name krunching.
4557
4558 For the source file naming rules, @xref{File Naming Rules}.
4559 @end table
4560
4561 @node Subprogram Inlining Control
4562 @subsection Subprogram Inlining Control
4563
4564 @table @code
4565 @item -gnatn
4566 @cindex @option{-gnatn} (@code{gcc})
4567 The @code{n} here is intended to suggest the first syllable of the
4568 word "inline".
4569 GNAT recognizes and processes @code{Inline} pragmas. However, for the
4570 inlining to actually occur, optimization must be enabled. To enable
4571 inlining across unit boundaries, this is, inlining a call in one unit of
4572 a subprogram declared in a @code{with}'ed unit, you must also specify
4573 this switch.
4574 In the absence of this switch, GNAT does not attempt
4575 inlining across units and does not need to access the bodies of
4576 subprograms for which @code{pragma Inline} is specified if they are not
4577 in the current unit.
4578
4579 If you specify this switch the compiler will access these bodies,
4580 creating an extra source dependency for the resulting object file, and
4581 where possible, the call will be inlined.
4582 For further details on when inlining is possible
4583 see @xref{Inlining of Subprograms}.
4584
4585 @item -gnatN
4586 @cindex @option{-gnatN} (@code{gcc})
4587 The front end inlining activated by this switch is generally more extensive,
4588 and quite often more effective than the standard @option{-gnatn} inlining mode.
4589 It will also generate additional dependencies.
4590
4591 @end table
4592
4593 @node Auxiliary Output Control
4594 @subsection Auxiliary Output Control
4595
4596 @table @code
4597 @item -gnatt
4598 @cindex @option{-gnatt} (@code{gcc})
4599 @cindex Writing internal trees
4600 @cindex Internal trees, writing to file
4601 Causes GNAT to write the internal tree for a unit to a file (with the
4602 extension @file{.adt}.
4603 This not normally required, but is used by separate analysis tools.
4604 Typically
4605 these tools do the necessary compilations automatically, so you should
4606 not have to specify this switch in normal operation.
4607
4608 @item -gnatu
4609 @cindex @option{-gnatu} (@code{gcc})
4610 Print a list of units required by this compilation on @file{stdout}.
4611 The listing includes all units on which the unit being compiled depends
4612 either directly or indirectly.
4613
4614 @item -pass-exit-codes
4615 @cindex @code{-pass-exit-codes} (@code{gcc})
4616 If this switch is not used, the exit code returned by @code{gcc} when
4617 compiling multiple files indicates whether all source files have
4618 been successfully used to generate object files or not.
4619
4620 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
4621 exit status and allows an integrated development environment to better
4622 react to a compilation failure. Those exit status are:
4623
4624 @table @asis
4625 @item 5
4626 There was an error in at least one source file.
4627 @item 3
4628 At least one source file did not generate an object file.
4629 @item 2
4630 The compiler died unexpectedly (internal error for example).
4631 @item 0
4632 An object file has been generated for every source file.
4633 @end table
4634 @end table
4635
4636 @node Debugging Control
4637 @subsection Debugging Control
4638
4639 @table @code
4640 @cindex Debugging options
4641 @item -gnatd@var{x}
4642 Activate internal debugging switches. @var{x} is a letter or digit, or
4643 string of letters or digits, which specifies the type of debugging
4644 outputs desired. Normally these are used only for internal development
4645 or system debugging purposes. You can find full documentation for these
4646 switches in the body of the @code{Debug} unit in the compiler source
4647 file @file{debug.adb}.
4648
4649 @item -gnatG
4650 @cindex @option{-gnatG} (@code{gcc})
4651 This switch causes the compiler to generate auxiliary output containing
4652 a pseudo-source listing of the generated expanded code. Like most Ada
4653 compilers, GNAT works by first transforming the high level Ada code into
4654 lower level constructs. For example, tasking operations are transformed
4655 into calls to the tasking run-time routines. A unique capability of GNAT
4656 is to list this expanded code in a form very close to normal Ada source.
4657 This is very useful in understanding the implications of various Ada
4658 usage on the efficiency of the generated code. There are many cases in
4659 Ada (e.g. the use of controlled types), where simple Ada statements can
4660 generate a lot of run-time code. By using @option{-gnatG} you can identify
4661 these cases, and consider whether it may be desirable to modify the coding
4662 approach to improve efficiency.
4663
4664 The format of the output is very similar to standard Ada source, and is
4665 easily understood by an Ada programmer. The following special syntactic
4666 additions correspond to low level features used in the generated code that
4667 do not have any exact analogies in pure Ada source form. The following
4668 is a partial list of these special constructions. See the specification
4669 of package @code{Sprint} in file @file{sprint.ads} for a full list.
4670
4671 @table @code
4672 @item new @var{xxx} [storage_pool = @var{yyy}]
4673 Shows the storage pool being used for an allocator.
4674
4675 @item at end @var{procedure-name};
4676 Shows the finalization (cleanup) procedure for a scope.
4677
4678 @item (if @var{expr} then @var{expr} else @var{expr})
4679 Conditional expression equivalent to the @code{x?y:z} construction in C.
4680
4681 @item @var{target}^(@var{source})
4682 A conversion with floating-point truncation instead of rounding.
4683
4684 @item @var{target}?(@var{source})
4685 A conversion that bypasses normal Ada semantic checking. In particular
4686 enumeration types and fixed-point types are treated simply as integers.
4687
4688 @item @var{target}?^(@var{source})
4689 Combines the above two cases.
4690
4691 @item @var{x} #/ @var{y}
4692 @itemx @var{x} #mod @var{y}
4693 @itemx @var{x} #* @var{y}
4694 @itemx @var{x} #rem @var{y}
4695 A division or multiplication of fixed-point values which are treated as
4696 integers without any kind of scaling.
4697
4698 @item free @var{expr} [storage_pool = @var{xxx}]
4699 Shows the storage pool associated with a @code{free} statement.
4700
4701 @item freeze @var{typename} [@var{actions}]
4702 Shows the point at which @var{typename} is frozen, with possible
4703 associated actions to be performed at the freeze point.
4704
4705 @item reference @var{itype}
4706 Reference (and hence definition) to internal type @var{itype}.
4707
4708 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
4709 Intrinsic function call.
4710
4711 @item @var{labelname} : label
4712 Declaration of label @var{labelname}.
4713
4714 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
4715 A multiple concatenation (same effect as @var{expr} & @var{expr} &
4716 @var{expr}, but handled more efficiently).
4717
4718 @item [constraint_error]
4719 Raise the @code{Constraint_Error} exception.
4720
4721 @item @var{expression}'reference
4722 A pointer to the result of evaluating @var{expression}.
4723
4724 @item @var{target-type}!(@var{source-expression})
4725 An unchecked conversion of @var{source-expression} to @var{target-type}.
4726
4727 @item [@var{numerator}/@var{denominator}]
4728 Used to represent internal real literals (that) have no exact
4729 representation in base 2-16 (for example, the result of compile time
4730 evaluation of the expression 1.0/27.0).
4731
4732 @item -gnatD
4733 @cindex @option{-gnatD} (@code{gcc})
4734 This switch is used in conjunction with @option{-gnatG} to cause the expanded
4735 source, as described above to be written to files with names
4736 @file{xxx.dg}, where @file{xxx} is the normal file name,
4737 for example, if the source file name is @file{hello.adb},
4738 then a file @file{hello.adb.dg} will be written.
4739 The debugging information generated
4740 by the @code{gcc} @code{-g} switch will refer to the generated
4741 @file{xxx.dg} file. This allows you to do source level debugging using
4742 the generated code which is sometimes useful for complex code, for example
4743 to find out exactly which part of a complex construction raised an
4744 exception. This switch also suppress generation of cross-reference
4745 information (see -gnatx).
4746
4747 @item -gnatC
4748 @cindex @option{-gnatE} (@code{gcc})
4749 In the generated debugging information, and also in the case of long external
4750 names, the compiler uses a compression mechanism if the name is very long.
4751 This compression method uses a checksum, and avoids trouble on some operating
4752 systems which have difficulty with very long names. The @option{-gnatC} switch
4753 forces this compression approach to be used on all external names and names
4754 in the debugging information tables. This reduces the size of the generated
4755 executable, at the expense of making the naming scheme more complex. The
4756 compression only affects the qualification of the name. Thus a name in
4757 the source:
4758
4759 @smallexample
4760 Very_Long_Package.Very_Long_Inner_Package.Var
4761 @end smallexample
4762
4763 @noindent
4764 would normally appear in these tables as:
4765
4766 @smallexample
4767 very_long_package__very_long_inner_package__var
4768 @end smallexample
4769
4770 @noindent
4771 but if the @option{-gnatC} switch is used, then the name appears as
4772
4773 @smallexample
4774 XCb7e0c705__var
4775 @end smallexample
4776
4777 @noindent
4778 Here b7e0c705 is a compressed encoding of the qualification prefix.
4779 The GNAT Ada aware version of GDB understands these encoded prefixes, so if this
4780 debugger is used, the encoding is largely hidden from the user of the compiler.
4781
4782 @end table
4783
4784 @item -gnatR[0|1|2|3][s]
4785 @cindex @option{-gnatR} (@code{gcc})
4786 This switch controls output from the compiler of a listing showing
4787 representation information for declared types and objects. For
4788 @option{-gnatR0}, no information is output (equivalent to omitting
4789 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
4790 so @option{-gnatR} with no parameter has the same effect), size and alignment
4791 information is listed for declared array and record types. For
4792 @option{-gnatR2}, size and alignment information is listed for all
4793 expression information for values that are computed at run time for
4794 variant records. These symbolic expressions have a mostly obvious
4795 format with #n being used to represent the value of the n'th
4796 discriminant. See source files @file{repinfo.ads/adb} in the
4797 @code{GNAT} sources for full detalis on the format of @option{-gnatR3}
4798 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
4799 the output is to a file with the name @file{file.rep} where
4800 file is the name of the corresponding source file.
4801
4802 @item -gnatx
4803 @cindex @option{-gnatx} (@code{gcc})
4804 Normally the compiler generates full cross-referencing information in
4805 the @file{ALI} file. This information is used by a number of tools,
4806 including @code{gnatfind} and @code{gnatxref}. The -gnatx switch
4807 suppresses this information. This saves some space and may slightly
4808 speed up compilation, but means that these tools cannot be used.
4809 @end table
4810
4811 @node Units to Sources Mapping Files
4812 @subsection Units to Sources Mapping Files
4813
4814 @table @code
4815
4816 @item -gnatem@var{path}
4817 @cindex @option{-gnatem} (@code{gcc})
4818 A mapping file is a way to communicate to the compiler two mappings:
4819 from unit names to file names (without any directory information) and from
4820 file names to path names (with full directory information). These mappings
4821 are used by the compiler to short-circuit the path search.
4822
4823 A mapping file is a sequence of sets of three lines. In each set,
4824 the first line is the unit name, in lower case, with "%s" appended for
4825 specifications and "%b" appended for bodies; the second line is the file
4826 name; and the third line is the path name.
4827
4828 Example:
4829 @smallexample
4830    main%b
4831    main.2.ada
4832    /gnat/project1/sources/main.2.ada
4833 @end smallexample
4834
4835 When the switch @option{-gnatem} is specified, the compiler will create
4836 in memory the two mappings from the specified file. If there is any problem
4837 (non existent file, truncated file or duplicate entries), no mapping
4838 will be created.
4839
4840 Several @option{-gnatem} switches may be specified; however, only the last
4841 one on the command line will be taken into account.
4842
4843 When using a project file, @code{gnatmake} create a temporary mapping file
4844 and communicates it to the compiler using this switch.
4845
4846 @end table
4847
4848 @node Search Paths and the Run-Time Library (RTL)
4849 @section Search Paths and the Run-Time Library (RTL)
4850
4851 @noindent
4852 With the GNAT source-based library system, the compiler must be able to
4853 find source files for units that are needed by the unit being compiled.
4854 Search paths are used to guide this process.
4855
4856 The compiler compiles one source file whose name must be given
4857 explicitly on the command line. In other words, no searching is done
4858 for this file. To find all other source files that are needed (the most
4859 common being the specs of units), the compiler examines the following
4860 directories, in the following order:
4861
4862 @enumerate
4863 @item
4864 The directory containing the source file of the main unit being compiled
4865 (the file name on the command line).
4866
4867 @item
4868 Each directory named by an @code{-I} switch given on the @code{gcc}
4869 command line, in the order given.
4870
4871 @item
4872 @findex ADA_INCLUDE_PATH
4873 Each of the directories listed in the value of the
4874 @code{ADA_INCLUDE_PATH} environment variable.
4875 Construct this value
4876 exactly as the @code{PATH} environment variable: a list of directory
4877 names separated by colons (semicolons when working with the NT version).
4878 @item
4879 The content of the "ada_source_path" file which is part of the GNAT
4880 installation tree and is used to store standard libraries such as the
4881 GNAT Run Time Library (RTL) source files.
4882 @ref{Installing an Ada Library}
4883 @end enumerate
4884
4885 @noindent
4886 Specifying the switch @code{-I-}
4887 inhibits the use of the directory
4888 containing the source file named in the command line. You can still
4889 have this directory on your search path, but in this case it must be
4890 explicitly requested with a @code{-I} switch.
4891
4892 Specifying the switch @code{-nostdinc}
4893 inhibits the search of the default location for the GNAT Run Time
4894 Library (RTL) source files.
4895
4896 The compiler outputs its object files and ALI files in the current
4897 working directory.
4898 Caution: The object file can be redirected with the @code{-o} switch;
4899 however, @code{gcc} and @code{gnat1} have not been coordinated on this
4900 so the ALI file will not go to the right place. Therefore, you should
4901 avoid using the @code{-o} switch.
4902
4903 @findex System.IO
4904 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
4905 children make up the GNAT RTL, together with the simple @code{System.IO}
4906 package used in the "Hello World" example. The sources for these units
4907 are needed by the compiler and are kept together in one directory. Not
4908 all of the bodies are needed, but all of the sources are kept together
4909 anyway. In a normal installation, you need not specify these directory
4910 names when compiling or binding. Either the environment variables or
4911 the built-in defaults cause these files to be found.
4912
4913 In addition to the language-defined hierarchies (System, Ada and
4914 Interfaces), the GNAT distribution provides a fourth hierarchy,
4915 consisting of child units of GNAT. This is a collection of generally
4916 useful routines. See the GNAT Reference Manual for further details.
4917
4918 Besides simplifying access to the RTL, a major use of search paths is
4919 in compiling sources from multiple directories. This can make
4920 development environments much more flexible.
4921
4922 @node Order of Compilation Issues
4923 @section Order of Compilation Issues
4924
4925 @noindent
4926 If, in our earlier example, there was a spec for the @code{hello}
4927 procedure, it would be contained in the file @file{hello.ads}; yet this
4928 file would not have to be explicitly compiled. This is the result of the
4929 model we chose to implement library management. Some of the consequences
4930 of this model are as follows:
4931
4932 @itemize @bullet
4933 @item
4934 There is no point in compiling specs (except for package
4935 specs with no bodies) because these are compiled as needed by clients. If
4936 you attempt a useless compilation, you will receive an error message.
4937 It is also useless to compile subunits because they are compiled as needed
4938 by the parent.
4939
4940 @item
4941 There are no order of compilation requirements: performing a
4942 compilation never obsoletes anything. The only way you can obsolete
4943 something and require recompilations is to modify one of the
4944 source files on which it depends.
4945
4946 @item
4947 There is no library as such, apart from the ALI files
4948 (@pxref{The Ada Library Information Files}, for information on the format of these
4949 files). For now we find it convenient to create separate ALI files, but
4950 eventually the information therein may be incorporated into the object
4951 file directly.
4952
4953 @item
4954 When you compile a unit, the source files for the specs of all units
4955 that it @code{with}'s, all its subunits, and the bodies of any generics it
4956 instantiates must be available (reachable by the search-paths mechanism
4957 described above), or you will receive a fatal error message.
4958 @end itemize
4959
4960 @node Examples
4961 @section Examples
4962
4963 @noindent
4964 The following are some typical Ada compilation command line examples:
4965
4966 @table @code
4967 @item $ gcc -c xyz.adb
4968 Compile body in file @file{xyz.adb} with all default options.
4969
4970 @item $ gcc -c -O2 -gnata xyz-def.adb
4971
4972 Compile the child unit package in file @file{xyz-def.adb} with extensive
4973 optimizations, and pragma @code{Assert}/@code{Debug} statements
4974 enabled.
4975
4976 @item $ gcc -c -gnatc abc-def.adb
4977 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
4978 mode.
4979 @end table
4980
4981 @node Binding Using gnatbind
4982 @chapter Binding Using @code{gnatbind}
4983 @findex gnatbind
4984
4985 @menu
4986 * Running gnatbind::
4987 * Generating the Binder Program in C::
4988 * Consistency-Checking Modes::
4989 * Binder Error Message Control::
4990 * Elaboration Control::
4991 * Output Control::
4992 * Binding with Non-Ada Main Programs::
4993 * Binding Programs with No Main Subprogram::
4994 * Summary of Binder Switches::
4995 * Command-Line Access::
4996 * Search Paths for gnatbind::
4997 * Examples of gnatbind Usage::
4998 @end menu
4999
5000 @noindent
5001 This chapter describes the GNAT binder, @code{gnatbind}, which is used
5002 to bind compiled GNAT objects. The @code{gnatbind} program performs
5003 four separate functions:
5004
5005 @enumerate
5006 @item
5007 Checks that a program is consistent, in accordance with the rules in
5008 Chapter 10 of the Ada 95 Reference Manual. In particular, error
5009 messages are generated if a program uses inconsistent versions of a
5010 given unit.
5011
5012 @item
5013 Checks that an acceptable order of elaboration exists for the program
5014 and issues an error message if it cannot find an order of elaboration
5015 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
5016
5017 @item
5018 Generates a main program incorporating the given elaboration order.
5019 This program is a small Ada package (body and spec) that
5020 must be subsequently compiled
5021 using the GNAT compiler. The necessary compilation step is usually
5022 performed automatically by @code{gnatlink}. The two most important
5023 functions of this program
5024 are to call the elaboration routines of units in an appropriate order
5025 and to call the main program.
5026
5027 @item
5028 Determines the set of object files required by the given main program.
5029 This information is output in the forms of comments in the generated program,
5030 to be read by the @code{gnatlink} utility used to link the Ada application.
5031 @end enumerate
5032
5033 @node Running gnatbind
5034 @section Running @code{gnatbind}
5035
5036 @noindent
5037 The form of the @code{gnatbind} command is
5038
5039 @smallexample
5040 $ gnatbind [@var{switches}] @var{mainprog}[.ali] [@var{switches}]
5041 @end smallexample
5042
5043 @noindent
5044 where @var{mainprog}.adb is the Ada file containing the main program
5045 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
5046 package in two files which names are
5047 @file{b~@var{ada_main}.ads}, and @file{b~@var{ada_main}.adb}.
5048 For example, if given the
5049 parameter @samp{hello.ali}, for a main program contained in file
5050 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
5051 and @file{b~hello.adb}.
5052
5053 When doing consistency checking, the binder takes into consideration
5054 any source files it can locate. For example, if the binder determines
5055 that the given main program requires the package @code{Pack}, whose
5056 @file{.ali}
5057 file is @file{pack.ali} and whose corresponding source spec file is
5058 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
5059 (using the same search path conventions as previously described for the
5060 @code{gcc} command). If it can locate this source file, it checks that
5061 the time stamps
5062 or source checksums of the source and its references to in @file{ali} files
5063 match. In other words, any @file{ali} files that mentions this spec must have
5064 resulted from compiling this version of the source file (or in the case
5065 where the source checksums match, a version close enough that the
5066 difference does not matter).
5067
5068 @cindex Source files, use by binder
5069 The effect of this consistency checking, which includes source files, is
5070 that the binder ensures that the program is consistent with the latest
5071 version of the source files that can be located at bind time. Editing a
5072 source file without compiling files that depend on the source file cause
5073 error messages to be generated by the binder.
5074
5075 For example, suppose you have a main program @file{hello.adb} and a
5076 package @code{P}, from file @file{p.ads} and you perform the following
5077 steps:
5078
5079 @enumerate
5080 @item
5081 Enter @code{gcc -c hello.adb} to compile the main program.
5082
5083 @item
5084 Enter @code{gcc -c p.ads} to compile package @code{P}.
5085
5086 @item
5087 Edit file @file{p.ads}.
5088
5089 @item
5090 Enter @code{gnatbind hello}.
5091 @end enumerate
5092
5093 At this point, the file @file{p.ali} contains an out-of-date time stamp
5094 because the file @file{p.ads} has been edited. The attempt at binding
5095 fails, and the binder generates the following error messages:
5096
5097 @smallexample
5098 error: "hello.adb" must be recompiled ("p.ads" has been modified)
5099 error: "p.ads" has been modified and must be recompiled
5100 @end smallexample
5101
5102 @noindent
5103 Now both files must be recompiled as indicated, and then the bind can
5104 succeed, generating a main program. You need not normally be concerned
5105 with the contents of this file, but it is similar to the following which
5106 is the binder file generated for a simple "hello world" program.
5107
5108 @smallexample
5109 @iftex
5110 @leftskip=0cm
5111 @end iftex
5112 --  The package is called Ada_Main unless this name is actually used
5113 --  as a unit name in the partition, in which case some other unique
5114 --  name is used.
5115
5116 with System;
5117 package ada_main is
5118
5119    Elab_Final_Code : Integer;
5120    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
5121
5122    --  The main program saves the parameters (argument count,
5123    --  argument values, environment pointer) in global variables
5124    --  for later access by other units including
5125    --  Ada.Command_Line.
5126
5127    gnat_argc : Integer;
5128    gnat_argv : System.Address;
5129    gnat_envp : System.Address;
5130
5131    --  The actual variables are stored in a library routine. This
5132    --  is useful for some shared library situations, where there
5133    --  are problems if variables are not in the library.
5134
5135    pragma Import (C, gnat_argc);
5136    pragma Import (C, gnat_argv);
5137    pragma Import (C, gnat_envp);
5138
5139    --  The exit status is similarly an external location
5140
5141    gnat_exit_status : Integer;
5142    pragma Import (C, gnat_exit_status);
5143
5144    GNAT_Version : constant String :=
5145                     "GNAT Version: 3.15w (20010315)";
5146    pragma Export (C, GNAT_Version, "__gnat_version");
5147
5148    --  This is the generated adafinal routine that performs
5149    --  finalization at the end of execution. In the case where
5150    --  Ada is the main program, this main program makes a call
5151    --  to adafinal at program termination.
5152
5153    procedure adafinal;
5154    pragma Export (C, adafinal, "adafinal");
5155
5156    --  This is the generated adainit routine that performs
5157    --  initialization at the start of execution. In the case
5158    --  where Ada is the main program, this main program makes
5159    --  a call to adainit at program startup.
5160
5161    procedure adainit;
5162    pragma Export (C, adainit, "adainit");
5163
5164    --  This routine is called at the start of execution. It is
5165    --  a dummy routine that is used by the debugger to breakpoint
5166    --  at the start of execution.
5167
5168    procedure Break_Start;
5169    pragma Import (C, Break_Start, "__gnat_break_start");
5170
5171    --  This is the actual generated main program (it would be
5172    --  suppressed if the no main program switch were used). As
5173    --  required by standard system conventions, this program has
5174    --  the external name main.
5175
5176    function main
5177      (argc : Integer;
5178       argv : System.Address;
5179       envp : System.Address)
5180       return Integer;
5181    pragma Export (C, main, "main");
5182
5183    --  The following set of constants give the version
5184    --  identification values for every unit in the bound
5185    --  partition. This identification is computed from all
5186    --  dependent semantic units, and corresponds to the
5187    --  string that would be returned by use of the
5188    --  Body_Version or Version attributes.
5189
5190    type Version_32 is mod 2 ** 32;
5191    u00001 : constant Version_32 := 16#7880BEB3#;
5192    u00002 : constant Version_32 := 16#0D24CBD0#;
5193    u00003 : constant Version_32 := 16#3283DBEB#;
5194    u00004 : constant Version_32 := 16#2359F9ED#;
5195    u00005 : constant Version_32 := 16#664FB847#;
5196    u00006 : constant Version_32 := 16#68E803DF#;
5197    u00007 : constant Version_32 := 16#5572E604#;
5198    u00008 : constant Version_32 := 16#46B173D8#;
5199    u00009 : constant Version_32 := 16#156A40CF#;
5200    u00010 : constant Version_32 := 16#033DABE0#;
5201    u00011 : constant Version_32 := 16#6AB38FEA#;
5202    u00012 : constant Version_32 := 16#22B6217D#;
5203    u00013 : constant Version_32 := 16#68A22947#;
5204    u00014 : constant Version_32 := 16#18CC4A56#;
5205    u00015 : constant Version_32 := 16#08258E1B#;
5206    u00016 : constant Version_32 := 16#367D5222#;
5207    u00017 : constant Version_32 := 16#20C9ECA4#;
5208    u00018 : constant Version_32 := 16#50D32CB6#;
5209    u00019 : constant Version_32 := 16#39A8BB77#;
5210    u00020 : constant Version_32 := 16#5CF8FA2B#;
5211    u00021 : constant Version_32 := 16#2F1EB794#;
5212    u00022 : constant Version_32 := 16#31AB6444#;
5213    u00023 : constant Version_32 := 16#1574B6E9#;
5214    u00024 : constant Version_32 := 16#5109C189#;
5215    u00025 : constant Version_32 := 16#56D770CD#;
5216    u00026 : constant Version_32 := 16#02F9DE3D#;
5217    u00027 : constant Version_32 := 16#08AB6B2C#;
5218    u00028 : constant Version_32 := 16#3FA37670#;
5219    u00029 : constant Version_32 := 16#476457A0#;
5220    u00030 : constant Version_32 := 16#731E1B6E#;
5221    u00031 : constant Version_32 := 16#23C2E789#;
5222    u00032 : constant Version_32 := 16#0F1BD6A1#;
5223    u00033 : constant Version_32 := 16#7C25DE96#;
5224    u00034 : constant Version_32 := 16#39ADFFA2#;
5225    u00035 : constant Version_32 := 16#571DE3E7#;
5226    u00036 : constant Version_32 := 16#5EB646AB#;
5227    u00037 : constant Version_32 := 16#4249379B#;
5228    u00038 : constant Version_32 := 16#0357E00A#;
5229    u00039 : constant Version_32 := 16#3784FB72#;
5230    u00040 : constant Version_32 := 16#2E723019#;
5231    u00041 : constant Version_32 := 16#623358EA#;
5232    u00042 : constant Version_32 := 16#107F9465#;
5233    u00043 : constant Version_32 := 16#6843F68A#;
5234    u00044 : constant Version_32 := 16#63305874#;
5235    u00045 : constant Version_32 := 16#31E56CE1#;
5236    u00046 : constant Version_32 := 16#02917970#;
5237    u00047 : constant Version_32 := 16#6CCBA70E#;
5238    u00048 : constant Version_32 := 16#41CD4204#;
5239    u00049 : constant Version_32 := 16#572E3F58#;
5240    u00050 : constant Version_32 := 16#20729FF5#;
5241    u00051 : constant Version_32 := 16#1D4F93E8#;
5242    u00052 : constant Version_32 := 16#30B2EC3D#;
5243    u00053 : constant Version_32 := 16#34054F96#;
5244    u00054 : constant Version_32 := 16#5A199860#;
5245    u00055 : constant Version_32 := 16#0E7F912B#;
5246    u00056 : constant Version_32 := 16#5760634A#;
5247    u00057 : constant Version_32 := 16#5D851835#;
5248
5249    --  The following Export pragmas export the version numbers
5250    --  with symbolic names ending in B (for body) or S
5251    --  (for spec) so that they can be located in a link. The
5252    --  information provided here is sufficient to track down
5253    --  the exact versions of units used in a given build.
5254
5255    pragma Export (C, u00001, "helloB");
5256    pragma Export (C, u00002, "system__standard_libraryB");
5257    pragma Export (C, u00003, "system__standard_libraryS");
5258    pragma Export (C, u00004, "adaS");
5259    pragma Export (C, u00005, "ada__text_ioB");
5260    pragma Export (C, u00006, "ada__text_ioS");
5261    pragma Export (C, u00007, "ada__exceptionsB");
5262    pragma Export (C, u00008, "ada__exceptionsS");
5263    pragma Export (C, u00009, "gnatS");
5264    pragma Export (C, u00010, "gnat__heap_sort_aB");
5265    pragma Export (C, u00011, "gnat__heap_sort_aS");
5266    pragma Export (C, u00012, "systemS");
5267    pragma Export (C, u00013, "system__exception_tableB");
5268    pragma Export (C, u00014, "system__exception_tableS");
5269    pragma Export (C, u00015, "gnat__htableB");
5270    pragma Export (C, u00016, "gnat__htableS");
5271    pragma Export (C, u00017, "system__exceptionsS");
5272    pragma Export (C, u00018, "system__machine_state_operationsB");
5273    pragma Export (C, u00019, "system__machine_state_operationsS");
5274    pragma Export (C, u00020, "system__machine_codeS");
5275    pragma Export (C, u00021, "system__storage_elementsB");
5276    pragma Export (C, u00022, "system__storage_elementsS");
5277    pragma Export (C, u00023, "system__secondary_stackB");
5278    pragma Export (C, u00024, "system__secondary_stackS");
5279    pragma Export (C, u00025, "system__parametersB");
5280    pragma Export (C, u00026, "system__parametersS");
5281    pragma Export (C, u00027, "system__soft_linksB");
5282    pragma Export (C, u00028, "system__soft_linksS");
5283    pragma Export (C, u00029, "system__stack_checkingB");
5284    pragma Export (C, u00030, "system__stack_checkingS");
5285    pragma Export (C, u00031, "system__tracebackB");
5286    pragma Export (C, u00032, "system__tracebackS");
5287    pragma Export (C, u00033, "ada__streamsS");
5288    pragma Export (C, u00034, "ada__tagsB");
5289    pragma Export (C, u00035, "ada__tagsS");
5290    pragma Export (C, u00036, "system__string_opsB");
5291    pragma Export (C, u00037, "system__string_opsS");
5292    pragma Export (C, u00038, "interfacesS");
5293    pragma Export (C, u00039, "interfaces__c_streamsB");
5294    pragma Export (C, u00040, "interfaces__c_streamsS");
5295    pragma Export (C, u00041, "system__file_ioB");
5296    pragma Export (C, u00042, "system__file_ioS");
5297    pragma Export (C, u00043, "ada__finalizationB");
5298    pragma Export (C, u00044, "ada__finalizationS");
5299    pragma Export (C, u00045, "system__finalization_rootB");
5300    pragma Export (C, u00046, "system__finalization_rootS");
5301    pragma Export (C, u00047, "system__finalization_implementationB");
5302    pragma Export (C, u00048, "system__finalization_implementationS");
5303    pragma Export (C, u00049, "system__string_ops_concat_3B");
5304    pragma Export (C, u00050, "system__string_ops_concat_3S");
5305    pragma Export (C, u00051, "system__stream_attributesB");
5306    pragma Export (C, u00052, "system__stream_attributesS");
5307    pragma Export (C, u00053, "ada__io_exceptionsS");
5308    pragma Export (C, u00054, "system__unsigned_typesS");
5309    pragma Export (C, u00055, "system__file_control_blockS");
5310    pragma Export (C, u00056, "ada__finalization__list_controllerB");
5311    pragma Export (C, u00057, "ada__finalization__list_controllerS");
5312
5313    -- BEGIN ELABORATION ORDER
5314    -- ada (spec)
5315    -- gnat (spec)
5316    -- gnat.heap_sort_a (spec)
5317    -- gnat.heap_sort_a (body)
5318    -- gnat.htable (spec)
5319    -- gnat.htable (body)
5320    -- interfaces (spec)
5321    -- system (spec)
5322    -- system.machine_code (spec)
5323    -- system.parameters (spec)
5324    -- system.parameters (body)
5325    -- interfaces.c_streams (spec)
5326    -- interfaces.c_streams (body)
5327    -- system.standard_library (spec)
5328    -- ada.exceptions (spec)
5329    -- system.exception_table (spec)
5330    -- system.exception_table (body)
5331    -- ada.io_exceptions (spec)
5332    -- system.exceptions (spec)
5333    -- system.storage_elements (spec)
5334    -- system.storage_elements (body)
5335    -- system.machine_state_operations (spec)
5336    -- system.machine_state_operations (body)
5337    -- system.secondary_stack (spec)
5338    -- system.stack_checking (spec)
5339    -- system.soft_links (spec)
5340    -- system.soft_links (body)
5341    -- system.stack_checking (body)
5342    -- system.secondary_stack (body)
5343    -- system.standard_library (body)
5344    -- system.string_ops (spec)
5345    -- system.string_ops (body)
5346    -- ada.tags (spec)
5347    -- ada.tags (body)
5348    -- ada.streams (spec)
5349    -- system.finalization_root (spec)
5350    -- system.finalization_root (body)
5351    -- system.string_ops_concat_3 (spec)
5352    -- system.string_ops_concat_3 (body)
5353    -- system.traceback (spec)
5354    -- system.traceback (body)
5355    -- ada.exceptions (body)
5356    -- system.unsigned_types (spec)
5357    -- system.stream_attributes (spec)
5358    -- system.stream_attributes (body)
5359    -- system.finalization_implementation (spec)
5360    -- system.finalization_implementation (body)
5361    -- ada.finalization (spec)
5362    -- ada.finalization (body)
5363    -- ada.finalization.list_controller (spec)
5364    -- ada.finalization.list_controller (body)
5365    -- system.file_control_block (spec)
5366    -- system.file_io (spec)
5367    -- system.file_io (body)
5368    -- ada.text_io (spec)
5369    -- ada.text_io (body)
5370    -- hello (body)
5371    -- END ELABORATION ORDER
5372
5373 end ada_main;
5374
5375 --  The following source file name pragmas allow the generated file
5376 --  names to be unique for different main programs. They are needed
5377 --  since the package name will always be Ada_Main.
5378
5379 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
5380 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
5381
5382 --  Generated package body for Ada_Main starts here
5383
5384 package body ada_main is
5385
5386    --  The actual finalization is performed by calling the
5387    --  library routine in System.Standard_Library.Adafinal
5388
5389    procedure Do_Finalize;
5390    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
5391
5392    -------------
5393    -- adainit --
5394    -------------
5395
5396 @findex adainit
5397    procedure adainit is
5398
5399       --  These booleans are set to True once the associated unit has
5400       --  been elaborated. It is also used to avoid elaborating the
5401       --  same unit twice.
5402
5403       E040 : Boolean; pragma Import (Ada, E040, "interfaces__c_streams_E");
5404       E008 : Boolean; pragma Import (Ada, E008, "ada__exceptions_E");
5405       E014 : Boolean; pragma Import (Ada, E014, "system__exception_table_E");
5406       E053 : Boolean; pragma Import (Ada, E053, "ada__io_exceptions_E");
5407       E017 : Boolean; pragma Import (Ada, E017, "system__exceptions_E");
5408       E024 : Boolean; pragma Import (Ada, E024, "system__secondary_stack_E");
5409       E030 : Boolean; pragma Import (Ada, E030, "system__stack_checking_E");
5410       E028 : Boolean; pragma Import (Ada, E028, "system__soft_links_E");
5411       E035 : Boolean; pragma Import (Ada, E035, "ada__tags_E");
5412       E033 : Boolean; pragma Import (Ada, E033, "ada__streams_E");
5413       E046 : Boolean; pragma Import (Ada, E046, "system__finalization_root_E");
5414       E048 : Boolean; pragma Import (Ada, E048, "system__finalization_implementation_E");
5415       E044 : Boolean; pragma Import (Ada, E044, "ada__finalization_E");
5416       E057 : Boolean; pragma Import (Ada, E057, "ada__finalization__list_controller_E");
5417       E055 : Boolean; pragma Import (Ada, E055, "system__file_control_block_E");
5418       E042 : Boolean; pragma Import (Ada, E042, "system__file_io_E");
5419       E006 : Boolean; pragma Import (Ada, E006, "ada__text_io_E");
5420
5421       --  Set_Globals is a library routine that stores away the
5422       --  value of the indicated set of global values in global
5423       --  variables within the library.
5424
5425       procedure Set_Globals
5426         (Main_Priority            : Integer;
5427          Time_Slice_Value         : Integer;
5428          WC_Encoding              : Character;
5429          Locking_Policy           : Character;
5430          Queuing_Policy           : Character;
5431          Task_Dispatching_Policy  : Character;
5432          Adafinal                 : System.Address;
5433          Unreserve_All_Interrupts : Integer;
5434          Exception_Tracebacks     : Integer);
5435 @findex __gnat_set_globals
5436       pragma Import (C, Set_Globals, "__gnat_set_globals");
5437
5438       --  SDP_Table_Build is a library routine used to build the
5439       --  exception tables. See unit Ada.Exceptions in files
5440       --  a-except.ads/adb for full details of how zero cost
5441       --  exception handling works. This procedure, the call to
5442       --  it, and the two following tables are all omitted if the
5443       --  build is in longjmp/setjump exception mode.
5444
5445 @findex SDP_Table_Build
5446 @findex Zero Cost Exceptions
5447       procedure SDP_Table_Build
5448         (SDP_Addresses   : System.Address;
5449          SDP_Count       : Natural;
5450          Elab_Addresses  : System.Address;
5451          Elab_Addr_Count : Natural);
5452       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
5453
5454       --  Table of Unit_Exception_Table addresses. Used for zero
5455       --  cost exception handling to build the top level table.
5456
5457       ST : aliased constant array (1 .. 23) of System.Address := (
5458         Hello'UET_Address,
5459         Ada.Text_Io'UET_Address,
5460         Ada.Exceptions'UET_Address,
5461         Gnat.Heap_Sort_A'UET_Address,
5462         System.Exception_Table'UET_Address,
5463         System.Machine_State_Operations'UET_Address,
5464         System.Secondary_Stack'UET_Address,
5465         System.Parameters'UET_Address,
5466         System.Soft_Links'UET_Address,
5467         System.Stack_Checking'UET_Address,
5468         System.Traceback'UET_Address,
5469         Ada.Streams'UET_Address,
5470         Ada.Tags'UET_Address,
5471         System.String_Ops'UET_Address,
5472         Interfaces.C_Streams'UET_Address,
5473         System.File_Io'UET_Address,
5474         Ada.Finalization'UET_Address,
5475         System.Finalization_Root'UET_Address,
5476         System.Finalization_Implementation'UET_Address,
5477         System.String_Ops_Concat_3'UET_Address,
5478         System.Stream_Attributes'UET_Address,
5479         System.File_Control_Block'UET_Address,
5480         Ada.Finalization.List_Controller'UET_Address);
5481
5482       --  Table of addresses of elaboration routines. Used for
5483       --  zero cost exception handling to make sure these
5484       --  addresses are included in the top level procedure
5485       --  address table.
5486
5487       EA : aliased constant array (1 .. 23) of System.Address := (
5488         adainit'Code_Address,
5489         Do_Finalize'Code_Address,
5490         Ada.Exceptions'Elab_Spec'Address,
5491         System.Exceptions'Elab_Spec'Address,
5492         Interfaces.C_Streams'Elab_Spec'Address,
5493         System.Exception_Table'Elab_Body'Address,
5494         Ada.Io_Exceptions'Elab_Spec'Address,
5495         System.Stack_Checking'Elab_Spec'Address,
5496         System.Soft_Links'Elab_Body'Address,
5497         System.Secondary_Stack'Elab_Body'Address,
5498         Ada.Tags'Elab_Spec'Address,
5499         Ada.Tags'Elab_Body'Address,
5500         Ada.Streams'Elab_Spec'Address,
5501         System.Finalization_Root'Elab_Spec'Address,
5502         Ada.Exceptions'Elab_Body'Address,
5503         System.Finalization_Implementation'Elab_Spec'Address,
5504         System.Finalization_Implementation'Elab_Body'Address,
5505         Ada.Finalization'Elab_Spec'Address,
5506         Ada.Finalization.List_Controller'Elab_Spec'Address,
5507         System.File_Control_Block'Elab_Spec'Address,
5508         System.File_Io'Elab_Body'Address,
5509         Ada.Text_Io'Elab_Spec'Address,
5510         Ada.Text_Io'Elab_Body'Address);
5511
5512    --  Start of processing for adainit
5513
5514    begin
5515
5516       --  Call SDP_Table_Build to build the top level procedure
5517       --  table for zero cost exception handling (omitted in
5518       --  longjmp/setjump mode).
5519
5520       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
5521
5522       --  Call Set_Globals to record various information for
5523       --  this partition.  The values are derived by the binder
5524       --  from information stored in the ali files by the compiler.
5525
5526 @findex __gnat_set_globals
5527       Set_Globals
5528         (Main_Priority            => -1,
5529          --  Priority of main program, -1 if no pragma Priority used
5530
5531          Time_Slice_Value         => -1,
5532          --  Time slice from Time_Slice pragma, -1 if none used
5533
5534          WC_Encoding              => 'b',
5535          --  Wide_Character encoding used, default is brackets
5536
5537          Locking_Policy           => ' ',
5538          --  Locking_Policy used, default of space means not
5539          --  specified, otherwise it is the first character of
5540          --  the policy name.
5541
5542          Queuing_Policy           => ' ',
5543          --  Queuing_Policy used, default of space means not
5544          --  specified, otherwise it is the first character of
5545          --  the policy name.
5546
5547          Task_Dispatching_Policy  => ' ',
5548          --  Task_Dispatching_Policy used, default of space means
5549          --  not specified, otherwise first character of the
5550          --  policy name.
5551
5552          Adafinal                 => System.Null_Address,
5553          --  Address of Adafinal routine, not used anymore
5554
5555          Unreserve_All_Interrupts => 0,
5556          --  Set true if pragma Unreserve_All_Interrupts was used
5557
5558          Exception_Tracebacks     => 0);
5559          --  Indicates if exception tracebacks are enabled
5560
5561       Elab_Final_Code := 1;
5562
5563       --  Now we have the elaboration calls for all units in the partition.
5564       --  The Elab_Spec and Elab_Body attributes generate references to the
5565       --  implicit elaboration procedures generated by the compiler for
5566       --  each unit that requires elaboration.
5567
5568       if not E040 then
5569          Interfaces.C_Streams'Elab_Spec;
5570       end if;
5571       E040 := True;
5572       if not E008 then
5573          Ada.Exceptions'Elab_Spec;
5574       end if;
5575       if not E014 then
5576          System.Exception_Table'Elab_Body;
5577          E014 := True;
5578       end if;
5579       if not E053 then
5580          Ada.Io_Exceptions'Elab_Spec;
5581          E053 := True;
5582       end if;
5583       if not E017 then
5584          System.Exceptions'Elab_Spec;
5585          E017 := True;
5586       end if;
5587       if not E030 then
5588          System.Stack_Checking'Elab_Spec;
5589       end if;
5590       if not E028 then
5591          System.Soft_Links'Elab_Body;
5592          E028 := True;
5593       end if;
5594       E030 := True;
5595       if not E024 then
5596          System.Secondary_Stack'Elab_Body;
5597          E024 := True;
5598       end if;
5599       if not E035 then
5600          Ada.Tags'Elab_Spec;
5601       end if;
5602       if not E035 then
5603          Ada.Tags'Elab_Body;
5604          E035 := True;
5605       end if;
5606       if not E033 then
5607          Ada.Streams'Elab_Spec;
5608          E033 := True;
5609       end if;
5610       if not E046 then
5611          System.Finalization_Root'Elab_Spec;
5612       end if;
5613       E046 := True;
5614       if not E008 then
5615          Ada.Exceptions'Elab_Body;
5616          E008 := True;
5617       end if;
5618       if not E048 then
5619          System.Finalization_Implementation'Elab_Spec;
5620       end if;
5621       if not E048 then
5622          System.Finalization_Implementation'Elab_Body;
5623          E048 := True;
5624       end if;
5625       if not E044 then
5626          Ada.Finalization'Elab_Spec;
5627       end if;
5628       E044 := True;
5629       if not E057 then
5630          Ada.Finalization.List_Controller'Elab_Spec;
5631       end if;
5632       E057 := True;
5633       if not E055 then
5634          System.File_Control_Block'Elab_Spec;
5635          E055 := True;
5636       end if;
5637       if not E042 then
5638          System.File_Io'Elab_Body;
5639          E042 := True;
5640       end if;
5641       if not E006 then
5642          Ada.Text_Io'Elab_Spec;
5643       end if;
5644       if not E006 then
5645          Ada.Text_Io'Elab_Body;
5646          E006 := True;
5647       end if;
5648
5649       Elab_Final_Code := 0;
5650    end adainit;
5651
5652    --------------
5653    -- adafinal --
5654    --------------
5655
5656 @findex adafinal
5657    procedure adafinal is
5658    begin
5659       Do_Finalize;
5660    end adafinal;
5661
5662    ----------
5663    -- main --
5664    ----------
5665
5666    --  main is actually a function, as in the ANSI C standard,
5667    --  defined to return the exit status. The three parameters
5668    --  are the argument count, argument values and environment
5669    --  pointer.
5670
5671 @findex Main Program
5672    function main
5673      (argc : Integer;
5674       argv : System.Address;
5675       envp : System.Address)
5676       return Integer
5677    is
5678       --  The initialize routine performs low level system
5679       --  initialization using a standard library routine which
5680       --  sets up signal handling and performs any other
5681       --  required setup. The routine can be found in file
5682       --  a-init.c.
5683
5684 @findex __gnat_initialize
5685       procedure initialize;
5686       pragma Import (C, initialize, "__gnat_initialize");
5687
5688       --  The finalize routine performs low level system
5689       --  finalization using a standard library routine. The
5690       --  routine is found in file a-final.c and in the standard
5691       --  distribution is a dummy routine that does nothing, so
5692       --  really this is a hook for special user finalization.
5693
5694 @findex __gnat_finalize
5695       procedure finalize;
5696       pragma Import (C, finalize, "__gnat_finalize");
5697
5698       --  We get to the main program of the partition by using
5699       --  pragma Import because if we try to with the unit and
5700       --  call it Ada style, then not only do we waste time
5701       --  recompiling it, but also, we don't really know the right
5702       --  switches (e.g. identifier character set) to be used
5703       --  to compile it.
5704
5705       procedure Ada_Main_Program;
5706       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
5707
5708    --  Start of processing for main
5709
5710    begin
5711       --  Save global variables
5712
5713       gnat_argc := argc;
5714       gnat_argv := argv;
5715       gnat_envp := envp;
5716
5717       --  Call low level system initialization
5718
5719       Initialize;
5720
5721       --  Call our generated Ada initialization routine
5722
5723       adainit;
5724
5725       --  This is the point at which we want the debugger to get
5726       --  control
5727
5728       Break_Start;
5729
5730       --  Now we call the main program of the partition
5731
5732       Ada_Main_Program;
5733
5734       --  Perform Ada finalization
5735
5736       adafinal;
5737
5738       --  Perform low level system finalization
5739
5740       Finalize;
5741
5742       --  Return the proper exit status
5743       return (gnat_exit_status);
5744    end;
5745
5746 --  This section is entirely comments, so it has no effect on the
5747 --  compilation of the Ada_Main package. It provides the list of
5748 --  object files and linker options, as well as some standard
5749 --  libraries needed for the link. The gnatlink utility parses
5750 --  this b~hello.adb file to read these comment lines to generate
5751 --  the appropriate command line arguments for the call to the
5752 --  system linker. The BEGIN/END lines are used for sentinels for
5753 --  this parsing operation.
5754
5755 --  The exact file names will of course depend on the environment,
5756 --  host/target and location of files on the host system.
5757
5758 @findex Object file list
5759 -- BEGIN Object file/option list
5760    --   ./hello.o
5761    --   -L./
5762    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
5763    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
5764 -- END Object file/option list
5765
5766 end ada_main;
5767
5768 @end smallexample
5769
5770 @noindent
5771 The Ada code in the above example is exactly what is generated by the
5772 binder. We have added comments to more clearly indicate the function
5773 of each part of the generated @code{Ada_Main} package.
5774
5775 The code is standard Ada in all respects, and can be processed by any
5776 tools that handle Ada. In particular, it is possible to use the debugger
5777 in Ada mode to debug the generated Ada_Main package. For example, suppose
5778 that for reasons that you do not understand, your program is blowing up
5779 during elaboration of the body of @code{Ada.Text_IO}. To chase this bug
5780 down, you can place a breakpoint on the call:
5781
5782 @smallexample
5783 Ada.Text_Io'Elab_Body;
5784 @end smallexample
5785
5786 @noindent
5787 and trace the elaboration routine for this package to find out where
5788 the problem might be (more usually of course you would be debugging
5789 elaboration code in your own application).
5790
5791 @node Generating the Binder Program in C
5792 @section Generating the Binder Program in C
5793 @noindent
5794 In most normal usage, the default mode of @code{gnatbind} which is to
5795 generate the main package in Ada, as described in the previous section.
5796 In particular, this means that any Ada programmer can read and understand
5797 the generated main program. It can also be debugged just like any other
5798 Ada code provided the @code{-g} switch is used for @code{gnatbind}
5799 and @code{gnatlink}.
5800
5801 However for some purposes it may be convenient to generate the main
5802 program in C rather than Ada. This may for example be helpful when you
5803 are generating a mixed language program with the main program in C. The
5804 GNAT compiler itself is an example. The use of the @code{-C} switch
5805 for both @code{gnatbind} and @code{gnatlink} will cause the program to
5806 be generated in C (and compiled using the gnu C compiler). The
5807 following shows the C code generated for the same "Hello World"
5808 program:
5809
5810 @smallexample
5811
5812 #ifdef __STDC__
5813 #define PARAMS(paramlist) paramlist
5814 #else
5815 #define PARAMS(paramlist) ()
5816 #endif
5817
5818 extern void __gnat_set_globals
5819  PARAMS ((int, int, int, int, int, int,
5820           void (*) PARAMS ((void)), int, int));
5821 extern void adafinal PARAMS ((void));
5822 extern void adainit PARAMS ((void));
5823 extern void system__standard_library__adafinal PARAMS ((void));
5824 extern int main PARAMS ((int, char **, char **));
5825 extern void exit PARAMS ((int));
5826 extern void __gnat_break_start PARAMS ((void));
5827 extern void _ada_hello PARAMS ((void));
5828 extern void __gnat_initialize PARAMS ((void));
5829 extern void __gnat_finalize PARAMS ((void));
5830
5831 extern void ada__exceptions___elabs PARAMS ((void));
5832 extern void system__exceptions___elabs PARAMS ((void));
5833 extern void interfaces__c_streams___elabs PARAMS ((void));
5834 extern void system__exception_table___elabb PARAMS ((void));
5835 extern void ada__io_exceptions___elabs PARAMS ((void));
5836 extern void system__stack_checking___elabs PARAMS ((void));
5837 extern void system__soft_links___elabb PARAMS ((void));
5838 extern void system__secondary_stack___elabb PARAMS ((void));
5839 extern void ada__tags___elabs PARAMS ((void));
5840 extern void ada__tags___elabb PARAMS ((void));
5841 extern void ada__streams___elabs PARAMS ((void));
5842 extern void system__finalization_root___elabs PARAMS ((void));
5843 extern void ada__exceptions___elabb PARAMS ((void));
5844 extern void system__finalization_implementation___elabs PARAMS ((void));
5845 extern void system__finalization_implementation___elabb PARAMS ((void));
5846 extern void ada__finalization___elabs PARAMS ((void));
5847 extern void ada__finalization__list_controller___elabs PARAMS ((void));
5848 extern void system__file_control_block___elabs PARAMS ((void));
5849 extern void system__file_io___elabb PARAMS ((void));
5850 extern void ada__text_io___elabs PARAMS ((void));
5851 extern void ada__text_io___elabb PARAMS ((void));
5852
5853 extern int __gnat_inside_elab_final_code;
5854
5855 extern int gnat_argc;
5856 extern char **gnat_argv;
5857 extern char **gnat_envp;
5858 extern int gnat_exit_status;
5859
5860 char __gnat_version[] = "GNAT Version: 3.15w (20010315)";
5861 void adafinal () @{
5862    system__standard_library__adafinal ();
5863 @}
5864
5865 void adainit ()
5866 @{
5867    extern char ada__exceptions_E;
5868    extern char system__exceptions_E;
5869    extern char interfaces__c_streams_E;
5870    extern char system__exception_table_E;
5871    extern char ada__io_exceptions_E;
5872    extern char system__secondary_stack_E;
5873    extern char system__stack_checking_E;
5874    extern char system__soft_links_E;
5875    extern char ada__tags_E;
5876    extern char ada__streams_E;
5877    extern char system__finalization_root_E;
5878    extern char system__finalization_implementation_E;
5879    extern char ada__finalization_E;
5880    extern char ada__finalization__list_controller_E;
5881    extern char system__file_control_block_E;
5882    extern char system__file_io_E;
5883    extern char ada__text_io_E;
5884
5885    extern void *__gnat_hello__SDP;
5886    extern void *__gnat_ada__text_io__SDP;
5887    extern void *__gnat_ada__exceptions__SDP;
5888    extern void *__gnat_gnat__heap_sort_a__SDP;
5889    extern void *__gnat_system__exception_table__SDP;
5890    extern void *__gnat_system__machine_state_operations__SDP;
5891    extern void *__gnat_system__secondary_stack__SDP;
5892    extern void *__gnat_system__parameters__SDP;
5893    extern void *__gnat_system__soft_links__SDP;
5894    extern void *__gnat_system__stack_checking__SDP;
5895    extern void *__gnat_system__traceback__SDP;
5896    extern void *__gnat_ada__streams__SDP;
5897    extern void *__gnat_ada__tags__SDP;
5898    extern void *__gnat_system__string_ops__SDP;
5899    extern void *__gnat_interfaces__c_streams__SDP;
5900    extern void *__gnat_system__file_io__SDP;
5901    extern void *__gnat_ada__finalization__SDP;
5902    extern void *__gnat_system__finalization_root__SDP;
5903    extern void *__gnat_system__finalization_implementation__SDP;
5904    extern void *__gnat_system__string_ops_concat_3__SDP;
5905    extern void *__gnat_system__stream_attributes__SDP;
5906    extern void *__gnat_system__file_control_block__SDP;
5907    extern void *__gnat_ada__finalization__list_controller__SDP;
5908
5909    void **st[23] = @{
5910      &__gnat_hello__SDP,
5911      &__gnat_ada__text_io__SDP,
5912      &__gnat_ada__exceptions__SDP,
5913      &__gnat_gnat__heap_sort_a__SDP,
5914      &__gnat_system__exception_table__SDP,
5915      &__gnat_system__machine_state_operations__SDP,
5916      &__gnat_system__secondary_stack__SDP,
5917      &__gnat_system__parameters__SDP,
5918      &__gnat_system__soft_links__SDP,
5919      &__gnat_system__stack_checking__SDP,
5920      &__gnat_system__traceback__SDP,
5921      &__gnat_ada__streams__SDP,
5922      &__gnat_ada__tags__SDP,
5923      &__gnat_system__string_ops__SDP,
5924      &__gnat_interfaces__c_streams__SDP,
5925      &__gnat_system__file_io__SDP,
5926      &__gnat_ada__finalization__SDP,
5927      &__gnat_system__finalization_root__SDP,
5928      &__gnat_system__finalization_implementation__SDP,
5929      &__gnat_system__string_ops_concat_3__SDP,
5930      &__gnat_system__stream_attributes__SDP,
5931      &__gnat_system__file_control_block__SDP,
5932      &__gnat_ada__finalization__list_controller__SDP@};
5933
5934    extern void ada__exceptions___elabs ();
5935    extern void system__exceptions___elabs ();
5936    extern void interfaces__c_streams___elabs ();
5937    extern void system__exception_table___elabb ();
5938    extern void ada__io_exceptions___elabs ();
5939    extern void system__stack_checking___elabs ();
5940    extern void system__soft_links___elabb ();
5941    extern void system__secondary_stack___elabb ();
5942    extern void ada__tags___elabs ();
5943    extern void ada__tags___elabb ();
5944    extern void ada__streams___elabs ();
5945    extern void system__finalization_root___elabs ();
5946    extern void ada__exceptions___elabb ();
5947    extern void system__finalization_implementation___elabs ();
5948    extern void system__finalization_implementation___elabb ();
5949    extern void ada__finalization___elabs ();
5950    extern void ada__finalization__list_controller___elabs ();
5951    extern void system__file_control_block___elabs ();
5952    extern void system__file_io___elabb ();
5953    extern void ada__text_io___elabs ();
5954    extern void ada__text_io___elabb ();
5955
5956    void (*ea[23]) () = @{
5957      adainit,
5958      system__standard_library__adafinal,
5959      ada__exceptions___elabs,
5960      system__exceptions___elabs,
5961      interfaces__c_streams___elabs,
5962      system__exception_table___elabb,
5963      ada__io_exceptions___elabs,
5964      system__stack_checking___elabs,
5965      system__soft_links___elabb,
5966      system__secondary_stack___elabb,
5967      ada__tags___elabs,
5968      ada__tags___elabb,
5969      ada__streams___elabs,
5970      system__finalization_root___elabs,
5971      ada__exceptions___elabb,
5972      system__finalization_implementation___elabs,
5973      system__finalization_implementation___elabb,
5974      ada__finalization___elabs,
5975      ada__finalization__list_controller___elabs,
5976      system__file_control_block___elabs,
5977      system__file_io___elabb,
5978      ada__text_io___elabs,
5979      ada__text_io___elabb@};
5980
5981    __gnat_SDP_Table_Build (&st, 23, ea, 23);
5982    __gnat_set_globals (
5983       -1,      /* Main_Priority              */
5984       -1,      /* Time_Slice_Value           */
5985       'b',     /* WC_Encoding                */
5986       ' ',     /* Locking_Policy             */
5987       ' ',     /* Queuing_Policy             */
5988       ' ',     /* Tasking_Dispatching_Policy */
5989       0,       /* Finalization routine address, not used anymore */
5990       0,       /* Unreserve_All_Interrupts */
5991       0);      /* Exception_Tracebacks */
5992
5993    __gnat_inside_elab_final_code = 1;
5994
5995    if (ada__exceptions_E == 0) @{
5996       ada__exceptions___elabs ();
5997    @}
5998    if (system__exceptions_E == 0) @{
5999       system__exceptions___elabs ();
6000       system__exceptions_E++;
6001    @}
6002    if (interfaces__c_streams_E == 0) @{
6003       interfaces__c_streams___elabs ();
6004    @}
6005    interfaces__c_streams_E = 1;
6006    if (system__exception_table_E == 0) @{
6007       system__exception_table___elabb ();
6008       system__exception_table_E++;
6009    @}
6010    if (ada__io_exceptions_E == 0) @{
6011       ada__io_exceptions___elabs ();
6012       ada__io_exceptions_E++;
6013    @}
6014    if (system__stack_checking_E == 0) @{
6015       system__stack_checking___elabs ();
6016    @}
6017    if (system__soft_links_E == 0) @{
6018       system__soft_links___elabb ();
6019       system__soft_links_E++;
6020    @}
6021    system__stack_checking_E = 1;
6022    if (system__secondary_stack_E == 0) @{
6023       system__secondary_stack___elabb ();
6024       system__secondary_stack_E++;
6025    @}
6026    if (ada__tags_E == 0) @{
6027       ada__tags___elabs ();
6028    @}
6029    if (ada__tags_E == 0) @{
6030       ada__tags___elabb ();
6031       ada__tags_E++;
6032    @}
6033    if (ada__streams_E == 0) @{
6034       ada__streams___elabs ();
6035       ada__streams_E++;
6036    @}
6037    if (system__finalization_root_E == 0) @{
6038       system__finalization_root___elabs ();
6039    @}
6040    system__finalization_root_E = 1;
6041    if (ada__exceptions_E == 0) @{
6042       ada__exceptions___elabb ();
6043       ada__exceptions_E++;
6044    @}
6045    if (system__finalization_implementation_E == 0) @{
6046       system__finalization_implementation___elabs ();
6047    @}
6048    if (system__finalization_implementation_E == 0) @{
6049       system__finalization_implementation___elabb ();
6050       system__finalization_implementation_E++;
6051    @}
6052    if (ada__finalization_E == 0) @{
6053       ada__finalization___elabs ();
6054    @}
6055    ada__finalization_E = 1;
6056    if (ada__finalization__list_controller_E == 0) @{
6057       ada__finalization__list_controller___elabs ();
6058    @}
6059    ada__finalization__list_controller_E = 1;
6060    if (system__file_control_block_E == 0) @{
6061       system__file_control_block___elabs ();
6062       system__file_control_block_E++;
6063    @}
6064    if (system__file_io_E == 0) @{
6065       system__file_io___elabb ();
6066       system__file_io_E++;
6067    @}
6068    if (ada__text_io_E == 0) @{
6069       ada__text_io___elabs ();
6070    @}
6071    if (ada__text_io_E == 0) @{
6072       ada__text_io___elabb ();
6073       ada__text_io_E++;
6074    @}
6075
6076    __gnat_inside_elab_final_code = 0;
6077 @}
6078 int main (argc, argv, envp)
6079     int argc;
6080     char **argv;
6081     char **envp;
6082 @{
6083    gnat_argc = argc;
6084    gnat_argv = argv;
6085    gnat_envp = envp;
6086
6087    __gnat_initialize ();
6088    adainit ();
6089    __gnat_break_start ();
6090
6091    _ada_hello ();
6092
6093    system__standard_library__adafinal ();
6094    __gnat_finalize ();
6095    exit (gnat_exit_status);
6096 @}
6097 unsigned helloB = 0x7880BEB3;
6098 unsigned system__standard_libraryB = 0x0D24CBD0;
6099 unsigned system__standard_libraryS = 0x3283DBEB;
6100 unsigned adaS = 0x2359F9ED;
6101 unsigned ada__text_ioB = 0x47C85FC4;
6102 unsigned ada__text_ioS = 0x496FE45C;
6103 unsigned ada__exceptionsB = 0x74F50187;
6104 unsigned ada__exceptionsS = 0x6736945B;
6105 unsigned gnatS = 0x156A40CF;
6106 unsigned gnat__heap_sort_aB = 0x033DABE0;
6107 unsigned gnat__heap_sort_aS = 0x6AB38FEA;
6108 unsigned systemS = 0x0331C6FE;
6109 unsigned system__exceptionsS = 0x20C9ECA4;
6110 unsigned system__exception_tableB = 0x68A22947;
6111 unsigned system__exception_tableS = 0x394BADD5;
6112 unsigned gnat__htableB = 0x08258E1B;
6113 unsigned gnat__htableS = 0x367D5222;
6114 unsigned system__machine_state_operationsB = 0x4F3B7492;
6115 unsigned system__machine_state_operationsS = 0x182F5CF4;
6116 unsigned system__storage_elementsB = 0x2F1EB794;
6117 unsigned system__storage_elementsS = 0x102C83C7;
6118 unsigned system__secondary_stackB = 0x1574B6E9;
6119 unsigned system__secondary_stackS = 0x708E260A;
6120 unsigned system__parametersB = 0x56D770CD;
6121 unsigned system__parametersS = 0x237E39BE;
6122 unsigned system__soft_linksB = 0x08AB6B2C;
6123 unsigned system__soft_linksS = 0x1E2491F3;
6124 unsigned system__stack_checkingB = 0x476457A0;
6125 unsigned system__stack_checkingS = 0x5299FCED;
6126 unsigned system__tracebackB = 0x2971EBDE;
6127 unsigned system__tracebackS = 0x2E9C3122;
6128 unsigned ada__streamsS = 0x7C25DE96;
6129 unsigned ada__tagsB = 0x39ADFFA2;
6130 unsigned ada__tagsS = 0x769A0464;
6131 unsigned system__string_opsB = 0x5EB646AB;
6132 unsigned system__string_opsS = 0x63CED018;
6133 unsigned interfacesS = 0x0357E00A;
6134 unsigned interfaces__c_streamsB = 0x3784FB72;
6135 unsigned interfaces__c_streamsS = 0x2E723019;
6136 unsigned system__file_ioB = 0x623358EA;
6137 unsigned system__file_ioS = 0x31F873E6;
6138 unsigned ada__finalizationB = 0x6843F68A;
6139 unsigned ada__finalizationS = 0x63305874;
6140 unsigned system__finalization_rootB = 0x31E56CE1;
6141 unsigned system__finalization_rootS = 0x23169EF3;
6142 unsigned system__finalization_implementationB = 0x6CCBA70E;
6143 unsigned system__finalization_implementationS = 0x604AA587;
6144 unsigned system__string_ops_concat_3B = 0x572E3F58;
6145 unsigned system__string_ops_concat_3S = 0x01F57876;
6146 unsigned system__stream_attributesB = 0x1D4F93E8;
6147 unsigned system__stream_attributesS = 0x30B2EC3D;
6148 unsigned ada__io_exceptionsS = 0x34054F96;
6149 unsigned system__unsigned_typesS = 0x7B9E7FE3;
6150 unsigned system__file_control_blockS = 0x2FF876A8;
6151 unsigned ada__finalization__list_controllerB = 0x5760634A;
6152 unsigned ada__finalization__list_controllerS = 0x5D851835;
6153
6154 /* BEGIN ELABORATION ORDER
6155 ada (spec)
6156 gnat (spec)
6157 gnat.heap_sort_a (spec)
6158 gnat.htable (spec)
6159 gnat.htable (body)
6160 interfaces (spec)
6161 system (spec)
6162 system.parameters (spec)
6163 system.standard_library (spec)
6164 ada.exceptions (spec)
6165 system.exceptions (spec)
6166 system.parameters (body)
6167 gnat.heap_sort_a (body)
6168 interfaces.c_streams (spec)
6169 interfaces.c_streams (body)
6170 system.exception_table (spec)
6171 system.exception_table (body)
6172 ada.io_exceptions (spec)
6173 system.storage_elements (spec)
6174 system.storage_elements (body)
6175 system.machine_state_operations (spec)
6176 system.machine_state_operations (body)
6177 system.secondary_stack (spec)
6178 system.stack_checking (spec)
6179 system.soft_links (spec)
6180 system.soft_links (body)
6181 system.stack_checking (body)
6182 system.secondary_stack (body)
6183 system.standard_library (body)
6184 system.string_ops (spec)
6185 system.string_ops (body)
6186 ada.tags (spec)
6187 ada.tags (body)
6188 ada.streams (spec)
6189 system.finalization_root (spec)
6190 system.finalization_root (body)
6191 system.string_ops_concat_3 (spec)
6192 system.string_ops_concat_3 (body)
6193 system.traceback (spec)
6194 system.traceback (body)
6195 ada.exceptions (body)
6196 system.unsigned_types (spec)
6197 system.stream_attributes (spec)
6198 system.stream_attributes (body)
6199 system.finalization_implementation (spec)
6200 system.finalization_implementation (body)
6201 ada.finalization (spec)
6202 ada.finalization (body)
6203 ada.finalization.list_controller (spec)
6204 ada.finalization.list_controller (body)
6205 system.file_control_block (spec)
6206 system.file_io (spec)
6207 system.file_io (body)
6208 ada.text_io (spec)
6209 ada.text_io (body)
6210 hello (body)
6211    END ELABORATION ORDER */
6212
6213 /* BEGIN Object file/option list
6214 ./hello.o
6215 -L./
6216 -L/usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/
6217 /usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/libgnat.a
6218 -lexc
6219    END Object file/option list */
6220
6221 @end smallexample
6222
6223 @noindent
6224 Here again, the C code is exactly what is generated by the binder. The
6225 functions of the various parts of this code correspond in an obvious
6226 manner with the commented Ada code shown in the example in the previous
6227 section.
6228
6229 @node Consistency-Checking Modes
6230 @section Consistency-Checking Modes
6231
6232 @noindent
6233 As described in the previous section, by default @code{gnatbind} checks
6234 that object files are consistent with one another and are consistent
6235 with any source files it can locate. The following switches control binder
6236 access to sources.
6237
6238 @table @code
6239 @item -s
6240 @cindex @code{-s} (@code{gnatbind})
6241 Require source files to be present. In this mode, the binder must be
6242 able to locate all source files that are referenced, in order to check
6243 their consistency. In normal mode, if a source file cannot be located it
6244 is simply ignored. If you specify this switch, a missing source
6245 file is an error.
6246
6247 @item -x
6248 @cindex @code{-x} (@code{gnatbind})
6249 Exclude source files. In this mode, the binder only checks that ALI
6250 files are consistent with one another. Source files are not accessed.
6251 The binder runs faster in this mode, and there is still a guarantee that
6252 the resulting program is self-consistent.
6253 If a source file has been edited since it was last compiled, and you
6254 specify this switch, the binder will not detect that the object
6255 file is out of date with respect to the source file. Note that this is the
6256 mode that is automatically used by @code{gnatmake} because in this
6257 case the checking against sources has already been performed by
6258 @code{gnatmake} in the course of compilation (i.e. before binding).
6259
6260 @end table
6261
6262 @node Binder Error Message Control
6263 @section Binder Error Message Control
6264
6265 @noindent
6266 The following switches provide control over the generation of error
6267 messages from the binder:
6268
6269 @table @code
6270 @item -v
6271 @cindex @code{-v} (@code{gnatbind})
6272 Verbose mode. In the normal mode, brief error messages are generated to
6273 @file{stderr}. If this switch is present, a header is written
6274 to @file{stdout} and any error messages are directed to @file{stdout}.
6275 All that is written to @file{stderr} is a brief summary message.
6276
6277 @item -b
6278 @cindex @code{-b} (@code{gnatbind})
6279 Generate brief error messages to @file{stderr} even if verbose mode is
6280 specified. This is relevant only when used with the
6281 @code{-v} switch.
6282
6283 @item -m@var{n}
6284 @cindex @code{-m} (@code{gnatbind})
6285 Limits the number of error messages to @var{n}, a decimal integer in the
6286 range 1-999. The binder terminates immediately if this limit is reached.
6287
6288 @item -M@var{xxx}
6289 @cindex @code{-M} (@code{gnatbind})
6290 Renames the generated main program from @code{main} to @code{xxx}.
6291 This is useful in the case of some cross-building environments, where
6292 the actual main program is separate from the one generated
6293 by @code{gnatbind}.
6294
6295 @item -ws
6296 @cindex @code{-ws} (@code{gnatbind})
6297 @cindex Warnings
6298 Suppress all warning messages.
6299
6300 @item -we
6301 @cindex @code{-we} (@code{gnatbind})
6302 Treat any warning messages as fatal errors.
6303
6304
6305 @item -t
6306 @cindex @code{-t} (@code{gnatbind})
6307 @cindex Time stamp checks, in binder
6308 @cindex Binder consistency checks
6309 @cindex Consistency checks, in binder
6310 The binder performs a number of consistency checks including:
6311
6312 @itemize @bullet
6313 @item
6314 Check that time stamps of a given source unit are consistent
6315 @item
6316 Check that checksums of a given source unit are consistent
6317 @item
6318 Check that consistent versions of @code{GNAT} were used for compilation
6319 @item
6320 Check consistency of configuration pragmas as required
6321 @end itemize
6322
6323 @noindent
6324 Normally failure of such checks, in accordance with the consistency
6325 requirements of the Ada Reference Manual, causes error messages to be
6326 generated which abort the binder and prevent the output of a binder
6327 file and subsequent link to obtain an executable.
6328
6329 The @code{-t} switch converts these error messages
6330 into warnings, so that
6331 binding and linking can continue to completion even in the presence of such
6332 errors. The result may be a failed link (due to missing symbols), or a
6333 non-functional executable which has undefined semantics.
6334 @emph{This means that
6335 @code{-t} should be used only in unusual situations,
6336 with extreme care.}
6337 @end table
6338
6339 @node Elaboration Control
6340 @section Elaboration Control
6341
6342 @noindent
6343 The following switches provide additional control over the elaboration
6344 order. For full details see @xref{Elaboration Order Handling in GNAT}.
6345
6346 @table @code
6347 @item -p
6348 @cindex @code{-h} (@code{gnatbind})
6349 Normally the binder attempts to choose an elaboration order that is
6350 likely to minimize the likelihood of an elaboration order error resulting
6351 in raising a @code{Program_Error} exception. This switch reverses the
6352 action of the binder, and requests that it deliberately choose an order
6353 that is likely to maximize the likelihood of an elaboration error.
6354 This is useful in ensuring portability and avoiding dependence on
6355 accidental fortuitous elaboration ordering.
6356
6357 Normally it only makes sense to use the @code{-p} switch if dynamic
6358 elaboration checking is used (@option{-gnatE} switch used for compilation).
6359 This is because in the default static elaboration mode, all necessary
6360 @code{Elaborate_All} pragmas are implicitly inserted. These implicit
6361 pragmas are still respected by the binder in @code{-p} mode, so a
6362 safe elaboration order is assured.
6363 @end table
6364
6365 @node Output Control
6366 @section Output Control
6367
6368 @noindent
6369 The following switches allow additional control over the output
6370 generated by the binder.
6371
6372 @table @code
6373
6374 @item -A
6375 @cindex @code{-A} (@code{gnatbind})
6376 Generate binder program in Ada (default). The binder program is named
6377 @file{b~@var{mainprog}.adb} by default. This can be changed with
6378 @code{-o} @code{gnatbind} option.
6379
6380 @item -c
6381 @cindex @code{-c} (@code{gnatbind})
6382 Check only. Do not generate the binder output file. In this mode the
6383 binder performs all error checks but does not generate an output file.
6384
6385 @item -C
6386 @cindex @code{-C} (@code{gnatbind})
6387 Generate binder program in C. The binder program is named
6388 @file{b_@var{mainprog}.c}. This can be changed with @code{-o} @code{gnatbind}
6389 option.
6390
6391 @item -e
6392 @cindex @code{-e} (@code{gnatbind})
6393 Output complete list of elaboration-order dependencies, showing the
6394 reason for each dependency. This output can be rather extensive but may
6395 be useful in diagnosing problems with elaboration order. The output is
6396 written to @file{stdout}.
6397
6398 @item -h
6399 @cindex @code{-h} (@code{gnatbind})
6400 Output usage information. The output is written to @file{stdout}.
6401
6402 @item -K
6403 @cindex @code{-K} (@code{gnatbind})
6404 Output linker options to @file{stdout}. Includes library search paths,
6405 contents of pragmas Ident and Linker_Options, and libraries added
6406 by @code{gnatbind}.
6407
6408 @item -l
6409 @cindex @code{-l} (@code{gnatbind})
6410 Output chosen elaboration order. The output is written to @file{stdout}.
6411
6412 @item -O
6413 @cindex @code{-O} (@code{gnatbind})
6414 Output full names of all the object files that must be linked to provide
6415 the Ada component of the program. The output is written to @file{stdout}.
6416 This list includes the files explicitly supplied and referenced by the user
6417 as well as implicitly referenced run-time unit files. The latter are
6418 omitted if the corresponding units reside in shared libraries. The
6419 directory names for the run-time units depend on the system configuration.
6420
6421 @item -o @var{file}
6422 @cindex @code{-o} (@code{gnatbind})
6423 Set name of output file to @var{file} instead of the normal
6424 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
6425 binder generated body filename. In C mode you would normally give
6426 @var{file} an extension of @file{.c} because it will be a C source program.
6427 Note that if this option is used, then linking must be done manually.
6428 It is not possible to use gnatlink in this case, since it cannot locate
6429 the binder file.
6430
6431 @item -r
6432 @cindex @code{-r} (@code{gnatbind})
6433 Generate list of @code{pragma Rerstrictions} that could be applied to
6434 the current unit. This is useful for code audit purposes, and also may
6435 be used to improve code generation in some cases.
6436
6437 @end table
6438
6439 @node Binding with Non-Ada Main Programs
6440 @section Binding with Non-Ada Main Programs
6441
6442 @noindent
6443 In our description so far we have assumed that the main
6444 program is in Ada, and that the task of the binder is to generate a
6445 corresponding function @code{main} that invokes this Ada main
6446 program. GNAT also supports the building of executable programs where
6447 the main program is not in Ada, but some of the called routines are
6448 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
6449 The following switch is used in this situation:
6450
6451 @table @code
6452 @item -n
6453 @cindex @code{-n} (@code{gnatbind})
6454 No main program. The main program is not in Ada.
6455 @end table
6456
6457 @noindent
6458 In this case, most of the functions of the binder are still required,
6459 but instead of generating a main program, the binder generates a file
6460 containing the following callable routines:
6461
6462 @table @code
6463 @item adainit
6464 @findex adainit
6465 You must call this routine to initialize the Ada part of the program by
6466 calling the necessary elaboration routines. A call to @code{adainit} is
6467 required before the first call to an Ada subprogram.
6468
6469 Note that it is assumed that the basic execution environment must be setup
6470 to be appropriate for Ada execution at the point where the first Ada
6471 subprogram is called. In particular, if the Ada code will do any
6472 floating-point operations, then the FPU must be setup in an appropriate
6473 manner. For the case of the x86, for example, full precision mode is
6474 required. The procedure GNAT.Float_Control.Reset may be used to ensure
6475 that the FPU is in the right state.
6476
6477 @item adafinal
6478 @findex adafinal
6479 You must call this routine to perform any library-level finalization
6480 required by the Ada subprograms. A call to @code{adafinal} is required
6481 after the last call to an Ada subprogram, and before the program
6482 terminates.
6483 @end table
6484
6485 @noindent
6486 If the @code{-n} switch
6487 @cindex Binder, multiple input files
6488 is given, more than one ALI file may appear on
6489 the command line for @code{gnatbind}. The normal @dfn{closure}
6490 calculation is performed for each of the specified units. Calculating
6491 the closure means finding out the set of units involved by tracing
6492 @code{with} references. The reason it is necessary to be able to
6493 specify more than one ALI file is that a given program may invoke two or
6494 more quite separate groups of Ada units.
6495
6496 The binder takes the name of its output file from the last specified ALI
6497 file, unless overridden by the use of the @code{-o file}.
6498 The output is an Ada unit in source form that can
6499 be compiled with GNAT unless the -C switch is used in which case the
6500 output is a C source file, which must be compiled using the C compiler.
6501 This compilation occurs automatically as part of the @code{gnatlink}
6502 processing.
6503
6504 Currently the GNAT run time requires a FPU using 80 bits mode
6505 precision. Under targets where this is not the default it is required to
6506 call GNAT.Float_Control.Reset before using floating point numbers (this
6507 include float computation, float input and output) in the Ada code. A
6508 side effect is that this could be the wrong mode for the foreign code
6509 where floating point computation could be broken after this call.
6510
6511 @node Binding Programs with No Main Subprogram
6512 @section Binding Programs with No Main Subprogram
6513
6514 @noindent
6515 It is possible to have an Ada program which does not have a main
6516 subprogram. This program will call the elaboration routines of all the
6517 packages, then the finalization routines.
6518
6519 The following switch is used to bind programs organized in this manner:
6520
6521 @table @code
6522 @item -z
6523 @cindex @code{-z} (@code{gnatbind})
6524 Normally the binder checks that the unit name given on the command line
6525 corresponds to a suitable main subprogram. When this switch is used,
6526 a list of ALI files can be given, and the execution of the program
6527 consists of elaboration of these units in an appropriate order.
6528 @end table
6529
6530 @node Summary of Binder Switches
6531 @section Summary of Binder Switches
6532
6533 @noindent
6534 The following are the switches available with @code{gnatbind}:
6535
6536 @table @code
6537 @item -aO
6538 Specify directory to be searched for ALI files.
6539
6540 @item -aI
6541 Specify directory to be searched for source file.
6542
6543 @item -A
6544 Generate binder program in Ada (default)
6545
6546 @item -b
6547 Generate brief messages to @file{stderr} even if verbose mode set.
6548
6549 @item -c
6550 Check only, no generation of binder output file.
6551
6552 @item -C
6553 Generate binder program in C
6554
6555 @item -e
6556 Output complete list of elaboration-order dependencies.
6557
6558 @item -E
6559 Store tracebacks in exception occurrences when the target supports it.
6560 This is the default with the zero cost exception mechanism.
6561 This option is currently supported on the following targets:
6562 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6563 See also the packages @code{GNAT.Traceback} and
6564 @code{GNAT.Traceback.Symbolic} for more information.
6565 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
6566 @code{gcc} option.
6567
6568 @item -h
6569 Output usage (help) information
6570
6571 @item -I
6572 Specify directory to be searched for source and ALI files.
6573
6574 @item -I-
6575 Do not look for sources in the current directory where @code{gnatbind} was
6576 invoked, and do not look for ALI files in the directory containing the
6577 ALI file named in the @code{gnatbind} command line.
6578
6579 @item -l
6580 Output chosen elaboration order.
6581
6582 @item -Lxxx
6583 Binds the units for library building. In this case the adainit and
6584 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
6585 are renamed to xxxinit and xxxfinal. Implies -n.
6586 See @pxref{GNAT and Libraries} for more details.
6587
6588 @item -Mxyz
6589 Rename generated main program from main to xyz
6590
6591 @item -m@var{n}
6592 Limit number of detected errors to @var{n} (1-999).
6593
6594 @item -n
6595 No main program.
6596
6597 @item -nostdinc
6598 Do not look for sources in the system default directory.
6599
6600 @item -nostdlib
6601 Do not look for library files in the system default directory.
6602
6603 @item --RTS=@var{rts-path}
6604 @cindex @code{--RTS} (@code{gnatbind})
6605 Specifies the default location of the runtime library. Same meaning as the
6606 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
6607
6608 @item -o @var{file}
6609 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
6610 Note that if this option is used, then linking must be done manually,
6611 gnatlink cannot be used.
6612
6613 @item -O
6614 Output object list.
6615
6616 @item -p
6617 Pessimistic (worst-case) elaboration order
6618
6619 @item -s
6620 Require all source files to be present.
6621
6622 @item -static
6623 Link against a static GNAT run time.
6624
6625 @item -shared
6626 Link against a shared GNAT run time when available.
6627
6628 @item -t
6629 Tolerate time stamp and other consistency errors
6630
6631 @item -T@var{n}
6632 Set the time slice value to n microseconds. A value of zero means no time
6633 slicing and also indicates to the tasking run time to match as close as
6634 possible to the annex D requirements of the RM.
6635
6636 @item -v
6637 Verbose mode. Write error messages, header, summary output to
6638 @file{stdout}.
6639
6640 @item -w@var{x}
6641 Warning mode (@var{x}=s/e for suppress/treat as error)
6642
6643
6644 @item -x
6645 Exclude source files (check object consistency only).
6646
6647
6648 @item -z
6649 No main subprogram.
6650
6651 @end table
6652
6653 You may obtain this listing by running the program @code{gnatbind} with
6654 no arguments.
6655
6656 @node Command-Line Access
6657 @section Command-Line Access
6658
6659 @noindent
6660 The package @code{Ada.Command_Line} provides access to the command-line
6661 arguments and program name. In order for this interface to operate
6662 correctly, the two variables
6663
6664 @smallexample
6665 @group
6666 @cartouche
6667 int gnat_argc;
6668 char **gnat_argv;
6669 @end cartouche
6670 @end group
6671 @end smallexample
6672
6673 @noindent
6674 @findex gnat_argv
6675 @findex gnat_argc
6676 are declared in one of the GNAT library routines. These variables must
6677 be set from the actual @code{argc} and @code{argv} values passed to the
6678 main program. With no @code{n} present, @code{gnatbind}
6679 generates the C main program to automatically set these variables.
6680 If the @code{n} switch is used, there is no automatic way to
6681 set these variables. If they are not set, the procedures in
6682 @code{Ada.Command_Line} will not be available, and any attempt to use
6683 them will raise @code{Constraint_Error}. If command line access is
6684 required, your main program must set @code{gnat_argc} and
6685 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
6686 it.
6687
6688 @node Search Paths for gnatbind
6689 @section Search Paths for @code{gnatbind}
6690
6691 @noindent
6692 The binder takes the name of an ALI file as its argument and needs to
6693 locate source files as well as other ALI files to verify object consistency.
6694
6695 For source files, it follows exactly the same search rules as @code{gcc}
6696 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
6697 directories searched are:
6698
6699 @enumerate
6700 @item
6701 The directory containing the ALI file named in the command line, unless
6702 the switch @code{-I-} is specified.
6703
6704 @item
6705 All directories specified by @code{-I}
6706 switches on the @code{gnatbind}
6707 command line, in the order given.
6708
6709 @item
6710 @findex ADA_OBJECTS_PATH
6711 Each of the directories listed in the value of the
6712 @code{ADA_OBJECTS_PATH} environment variable.
6713 Construct this value
6714 exactly as the @code{PATH} environment variable: a list of directory
6715 names separated by colons (semicolons when working with the NT version
6716 of GNAT).
6717
6718 @item
6719 The content of the "ada_object_path" file which is part of the GNAT
6720 installation tree and is used to store standard libraries such as the
6721 GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is
6722 specified.
6723 @ref{Installing an Ada Library}
6724 @end enumerate
6725
6726 @noindent
6727 In the binder the switch @code{-I}
6728 is used to specify both source and
6729 library file paths. Use @code{-aI}
6730 instead if you want to specify
6731 source paths only, and @code{-aO}
6732 if you want to specify library paths
6733 only. This means that for the binder
6734 @code{-I}@var{dir} is equivalent to
6735 @code{-aI}@var{dir}
6736 @code{-aO}@var{dir}.
6737 The binder generates the bind file (a C language source file) in the
6738 current working directory.
6739
6740 @findex Ada
6741 @findex System
6742 @findex Interfaces
6743 @findex GNAT
6744 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6745 children make up the GNAT Run-Time Library, together with the package
6746 GNAT and its children, which contain a set of useful additional
6747 library functions provided by GNAT. The sources for these units are
6748 needed by the compiler and are kept together in one directory. The ALI
6749 files and object files generated by compiling the RTL are needed by the
6750 binder and the linker and are kept together in one directory, typically
6751 different from the directory containing the sources. In a normal
6752 installation, you need not specify these directory names when compiling
6753 or binding. Either the environment variables or the built-in defaults
6754 cause these files to be found.
6755
6756 Besides simplifying access to the RTL, a major use of search paths is
6757 in compiling sources from multiple directories. This can make
6758 development environments much more flexible.
6759
6760 @node Examples of gnatbind Usage
6761 @section Examples of @code{gnatbind} Usage
6762
6763 @noindent
6764 This section contains a number of examples of using the GNAT binding
6765 utility @code{gnatbind}.
6766
6767 @table @code
6768 @item gnatbind hello
6769 The main program @code{Hello} (source program in @file{hello.adb}) is
6770 bound using the standard switch settings. The generated main program is
6771 @file{b~hello.adb}. This is the normal, default use of the binder.
6772
6773 @item gnatbind hello -o mainprog.adb
6774 The main program @code{Hello} (source program in @file{hello.adb}) is
6775 bound using the standard switch settings. The generated main program is
6776 @file{mainprog.adb} with the associated spec in
6777 @file{mainprog.ads}. Note that you must specify the body here not the
6778 spec, in the case where the output is in Ada. Note that if this option
6779 is used, then linking must be done manually, since gnatlink will not
6780 be able to find the generated file.
6781
6782 @item gnatbind main -C -o mainprog.c -x
6783 The main program @code{Main} (source program in
6784 @file{main.adb}) is bound, excluding source files from the
6785 consistency checking, generating
6786 the file @file{mainprog.c}.
6787
6788 @item gnatbind -x main_program -C -o mainprog.c
6789 This command is exactly the same as the previous example. Switches may
6790 appear anywhere in the command line, and single letter switches may be
6791 combined into a single switch.
6792
6793 @item gnatbind -n math dbase -C -o ada-control.c
6794 The main program is in a language other than Ada, but calls to
6795 subprograms in packages @code{Math} and @code{Dbase} appear. This call
6796 to @code{gnatbind} generates the file @file{ada-control.c} containing
6797 the @code{adainit} and @code{adafinal} routines to be called before and
6798 after accessing the Ada units.
6799 @end table
6800
6801 @node Linking Using gnatlink
6802 @chapter Linking Using @code{gnatlink}
6803 @findex gnatlink
6804
6805 @noindent
6806 This chapter discusses @code{gnatlink}, a utility program used to link
6807 Ada programs and build an executable file. This is a simple program
6808 that invokes the Unix linker (via the @code{gcc}
6809 command) with a correct list of object files and library references.
6810 @code{gnatlink} automatically determines the list of files and
6811 references for the Ada part of a program. It uses the binder file
6812 generated by the binder to determine this list.
6813
6814 @menu
6815 * Running gnatlink::
6816 * Switches for gnatlink::
6817 * Setting Stack Size from gnatlink::
6818 * Setting Heap Size from gnatlink::
6819 @end menu
6820
6821 @node Running gnatlink
6822 @section Running @code{gnatlink}
6823
6824 @noindent
6825 The form of the @code{gnatlink} command is
6826
6827 @smallexample
6828 $ gnatlink [@var{switches}] @var{mainprog}[.ali] [@var{non-Ada objects}]
6829       [@var{linker options}]
6830 @end smallexample
6831
6832 @noindent
6833 @file{@var{mainprog}.ali} references the ALI file of the main program.
6834 The @file{.ali} extension of this file can be omitted. From this
6835 reference, @code{gnatlink} locates the corresponding binder file
6836 @file{b~@var{mainprog}.adb} and, using the information in this file along
6837 with the list of non-Ada objects and linker options, constructs a Unix
6838 linker command file to create the executable.
6839
6840 The arguments following @file{@var{mainprog}.ali} are passed to the
6841 linker uninterpreted. They typically include the names of object files
6842 for units written in other languages than Ada and any library references
6843 required to resolve references in any of these foreign language units,
6844 or in @code{pragma Import} statements in any Ada units.
6845
6846 @var{linker options} is an optional list of linker specific
6847 switches. The default linker called by gnatlink is @var{gcc} which in
6848 turn calls the appropriate system linker usually called
6849 @var{ld}. Standard options for the linker such as @code{-lmy_lib} or
6850 @code{-Ldir} can be added as is. For options that are not recognized by
6851 @var{gcc} as linker options, the @var{gcc} switches @code{-Xlinker} or
6852 @code{-Wl,} shall be used. Refer to the GCC documentation for
6853 details. Here is an example showing how to generate a linker map
6854 assuming that the underlying linker is GNU ld:
6855
6856 @smallexample
6857 $ gnatlink my_prog -Wl,-Map,MAPFILE
6858 @end smallexample
6859
6860 Using @var{linker options} it is possible to set the program stack and
6861 heap size. See @pxref{Setting Stack Size from gnatlink} and
6862 @pxref{Setting Heap Size from gnatlink}.
6863
6864 @code{gnatlink} determines the list of objects required by the Ada
6865 program and prepends them to the list of objects passed to the linker.
6866 @code{gnatlink} also gathers any arguments set by the use of
6867 @code{pragma Linker_Options} and adds them to the list of arguments
6868 presented to the linker.
6869
6870
6871 @node Switches for gnatlink
6872 @section Switches for @code{gnatlink}
6873
6874 @noindent
6875 The following switches are available with the @code{gnatlink} utility:
6876
6877 @table @code
6878
6879 @item -A
6880 @cindex @code{-A} (@code{gnatlink})
6881 The binder has generated code in Ada. This is the default.
6882
6883 @item -C
6884 @cindex @code{-C} (@code{gnatlink})
6885 If instead of generating a file in Ada, the binder has generated one in
6886 C, then the linker needs to know about it. Use this switch to signal
6887 to @code{gnatlink} that the binder has generated C code rather than
6888 Ada code.
6889
6890 @item -f
6891 @cindex Command line length
6892 @cindex @code{-f} (@code{gnatlink})
6893 On some targets, the command line length is limited, and @code{gnatlink}
6894 will generate a separate file for the linker if the list of object files
6895 is too long. The @code{-f} flag forces this file to be generated even if
6896 the limit is not exceeded. This is useful in some cases to deal with
6897 special situations where the command line length is exceeded.
6898
6899 @item -g
6900 @cindex Debugging information, including
6901 @cindex @code{-g} (@code{gnatlink})
6902 The option to include debugging information causes the Ada bind file (in
6903 other words, @file{b~@var{mainprog}.adb}) to be compiled with
6904 @code{-g}.
6905 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
6906 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
6907 Without @code{-g}, the binder removes these files by
6908 default. The same procedure apply if a C bind file was generated using
6909 @code{-C} @code{gnatbind} option, in this case the filenames are
6910 @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
6911
6912 @item -n
6913 @cindex @code{-n} (@code{gnatlink})
6914 Do not compile the file generated by the binder. This may be used when
6915 a link is rerun with different options, but there is no need to recompile
6916 the binder file.
6917
6918 @item -v
6919 @cindex @code{-v} (@code{gnatlink})
6920 Causes additional information to be output, including a full list of the
6921 included object files. This switch option is most useful when you want
6922 to see what set of object files are being used in the link step.
6923
6924 @item -v -v
6925 @cindex @code{-v -v} (@code{gnatlink})
6926 Very verbose mode. Requests that the compiler operate in verbose mode when
6927 it compiles the binder file, and that the system linker run in verbose mode.
6928
6929 @item -o @var{exec-name}
6930 @cindex @code{-o} (@code{gnatlink})
6931 @var{exec-name} specifies an alternate name for the generated
6932 executable program. If this switch is omitted, the executable has the same
6933 name as the main unit. For example, @code{gnatlink try.ali} creates
6934 an executable called @file{try}.
6935
6936 @item -b @var{target}
6937 @cindex @code{-b} (@code{gnatlink})
6938 Compile your program to run on @var{target}, which is the name of a
6939 system configuration. You must have a GNAT cross-compiler built if
6940 @var{target} is not the same as your host system.
6941
6942 @item -B@var{dir}
6943 @cindex @code{-B} (@code{gnatlink})
6944 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
6945 from @var{dir} instead of the default location. Only use this switch
6946 when multiple versions of the GNAT compiler are available. See the
6947 @code{gcc} manual page for further details. You would normally use the
6948 @code{-b} or @code{-V} switch instead.
6949
6950 @item --GCC=@var{compiler_name}
6951 @cindex @code{--GCC=compiler_name} (@code{gnatlink})
6952 Program used for compiling the binder file. The default is
6953 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
6954 @code{compiler_name} contains spaces or other separator characters. As
6955 an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
6956 @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
6957 inserted after your command name. Thus in the above example the compiler
6958 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
6959 If several @code{--GCC=compiler_name} are used, only the last
6960 @var{compiler_name} is taken into account. However, all the additional
6961 switches are also taken into account. Thus,
6962 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
6963 @code{--GCC="bar -x -y -z -t"}.
6964
6965 @item --LINK=@var{name}
6966 @cindex @code{--LINK=} (@code{gnatlink})
6967 @var{name} is the name of the linker to be invoked. This is especially
6968 useful in mixed language programs since languages such as c++ require
6969 their own linker to be used. When this switch is omitted, the default
6970 name for the linker is (@file{gcc}). When this switch is used, the
6971 specified linker is called instead of (@file{gcc}) with exactly the same
6972 parameters that would have been passed to (@file{gcc}) so if the desired
6973 linker requires different parameters it is necessary to use a wrapper
6974 script that massages the parameters before invoking the real linker. It
6975 may be useful to control the exact invocation by using the verbose
6976 switch.
6977
6978
6979
6980 @end table
6981
6982 @node Setting Stack Size from gnatlink
6983 @section Setting Stack Size from @code{gnatlink}
6984
6985 @noindent
6986 It is possible to specify the program stack size from @code{gnatlink}.
6987 Assuming that the underlying linker is GNU ld there is two ways to do so:
6988
6989 @itemize @bullet
6990
6991 @item using @code{-Xlinker} linker option
6992
6993 @smallexample
6994 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
6995 @end smallexample
6996
6997 This set the stack reserve size to 0x10000 bytes and the stack commit
6998 size to 0x1000 bytes.
6999
7000 @item using @code{-Wl} linker option
7001
7002 @smallexample
7003 $ gnatlink hello -Wl,--stack=0x1000000
7004 @end smallexample
7005
7006 This set the stack reserve size to 0x1000000 bytes. Note that with
7007 @code{-Wl} option it is not possible to set the stack commit size
7008 because the coma is a separator for this option.
7009
7010 @end itemize
7011
7012 @node Setting Heap Size from gnatlink
7013 @section Setting Heap Size from @code{gnatlink}
7014
7015 @noindent
7016 It is possible to specify the program heap size from @code{gnatlink}.
7017 Assuming that the underlying linker is GNU ld there is two ways to do so:
7018
7019 @itemize @bullet
7020
7021 @item using @code{-Xlinker} linker option
7022
7023 @smallexample
7024 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
7025 @end smallexample
7026
7027 This set the heap reserve size to 0x10000 bytes and the heap commit
7028 size to 0x1000 bytes.
7029
7030 @item using @code{-Wl} linker option
7031
7032 @smallexample
7033 $ gnatlink hello -Wl,--heap=0x1000000
7034 @end smallexample
7035
7036 This set the heap reserve size to 0x1000000 bytes. Note that with
7037 @code{-Wl} option it is not possible to set the heap commit size
7038 because the coma is a separator for this option.
7039
7040 @end itemize
7041
7042 @node The GNAT Make Program gnatmake
7043 @chapter The GNAT Make Program @code{gnatmake}
7044 @findex gnatmake
7045
7046 @menu
7047 * Running gnatmake::
7048 * Switches for gnatmake::
7049 * Mode Switches for gnatmake::
7050 * Notes on the Command Line::
7051 * How gnatmake Works::
7052 * Examples of gnatmake Usage::
7053 @end menu
7054 @noindent
7055 A typical development cycle when working on an Ada program consists of
7056 the following steps:
7057
7058 @enumerate
7059 @item
7060 Edit some sources to fix bugs.
7061
7062 @item
7063 Add enhancements.
7064
7065 @item
7066 Compile all sources affected.
7067
7068 @item
7069 Rebind and relink.
7070
7071 @item
7072 Test.
7073 @end enumerate
7074
7075 @noindent
7076 The third step can be tricky, because not only do the modified files
7077 @cindex Dependency rules
7078 have to be compiled, but any files depending on these files must also be
7079 recompiled. The dependency rules in Ada can be quite complex, especially
7080 in the presence of overloading, @code{use} clauses, generics and inlined
7081 subprograms.
7082
7083 @code{gnatmake} automatically takes care of the third and fourth steps
7084 of this process. It determines which sources need to be compiled,
7085 compiles them, and binds and links the resulting object files.
7086
7087 Unlike some other Ada make programs, the dependencies are always
7088 accurately recomputed from the new sources. The source based approach of
7089 the GNAT compilation model makes this possible. This means that if
7090 changes to the source program cause corresponding changes in
7091 dependencies, they will always be tracked exactly correctly by
7092 @code{gnatmake}.
7093
7094 @node Running gnatmake
7095 @section Running @code{gnatmake}
7096
7097 @noindent
7098 The usual form of the @code{gnatmake} command is
7099
7100 @smallexample
7101 $ gnatmake [@var{switches}] @var{file_name} [@var{file_names}] [@var{mode_switches}]
7102 @end smallexample
7103
7104 @noindent
7105 The only required argument is one @var{file_name}, which specifies
7106 a compilation unit that is a main program. Several @var{file_names} can be
7107 specified: this will result in several executables being built.
7108 If @code{switches} are present, they can be placed before the first
7109 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
7110 If @var{mode_switches} are present, they must always be placed after
7111 the last @var{file_name} and all @code{switches}.
7112
7113 If you are using standard file extensions (.adb and .ads), then the
7114 extension may be omitted from the @var{file_name} arguments. However, if
7115 you are using non-standard extensions, then it is required that the
7116 extension be given. A relative or absolute directory path can be
7117 specified in a @var{file_name}, in which case, the input source file will
7118 be searched for in the specified directory only. Otherwise, the input
7119 source file will first be searched in the directory where
7120 @code{gnatmake} was invoked and if it is not found, it will be search on
7121 the source path of the compiler as described in
7122 @ref{Search Paths and the Run-Time Library (RTL)}.
7123
7124 When several @var{file_names} are specified, if an executable needs to be
7125 rebuilt and relinked, all subsequent executables will be rebuilt and
7126 relinked, even if this would not be absolutely necessary.
7127
7128 All @code{gnatmake} output (except when you specify
7129 @code{-M}) is to
7130 @file{stderr}. The output produced by the
7131 @code{-M} switch is send to
7132 @file{stdout}.
7133
7134 @node Switches for gnatmake
7135 @section Switches for @code{gnatmake}
7136
7137 @noindent
7138 You may specify any of the following switches to @code{gnatmake}:
7139
7140 @table @code
7141 @item --GCC=@var{compiler_name}
7142 @cindex @code{--GCC=compiler_name} (@code{gnatmake})
7143 Program used for compiling. The default is `@code{gcc}'. You need to use
7144 quotes around @var{compiler_name} if @code{compiler_name} contains
7145 spaces or other separator characters. As an example @code{--GCC="foo -x
7146 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
7147 compiler. Note that switch @code{-c} is always inserted after your
7148 command name. Thus in the above example the compiler command that will
7149 be used by @code{gnatmake} will be @code{foo -c -x -y}.
7150 If several @code{--GCC=compiler_name} are used, only the last
7151 @var{compiler_name} is taken into account. However, all the additional
7152 switches are also taken into account. Thus,
7153 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7154 @code{--GCC="bar -x -y -z -t"}.
7155
7156 @item --GNATBIND=@var{binder_name}
7157 @cindex @code{--GNATBIND=binder_name} (@code{gnatmake})
7158 Program used for binding. The default is `@code{gnatbind}'. You need to
7159 use quotes around @var{binder_name} if @var{binder_name} contains spaces
7160 or other separator characters. As an example @code{--GNATBIND="bar -x
7161 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
7162 binder. Binder switches that are normally appended by @code{gnatmake} to
7163 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
7164
7165 @item --GNATLINK=@var{linker_name}
7166 @cindex @code{--GNATLINK=linker_name} (@code{gnatmake})
7167 Program used for linking. The default is `@code{gnatlink}'. You need to
7168 use quotes around @var{linker_name} if @var{linker_name} contains spaces
7169 or other separator characters. As an example @code{--GNATLINK="lan -x
7170 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
7171 linker. Linker switches that are normally appended by @code{gnatmake} to
7172 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
7173
7174
7175 @item -a
7176 @cindex @code{-a} (@code{gnatmake})
7177 Consider all files in the make process, even the GNAT internal system
7178 files (for example, the predefined Ada library files), as well as any
7179 locked files. Locked files are files whose ALI file is write-protected.
7180 By default,
7181 @code{gnatmake} does not check these files,
7182 because the assumption is that the GNAT internal files are properly up
7183 to date, and also that any write protected ALI files have been properly
7184 installed. Note that if there is an installation problem, such that one
7185 of these files is not up to date, it will be properly caught by the
7186 binder.
7187 You may have to specify this switch if you are working on GNAT
7188 itself. @code{-a} is also useful in conjunction with
7189 @code{-f}
7190 if you need to recompile an entire application,
7191 including run-time files, using special configuration pragma settings,
7192 such as a non-standard @code{Float_Representation} pragma.
7193 By default
7194 @code{gnatmake -a} compiles all GNAT
7195 internal files with
7196 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7197
7198 @item -b
7199 @cindex @code{-b} (@code{gnatmake})
7200 Bind only. Can be combined with @code{-c} to do compilation
7201 and binding, but no link. Can be combined with @code{-l}
7202 to do binding and linking. When not combined with @code{-c}
7203 all the units in the closure of the main program must have been previously
7204 compiled and must be up to date. The root unit specified by @var{file_name}
7205 may be given without extension, with the source extension or, if no GNAT
7206 Project File is specified, with the ALI file extension.
7207
7208 @item -c
7209 @cindex @code{-c} (@code{gnatmake})
7210 Compile only. Do not perform binding, except when @code{-b}
7211 is also specified. Do not perform linking, except if both
7212 @code{-b} and
7213  @code{-l} are also specified.
7214 If the root unit specified by @var{file_name} is not a main unit, this is the
7215 default. Otherwise @code{gnatmake} will attempt binding and linking
7216 unless all objects are up to date and the executable is more recent than
7217 the objects.
7218
7219 @item -C
7220 @cindex @code{-C} (@code{gnatmake})
7221 Use a mapping file. A mapping file is a way to communicate to the compiler
7222 two mappings: from unit names to file names (without any directory information)
7223 and from file names to path names (with full directory information).
7224 These mappings are used by the compiler to short-circuit the path search.
7225 When @code{gnatmake} is invoked with this switch, it will create a mapping
7226 file, initially populated by the project manager, if @code{-P} is used,
7227 otherwise initially empty. Each invocation of the compiler will add the newly
7228 accessed sources to the mapping file. This will improve the source search
7229 during the next invocation of the compiler.
7230
7231 @item -f
7232 @cindex @code{-f} (@code{gnatmake})
7233 Force recompilations. Recompile all sources, even though some object
7234 files may be up to date, but don't recompile predefined or GNAT internal
7235 files or locked files (files with a write-protected ALI file),
7236 unless the @code{-a} switch is also specified.
7237
7238 @item
7239 @item -i
7240 @cindex @code{-i} (@code{gnatmake})
7241 In normal mode, @code{gnatmake} compiles all object files and ALI files
7242 into the current directory. If the @code{-i} switch is used,
7243 then instead object files and ALI files that already exist are overwritten
7244 in place. This means that once a large project is organized into separate
7245 directories in the desired manner, then @code{gnatmake} will automatically
7246 maintain and update this organization. If no ALI files are found on the
7247 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
7248 the new object and ALI files are created in the
7249 directory containing the source being compiled. If another organization
7250 is desired, where objects and sources are kept in different directories,
7251 a useful technique is to create dummy ALI files in the desired directories.
7252 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
7253 the corresponding source file, and it will be put the resulting object
7254 and ALI files in the directory where it found the dummy file.
7255
7256 @item -j@var{n}
7257 @cindex @code{-j} (@code{gnatmake})
7258 @cindex Parallel make
7259 Use @var{n} processes to carry out the (re)compilations. On a
7260 multiprocessor machine compilations will occur in parallel. In the
7261 event of compilation errors, messages from various compilations might
7262 get interspersed (but @code{gnatmake} will give you the full ordered
7263 list of failing compiles at the end). If this is problematic, rerun
7264 the make process with n set to 1 to get a clean list of messages.
7265
7266 @item -k
7267 @cindex @code{-k} (@code{gnatmake})
7268 Keep going. Continue as much as possible after a compilation error. To
7269 ease the programmer's task in case of compilation errors, the list of
7270 sources for which the compile fails is given when @code{gnatmake}
7271 terminates.
7272
7273 If @code{gnatmake} is invoked with several @file{file_names} and with this
7274 switch, if there are compilation errors when building an executable,
7275 @code{gnatmake} will not attempt to build the following executables.
7276
7277 @item -l
7278 @cindex @code{-l} (@code{gnatmake})
7279 Link only. Can be combined with @code{-b} to binding
7280 and linking. Linking will not be performed if combined with
7281 @code{-c}
7282 but not with @code{-b}.
7283 When not combined with @code{-b}
7284 all the units in the closure of the main program must have been previously
7285 compiled and must be up to date, and the main program need to have been bound.
7286 The root unit specified by @var{file_name}
7287 may be given without extension, with the source extension or, if no GNAT
7288 Project File is specified, with the ALI file extension.
7289
7290 @item -m
7291 @cindex @code{-m} (@code{gnatmake})
7292 Specifies that the minimum necessary amount of recompilations
7293 be performed. In this mode @code{gnatmake} ignores time
7294 stamp differences when the only
7295 modifications to a source file consist in adding/removing comments,
7296 empty lines, spaces or tabs. This means that if you have changed the
7297 comments in a source file or have simply reformatted it, using this
7298 switch will tell gnatmake not to recompile files that depend on it
7299 (provided other sources on which these files depend have undergone no
7300 semantic modifications). Note that the debugging information may be
7301 out of date with respect to the sources if the @code{-m} switch causes
7302 a compilation to be switched, so the use of this switch represents a
7303 trade-off between compilation time and accurate debugging information.
7304
7305 @item -M
7306 @cindex Dependencies, producing list
7307 @cindex @code{-M} (@code{gnatmake})
7308 Check if all objects are up to date. If they are, output the object
7309 dependences to @file{stdout} in a form that can be directly exploited in
7310 a @file{Makefile}. By default, each source file is prefixed with its
7311 (relative or absolute) directory name. This name is whatever you
7312 specified in the various @code{-aI}
7313 and @code{-I} switches. If you use
7314 @code{gnatmake -M}
7315 @code{-q}
7316 (see below), only the source file names,
7317 without relative paths, are output. If you just specify the
7318 @code{-M}
7319 switch, dependencies of the GNAT internal system files are omitted. This
7320 is typically what you want. If you also specify
7321 the @code{-a} switch,
7322 dependencies of the GNAT internal files are also listed. Note that
7323 dependencies of the objects in external Ada libraries (see switch
7324 @code{-aL}@var{dir} in the following list) are never reported.
7325
7326 @item -n
7327 @cindex @code{-n} (@code{gnatmake})
7328 Don't compile, bind, or link. Checks if all objects are up to date.
7329 If they are not, the full name of the first file that needs to be
7330 recompiled is printed.
7331 Repeated use of this option, followed by compiling the indicated source
7332 file, will eventually result in recompiling all required units.
7333
7334 @item -o @var{exec_name}
7335 @cindex @code{-o} (@code{gnatmake})
7336 Output executable name. The name of the final executable program will be
7337 @var{exec_name}. If the @code{-o} switch is omitted the default
7338 name for the executable will be the name of the input file in appropriate form
7339 for an executable file on the host system.
7340
7341 This switch cannot be used when invoking @code{gnatmake} with several
7342 @file{file_names}.
7343
7344 @item -q
7345 @cindex @code{-q} (@code{gnatmake})
7346 Quiet. When this flag is not set, the commands carried out by
7347 @code{gnatmake} are displayed.
7348
7349 @item -s
7350 @cindex @code{-s} (@code{gnatmake})
7351 Recompile if compiler switches have changed since last compilation.
7352 All compiler switches but -I and -o are taken into account in the
7353 following way:
7354 orders between different ``first letter'' switches are ignored, but
7355 orders between same switches are taken into account. For example,
7356 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O} is equivalent
7357 to @code{-O -g}.
7358
7359 @item -u
7360 @cindex @code{-u} (@code{gnatmake})
7361 Unique. Recompile at most the main file. It implies -c. Combined with
7362 -f, it is equivalent to calling the compiler directly.
7363
7364 @item -v
7365 @cindex @code{-v} (@code{gnatmake})
7366 Verbose. Displays the reason for all recompilations @code{gnatmake}
7367 decides are necessary.
7368
7369 @item -z
7370 @cindex @code{-z} (@code{gnatmake})
7371 No main subprogram. Bind and link the program even if the unit name
7372 given on the command line is a package name. The resulting executable
7373 will execute the elaboration routines of the package and its closure,
7374 then the finalization routines.
7375
7376 @item @code{gcc} @asis{switches}
7377 The switch @code{-g} or any uppercase switch (other than @code{-A},
7378 @code{-L} or
7379 @code{-S}) or any switch that is more than one character is passed to
7380 @code{gcc} (e.g. @code{-O}, @option{-gnato,} etc.)
7381 @end table
7382
7383 @noindent
7384 Source and library search path switches:
7385
7386 @table @code
7387 @item -aI@var{dir}
7388 @cindex @code{-aI} (@code{gnatmake})
7389 When looking for source files also look in directory @var{dir}.
7390 The order in which source files search is undertaken is
7391 described in @ref{Search Paths and the Run-Time Library (RTL)}.
7392
7393 @item -aL@var{dir}
7394 @cindex @code{-aL} (@code{gnatmake})
7395 Consider @var{dir} as being an externally provided Ada library.
7396 Instructs @code{gnatmake} to skip compilation units whose @file{.ali}
7397 files have been located in directory @var{dir}. This allows you to have
7398 missing bodies for the units in @var{dir} and to ignore out of date bodies
7399 for the same units. You still need to specify
7400 the location of the specs for these units by using the switches
7401 @code{-aI@var{dir}}
7402 or @code{-I@var{dir}}.
7403 Note: this switch is provided for compatibility with previous versions
7404 of @code{gnatmake}. The easier method of causing standard libraries
7405 to be excluded from consideration is to write-protect the corresponding
7406 ALI files.
7407
7408 @item -aO@var{dir}
7409 @cindex @code{-aO} (@code{gnatmake})
7410 When searching for library and object files, look in directory
7411 @var{dir}. The order in which library files are searched is described in
7412 @ref{Search Paths for gnatbind}.
7413
7414 @item -A@var{dir}
7415 @cindex Search paths, for @code{gnatmake}
7416 @cindex @code{-A} (@code{gnatmake})
7417 Equivalent to @code{-aL@var{dir}
7418 -aI@var{dir}}.
7419
7420 @item -I@var{dir}
7421 @cindex @code{-I} (@code{gnatmake})
7422 Equivalent to @code{-aO@var{dir}
7423 -aI@var{dir}}.
7424
7425 @item -I-
7426 @cindex @code{-I-} (@code{gnatmake})
7427 @cindex Source files, suppressing search
7428 Do not look for source files in the directory containing the source
7429 file named in the command line.
7430 Do not look for ALI or object files in the directory
7431 where @code{gnatmake} was invoked.
7432
7433 @item -L@var{dir}
7434 @cindex @code{-L} (@code{gnatmake})
7435 @cindex Linker libraries
7436 Add directory @var{dir} to the list of directories in which the linker
7437 will search for libraries. This is equivalent to
7438 @code{-largs -L}@var{dir}.
7439
7440 @item -nostdinc
7441 @cindex @code{-nostdinc} (@code{gnatmake})
7442 Do not look for source files in the system default directory.
7443
7444 @item -nostdlib
7445 @cindex @code{-nostdlib} (@code{gnatmake})
7446 Do not look for library files in the system default directory.
7447
7448 @item --RTS=@var{rts-path}
7449 @cindex @code{--RTS} (@code{gnatmake})
7450 Specifies the default location of the runtime library. We look for the runtime
7451 in the following directories, and stop as soon as a valid runtime is found
7452 ("adainclude" or "ada_source_path", and "adalib" or "ada_object_path" present):
7453
7454 @itemize @bullet
7455 @item <current directory>/$rts_path
7456
7457 @item <default-search-dir>/$rts_path
7458
7459 @item <default-search-dir>/rts-$rts_path
7460 @end itemize
7461
7462 @noindent
7463 The selected path is handled like a normal RTS path.
7464
7465 @end table
7466
7467 @node Mode Switches for gnatmake
7468 @section Mode Switches for @code{gnatmake}
7469
7470 @noindent
7471 The mode switches (referred to as @code{mode_switches}) allow the
7472 inclusion of switches that are to be passed to the compiler itself, the
7473 binder or the linker. The effect of a mode switch is to cause all
7474 subsequent switches up to the end of the switch list, or up to the next
7475 mode switch, to be interpreted as switches to be passed on to the
7476 designated component of GNAT.
7477
7478 @table @code
7479 @item -cargs @var{switches}
7480 @cindex @code{-cargs} (@code{gnatmake})
7481 Compiler switches. Here @var{switches} is a list of switches
7482 that are valid switches for @code{gcc}. They will be passed on to
7483 all compile steps performed by @code{gnatmake}.
7484
7485 @item -bargs @var{switches}
7486 @cindex @code{-bargs} (@code{gnatmake})
7487 Binder switches. Here @var{switches} is a list of switches
7488 that are valid switches for @code{gcc}. They will be passed on to
7489 all bind steps performed by @code{gnatmake}.
7490
7491 @item -largs @var{switches}
7492 @cindex @code{-largs} (@code{gnatmake})
7493 Linker switches. Here @var{switches} is a list of switches
7494 that are valid switches for @code{gcc}. They will be passed on to
7495 all link steps performed by @code{gnatmake}.
7496 @end table
7497
7498 @node Notes on the Command Line
7499 @section Notes on the Command Line
7500
7501 @noindent
7502 This section contains some additional useful notes on the operation
7503 of the @code{gnatmake} command.
7504
7505 @itemize @bullet
7506 @item
7507 @cindex Recompilation, by @code{gnatmake}
7508 If @code{gnatmake} finds no ALI files, it recompiles the main program
7509 and all other units required by the main program.
7510 This means that @code{gnatmake}
7511 can be used for the initial compile, as well as during subsequent steps of
7512 the development cycle.
7513
7514 @item
7515 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
7516 is a subunit or body of a generic unit, @code{gnatmake} recompiles
7517 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
7518 warning.
7519
7520 @item
7521 In @code{gnatmake} the switch @code{-I}
7522 is used to specify both source and
7523 library file paths. Use @code{-aI}
7524 instead if you just want to specify
7525 source paths only and @code{-aO}
7526 if you want to specify library paths
7527 only.
7528
7529 @item
7530 @code{gnatmake} examines both an ALI file and its corresponding object file
7531 for consistency. If an ALI is more recent than its corresponding object,
7532 or if the object file is missing, the corresponding source will be recompiled.
7533 Note that @code{gnatmake} expects an ALI and the corresponding object file
7534 to be in the same directory.
7535
7536 @item
7537 @code{gnatmake} will ignore any files whose ALI file is write-protected.
7538 This may conveniently be used to exclude standard libraries from
7539 consideration and in particular it means that the use of the
7540 @code{-f} switch will not recompile these files
7541 unless @code{-a} is also specified.
7542
7543 @item
7544 @code{gnatmake} has been designed to make the use of Ada libraries
7545 particularly convenient. Assume you have an Ada library organized
7546 as follows: @var{obj-dir} contains the objects and ALI files for
7547 of your Ada compilation units,
7548 whereas @var{include-dir} contains the
7549 specs of these units, but no bodies. Then to compile a unit
7550 stored in @code{main.adb}, which uses this Ada library you would just type
7551
7552 @smallexample
7553 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
7554 @end smallexample
7555
7556 @item
7557 Using @code{gnatmake} along with the
7558 @code{-m (minimal recompilation)}
7559 switch provides a mechanism for avoiding unnecessary rcompilations. Using
7560 this switch,
7561 you can update the comments/format of your
7562 source files without having to recompile everything. Note, however, that
7563 adding or deleting lines in a source files may render its debugging
7564 info obsolete. If the file in question is a spec, the impact is rather
7565 limited, as that debugging info will only be useful during the
7566 elaboration phase of your program. For bodies the impact can be more
7567 significant. In all events, your debugger will warn you if a source file
7568 is more recent than the corresponding object, and alert you to the fact
7569 that the debugging information may be out of date.
7570 @end itemize
7571
7572 @node How gnatmake Works
7573 @section How @code{gnatmake} Works
7574
7575 @noindent
7576 Generally @code{gnatmake} automatically performs all necessary
7577 recompilations and you don't need to worry about how it works. However,
7578 it may be useful to have some basic understanding of the @code{gnatmake}
7579 approach and in particular to understand how it uses the results of
7580 previous compilations without incorrectly depending on them.
7581
7582 First a definition: an object file is considered @dfn{up to date} if the
7583 corresponding ALI file exists and its time stamp predates that of the
7584 object file and if all the source files listed in the
7585 dependency section of this ALI file have time stamps matching those in
7586 the ALI file. This means that neither the source file itself nor any
7587 files that it depends on have been modified, and hence there is no need
7588 to recompile this file.
7589
7590 @code{gnatmake} works by first checking if the specified main unit is up
7591 to date. If so, no compilations are required for the main unit. If not,
7592 @code{gnatmake} compiles the main program to build a new ALI file that
7593 reflects the latest sources. Then the ALI file of the main unit is
7594 examined to find all the source files on which the main program depends,
7595 and @code{gnatmake} recursively applies the above procedure on all these files.
7596
7597 This process ensures that @code{gnatmake} only trusts the dependencies
7598 in an existing ALI file if they are known to be correct. Otherwise it
7599 always recompiles to determine a new, guaranteed accurate set of
7600 dependencies. As a result the program is compiled "upside down" from what may
7601 be more familiar as the required order of compilation in some other Ada
7602 systems. In particular, clients are compiled before the units on which
7603 they depend. The ability of GNAT to compile in any order is critical in
7604 allowing an order of compilation to be chosen that guarantees that
7605 @code{gnatmake} will recompute a correct set of new dependencies if
7606 necessary.
7607
7608 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
7609 imported by several of the executables, it will be recompiled at most once.
7610
7611 @node Examples of gnatmake Usage
7612 @section Examples of @code{gnatmake} Usage
7613
7614 @table @code
7615 @item gnatmake hello.adb
7616 Compile all files necessary to bind and link the main program
7617 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
7618 resulting object files to generate an executable file @file{hello}.
7619
7620 @item gnatmake main1 main2 main3
7621 Compile all files necessary to bind and link the main programs
7622 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
7623 (containing unit @code{Main2}) and @file{main3.adb}
7624 (containing unit @code{Main3}) and bind and link the resulting object files
7625 to generate three executable files @file{main1},
7626 @file{main2}
7627 and @file{main3}.
7628
7629 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
7630
7631 Compile all files necessary to bind and link the main program unit
7632 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
7633 be done with optimization level 2 and the order of elaboration will be
7634 listed by the binder. @code{gnatmake} will operate in quiet mode, not
7635 displaying commands it is executing.
7636 @end table
7637
7638 @node Renaming Files Using gnatchop
7639 @chapter Renaming Files Using @code{gnatchop}
7640 @findex gnatchop
7641
7642 @noindent
7643 This chapter discusses how to handle files with multiple units by using
7644 the @code{gnatchop} utility. This utility is also useful in renaming
7645 files to meet the standard GNAT default file naming conventions.
7646
7647 @menu
7648 * Handling Files with Multiple Units::
7649 * Operating gnatchop in Compilation Mode::
7650 * Command Line for gnatchop::
7651 * Switches for gnatchop::
7652 * Examples of gnatchop Usage::
7653 @end menu
7654
7655 @node Handling Files with Multiple Units
7656 @section Handling Files with Multiple Units
7657
7658 @noindent
7659 The basic compilation model of GNAT requires that a file submitted to the
7660 compiler have only one unit and there be a strict correspondence
7661 between the file name and the unit name.
7662
7663 The @code{gnatchop} utility allows both of these rules to be relaxed,
7664 allowing GNAT to process files which contain multiple compilation units
7665 and files with arbitrary file names. @code{gnatchop}
7666 reads the specified file and generates one or more output files,
7667 containing one unit per file. The unit and the file name correspond,
7668 as required by GNAT.
7669
7670 If you want to permanently restructure a set of "foreign" files so that
7671 they match the GNAT rules, and do the remaining development using the
7672 GNAT structure, you can simply use @code{gnatchop} once, generate the
7673 new set of files and work with them from that point on.
7674
7675 Alternatively, if you want to keep your files in the "foreign" format,
7676 perhaps to maintain compatibility with some other Ada compilation
7677 system, you can set up a procedure where you use @code{gnatchop} each
7678 time you compile, regarding the source files that it writes as temporary
7679 files that you throw away.
7680
7681 @node Operating gnatchop in Compilation Mode
7682 @section Operating gnatchop in Compilation Mode
7683
7684 @noindent
7685 The basic function of @code{gnatchop} is to take a file with multiple units
7686 and split it into separate files. The boundary between files is reasonably
7687 clear, except for the issue of comments and pragmas. In default mode, the
7688 rule is that any pragmas between units belong to the previous unit, except
7689 that configuration pragmas always belong to the following unit. Any comments
7690 belong to the following unit. These rules
7691 almost always result in the right choice of
7692 the split point without needing to mark it explicitly and most users will
7693 find this default to be what they want. In this default mode it is incorrect to
7694 submit a file containing only configuration pragmas, or one that ends in
7695 configuration pragmas, to @code{gnatchop}.
7696
7697 However, using a special option to activate "compilation mode",
7698 @code{gnatchop}
7699 can perform another function, which is to provide exactly the semantics
7700 required by the RM for handling of configuration pragmas in a compilation.
7701 In the absence of configuration pragmas (at the main file level), this
7702 option has no effect, but it causes such configuration pragmas to be handled
7703 in a quite different manner.
7704
7705 First, in compilation mode, if @code{gnatchop} is given a file that consists of
7706 only configuration pragmas, then this file is appended to the
7707 @file{gnat.adc} file in the current directory. This behavior provides
7708 the required behavior described in the RM for the actions to be taken
7709 on submitting such a file to the compiler, namely that these pragmas
7710 should apply to all subsequent compilations in the same compilation
7711 environment. Using GNAT, the current directory, possibly containing a
7712 @file{gnat.adc} file is the representation
7713 of a compilation environment. For more information on the
7714 @file{gnat.adc} file, see the section on handling of configuration
7715 pragmas @pxref{Handling of Configuration Pragmas}.
7716
7717 Second, in compilation mode, if @code{gnatchop}
7718 is given a file that starts with
7719 configuration pragmas, and contains one or more units, then these
7720 configuration pragmas are prepended to each of the chopped files. This
7721 behavior provides the required behavior described in the RM for the
7722 actions to be taken on compiling such a file, namely that the pragmas
7723 apply to all units in the compilation, but not to subsequently compiled
7724 units.
7725
7726 Finally, if configuration pragmas appear between units, they are appended
7727 to the previous unit. This results in the previous unit being illegal,
7728 since the compiler does not accept configuration pragmas that follow
7729 a unit. This provides the required RM behavior that forbids configuration
7730 pragmas other than those preceding the first compilation unit of a
7731 compilation.
7732
7733 For most purposes, @code{gnatchop} will be used in default mode. The
7734 compilation mode described above is used only if you need exactly
7735 accurate behavior with respect to compilations, and you have files
7736 that contain multiple units and configuration pragmas. In this
7737 circumstance the use of @code{gnatchop} with the compilation mode
7738 switch provides the required behavior, and is for example the mode
7739 in which GNAT processes the ACVC tests.
7740
7741 @node Command Line for gnatchop
7742 @section Command Line for @code{gnatchop}
7743
7744 @noindent
7745 The @code{gnatchop} command has the form:
7746
7747 @smallexample
7748 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
7749       [@var{directory}]
7750 @end smallexample
7751
7752 @noindent
7753 The only required argument is the file name of the file to be chopped.
7754 There are no restrictions on the form of this file name. The file itself
7755 contains one or more Ada units, in normal GNAT format, concatenated
7756 together. As shown, more than one file may be presented to be chopped.
7757
7758 When run in default mode, @code{gnatchop} generates one output file in
7759 the current directory for each unit in each of the files.
7760
7761 @var{directory}, if specified, gives the name of the directory to which
7762 the output files will be written. If it is not specified, all files are
7763 written to the current directory.
7764
7765 For example, given a
7766 file called @file{hellofiles} containing
7767
7768 @smallexample
7769 @group
7770 @cartouche
7771 @b{procedure} hello;
7772
7773 @b{with} Text_IO; @b{use} Text_IO;
7774 @b{procedure} hello @b{is}
7775 @b{begin}
7776    Put_Line ("Hello");
7777 @b{end} hello;
7778 @end cartouche
7779 @end group
7780 @end smallexample
7781
7782 @noindent
7783 the command
7784
7785 @smallexample
7786 $ gnatchop hellofiles
7787 @end smallexample
7788
7789 @noindent
7790 generates two files in the current directory, one called
7791 @file{hello.ads} containing the single line that is the procedure spec,
7792 and the other called @file{hello.adb} containing the remaining text. The
7793 original file is not affected. The generated files can be compiled in
7794 the normal manner.
7795
7796 @node Switches for gnatchop
7797 @section Switches for @code{gnatchop}
7798
7799 @noindent
7800 @code{gnatchop} recognizes the following switches:
7801
7802 @table @code
7803
7804 @item -c
7805 @cindex @code{-c} (@code{gnatchop})
7806 Causes @code{gnatchop} to operate in compilation mode, in which
7807 configuration pragmas are handled according to strict RM rules. See
7808 previous section for a full description of this mode.
7809
7810 @item -gnatxxx
7811 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
7812 used to parse the given file. Not all @code{xxx} options make sense,
7813 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
7814 process a source file that uses Latin-2 coding for identifiers.
7815
7816 @item -h
7817 Causes @code{gnatchop} to generate a brief help summary to the standard
7818 output file showing usage information.
7819
7820 @item -k@var{mm}
7821 @cindex @code{-k} (@code{gnatchop})
7822 Limit generated file names to the specified number @code{mm}
7823 of characters.
7824 This is useful if the
7825 resulting set of files is required to be interoperable with systems
7826 which limit the length of file names.
7827 No space is allowed between the @code{-k} and the numeric value. The numeric
7828 value may be omitted in which case a default of @code{-k8},
7829 suitable for use
7830 with DOS-like file systems, is used. If no @code{-k} switch
7831 is present then
7832 there is no limit on the length of file names.
7833
7834 @item -p
7835 @cindex @code{-p} (@code{gnatchop})
7836 Causes the file modification time stamp of the input file to be
7837 preserved and used for the time stamp of the output file(s). This may be
7838 useful for preserving coherency of time stamps in an enviroment where
7839 @code{gnatchop} is used as part of a standard build process.
7840
7841 @item -q
7842 @cindex @code{-q} (@code{gnatchop})
7843 Causes output of informational messages indicating the set of generated
7844 files to be suppressed. Warnings and error messages are unaffected.
7845
7846 @item -r
7847 @cindex @code{-r} (@code{gnatchop})
7848 @findex Source_Reference
7849 Generate @code{Source_Reference} pragmas. Use this switch if the output
7850 files are regarded as temporary and development is to be done in terms
7851 of the original unchopped file. This switch causes
7852 @code{Source_Reference} pragmas to be inserted into each of the
7853 generated files to refers back to the original file name and line number.
7854 The result is that all error messages refer back to the original
7855 unchopped file.
7856 In addition, the debugging information placed into the object file (when
7857 the @code{-g} switch of @code{gcc} or @code{gnatmake} is specified) also
7858 refers back to this original file so that tools like profilers and
7859 debuggers will give information in terms of the original unchopped file.
7860
7861 If the original file to be chopped itself contains
7862 a @code{Source_Reference}
7863 pragma referencing a third file, then gnatchop respects
7864 this pragma, and the generated @code{Source_Reference} pragmas
7865 in the chopped file refer to the original file, with appropriate
7866 line numbers. This is particularly useful when @code{gnatchop}
7867 is used in conjunction with @code{gnatprep} to compile files that
7868 contain preprocessing statements and multiple units.
7869
7870 @item -v
7871 @cindex @code{-v} (@code{gnatchop})
7872 Causes @code{gnatchop} to operate in verbose mode. The version
7873 number and copyright notice are output, as well as exact copies of
7874 the gnat1 commands spawned to obtain the chop control information.
7875
7876 @item -w
7877 @cindex @code{-w} (@code{gnatchop})
7878 Overwrite existing file names. Normally @code{gnatchop} regards it as a
7879 fatal error if there is already a file with the same name as a
7880 file it would otherwise output, in other words if the files to be
7881 chopped contain duplicated units. This switch bypasses this
7882 check, and causes all but the last instance of such duplicated
7883 units to be skipped.
7884
7885 @item --GCC=xxxx
7886 @cindex @code{--GCC=} (@code{gnatchop})
7887 Specify the path of the GNAT parser to be used. When this switch is used,
7888 no attempt is made to add the prefix to the GNAT parser executable.
7889 @end table
7890
7891 @node Examples of gnatchop Usage
7892 @section Examples of @code{gnatchop} Usage
7893
7894 @table @code
7895 @item gnatchop -w hello_s.ada ichbiah/files
7896
7897 Chops the source file @file{hello_s.ada}. The output files will be
7898 placed in the directory @file{ichbiah/files},
7899 overwriting any
7900 files with matching names in that directory (no files in the current
7901 directory are modified).
7902
7903 @item gnatchop archive
7904 Chops the source file @file{archive}
7905 into the current directory. One
7906 useful application of @code{gnatchop} is in sending sets of sources
7907 around, for example in email messages. The required sources are simply
7908 concatenated (for example, using a Unix @code{cat}
7909 command), and then
7910 @code{gnatchop} is used at the other end to reconstitute the original
7911 file names.
7912
7913 @item gnatchop file1 file2 file3 direc
7914 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
7915 the resulting files in the directory @file{direc}. Note that if any units
7916 occur more than once anywhere within this set of files, an error message
7917 is generated, and no files are written. To override this check, use the
7918 @code{-w} switch,
7919 in which case the last occurrence in the last file will
7920 be the one that is output, and earlier duplicate occurrences for a given
7921 unit will be skipped.
7922 @end table
7923
7924 @node Configuration Pragmas
7925 @chapter Configuration Pragmas
7926 @cindex Configuration pragmas
7927 @cindex Pragmas, configuration
7928
7929 @noindent
7930 In Ada 95, configuration pragmas include those pragmas described as
7931 such in the Ada 95 Reference Manual, as well as
7932 implementation-dependent pragmas that are configuration pragmas. See the
7933 individual descriptions of pragmas in the GNAT Reference Manual for
7934 details on these additional GNAT-specific configuration pragmas. Most
7935 notably, the pragma @code{Source_File_Name}, which allows
7936 specifying non-default names for source files, is a configuration
7937 pragma. The following is a complete list of configuration pragmas
7938 recognized by @code{GNAT}:
7939
7940 @smallexample
7941    Ada_83
7942    Ada_95
7943    C_Pass_By_Copy
7944    Component_Alignment
7945    Discard_Names
7946    Elaboration_Checks
7947    Eliminate
7948    Extend_System
7949    Extensions_Allowed
7950    External_Name_Casing
7951    Float_Representation
7952    Initialize_Scalars
7953    License
7954    Locking_Policy
7955    Long_Float
7956    No_Run_Time
7957    Normalize_Scalars
7958    Polling
7959    Propagate_Exceptions
7960    Queuing_Policy
7961    Ravenscar
7962    Restricted_Run_Time
7963    Restrictions
7964    Reviewable
7965    Source_File_Name
7966    Style_Checks
7967    Suppress
7968    Task_Dispatching_Policy
7969    Unsuppress
7970    Use_VADS_Size
7971    Warnings
7972    Validity_Checks
7973 @end smallexample
7974
7975 @menu
7976 * Handling of Configuration Pragmas::
7977 * The Configuration Pragmas Files::
7978 @end menu
7979
7980 @node Handling of Configuration Pragmas
7981 @section Handling of Configuration Pragmas
7982
7983 Configuration pragmas may either appear at the start of a compilation
7984 unit, in which case they apply only to that unit, or they may apply to
7985 all compilations performed in a given compilation environment.
7986
7987 GNAT also provides the @code{gnatchop} utility to provide an automatic
7988 way to handle configuration pragmas following the semantics for
7989 compilations (that is, files with multiple units), described in the RM.
7990 See section @pxref{Operating gnatchop in Compilation Mode} for details.
7991 However, for most purposes, it will be more convenient to edit the
7992 @file{gnat.adc} file that contains configuration pragmas directly,
7993 as described in the following section.
7994
7995 @node The Configuration Pragmas Files
7996 @section The Configuration Pragmas Files
7997 @cindex @file{gnat.adc}
7998
7999 @noindent
8000 In GNAT a compilation environment is defined by the current
8001 directory at the time that a compile command is given. This current
8002 directory is searched for a file whose name is @file{gnat.adc}. If
8003 this file is present, it is expected to contain one or more
8004 configuration pragmas that will be applied to the current compilation.
8005 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
8006 considered.
8007
8008 Configuration pragmas may be entered into the @file{gnat.adc} file
8009 either by running @code{gnatchop} on a source file that consists only of
8010 configuration pragmas, or more conveniently  by
8011 direct editing of the @file{gnat.adc} file, which is a standard format
8012 source file.
8013
8014 In addition to @file{gnat.adc}, one additional file containing configuration
8015 pragmas may be applied to the current compilation using the switch
8016 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
8017 contains only configuration pragmas. These configuration pragmas are
8018 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
8019 is present and switch @option{-gnatA} is not used).
8020
8021 It is allowed to specify several switches @option{-gnatec}, however only
8022 the last one on the command line will be taken into account.
8023
8024
8025 @node Handling Arbitrary File Naming Conventions Using gnatname
8026 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
8027 @cindex Arbitrary File Naming Conventions
8028
8029 @menu
8030 * Arbitrary File Naming Conventions::
8031 * Running gnatname::
8032 * Switches for gnatname::
8033 * Examples of gnatname Usage::
8034 @end menu
8035
8036 @node Arbitrary File Naming Conventions
8037 @section Arbitrary File Naming Conventions
8038
8039 @noindent
8040 The GNAT compiler must be able to know the source file name of a compilation unit.
8041 When using the standard GNAT default file naming conventions (@code{.ads} for specs,
8042 @code{.adb} for bodies), the GNAT compiler does not need additional information.
8043
8044 @noindent
8045 When the source file names do not follow the standard GNAT default file naming
8046 conventions, the GNAT compiler must be given additional information through
8047 a configuration pragmas file (see @ref{Configuration Pragmas}) or a project file.
8048 When the non standard file naming conventions are well-defined, a small number of
8049 pragmas @code{Source_File_Name} specifying a naming pattern
8050 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
8051 if the file naming conventions are irregular or arbitrary, a number
8052 of pragma @code{Source_File_Name} for individual compilation units must be defined.
8053 To help maintain the correspondence between compilation unit names and
8054 source file names within the compiler,
8055 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
8056 set of files.
8057
8058 @node Running gnatname
8059 @section Running @code{gnatname}
8060
8061 @noindent
8062 The usual form of the @code{gnatname} command is
8063
8064 @smallexample
8065 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
8066 @end smallexample
8067
8068 @noindent
8069 All of the arguments are optional. If invoked without any argument,
8070 @code{gnatname} will display its usage.
8071
8072 @noindent
8073 When used with at least one naming pattern, @code{gnatname} will attempt to
8074 find all the compilation units in files that follow at least one of the
8075 naming patterns. To find these compilation units,
8076 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
8077 regular files.
8078
8079 @noindent
8080 One or several Naming Patterns may be given as arguments to @code{gnatname}.
8081 Each Naming Pattern is enclosed between double quotes.
8082 A Naming Pattern is a regular expression similar to the wildcard patterns
8083 used in file names by the Unix shells or the DOS prompt.
8084
8085 @noindent
8086 Examples of Naming Patterns are
8087
8088 @smallexample
8089    "*.[12].ada"
8090    "*.ad[sb]*"
8091    "body_*"    "spec_*"
8092 @end smallexample
8093
8094 @noindent
8095 For a more complete description of the syntax of Naming Patterns, see the second kind
8096 of regular expressions described in @file{g-regexp.ads} (the "Glob" regular
8097 expressions).
8098
8099 @noindent
8100 When invoked with no switches, @code{gnatname} will create a configuration
8101 pragmas file @file{gnat.adc} in the current working directory, with pragmas
8102 @code{Source_File_Name} for each file that contains a valid Ada unit.
8103
8104 @node Switches for gnatname
8105 @section Switches for @code{gnatname}
8106
8107 @noindent
8108 Switches for @code{gnatname} must precede any specified Naming Pattern.
8109
8110 @noindent
8111 You may specify any of the following switches to @code{gnatname}:
8112
8113 @table @code
8114
8115 @item -c@file{file}
8116 @cindex @code{-c} (@code{gnatname})
8117 Create a configuration pragmas file @file{file} (instead of the default
8118 @file{gnat.adc}). There may be zero, one or more space between @code{-c} and
8119 @file{file}. @file{file} may include directory information. @file{file} must be
8120 writeable. There may be only one switch @code{-c}. When a switch @code{-c} is
8121 specified, no switch @code{-P} may be specified (see below).
8122
8123 @item -d@file{dir}
8124 @cindex @code{-d} (@code{gnatname})
8125 Look for source files in directory @file{dir}. There may be zero, one or more spaces
8126 between @code{-d} and @file{dir}. When a switch @code{-d} is specified,
8127 the current working directory will not be searched for source files, unless it
8128 is explictly
8129 specified with a @code{-d} or @code{-D} switch. Several switches @code{-d} may be
8130 specified. If @file{dir} is a relative path, it is relative to the directory of
8131 the configuration pragmas file specified with switch @code{-c}, or to the directory
8132 of the project file specified with switch @code{-P} or, if neither switch @code{-c}
8133 nor switch @code{-P} are specified, it is relative to the current working
8134 directory. The directory
8135 specified with switch @code{-c} must exist and be readable.
8136
8137 @item -D@file{file}
8138 @cindex @code{-D} (@code{gnatname})
8139 Look for source files in all directories listed in text file @file{file}. There may be
8140 zero, one or more spaces between @code{-d} and @file{dir}. @file{file}
8141 must be an existing, readable text file. Each non empty line in @file{file} must be
8142 a directory. Specifying switch @code{-D} is equivalent to specifying as many switches
8143 @code{-d} as there are non empty lines in @file{file}.
8144
8145 @item -h
8146 @cindex @code{-h} (@code{gnatname})
8147 Output usage (help) information. The output is written to @file{stdout}.
8148
8149 @item -P@file{proj}
8150 @cindex @code{-P} (@code{gnatname})
8151 Create or update project file @file{proj}. There may be zero, one or more space
8152 between @code{-P} and @file{proj}. @file{proj} may include directory information.
8153 @file{proj} must be writeable. There may be only one switch @code{-P}.
8154 When a switch @code{-P} is specified, no switch @code{-c} may be specified.
8155
8156 @item -v
8157 @cindex @code{-v} (@code{gnatname})
8158 Verbose mode. Output detailed explanation of behavior to @file{stdout}. This includes
8159 name of the file written, the name of the directories to search and, for each file
8160 in those directories whose name matches at least one of the Naming Patterns, an
8161 indication of whether the file contains a unit, and if so the name of the unit.
8162
8163 @item -v -v
8164 Very Verbose mode. In addition to the output produced in verbose mode, for each file
8165 in the searched directories whose name matches none of the Naming Patterns, an
8166 indication is given that there is no match.
8167
8168 @item -x@file{pattern}
8169 Excluded patterns. Using this switch, it is possible to exclude some files
8170 that would match the name patterns. For example,
8171 @code{"gnatname -x "*_nt.ada" "*.ada"} will look for Ada units in all files
8172 with the @file{.ada} extension, except those whose names end with
8173 @file{_nt.ada}.
8174
8175 @end table
8176
8177 @node Examples of gnatname Usage
8178 @section Examples of @code{gnatname} Usage
8179
8180 @smallexample
8181 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
8182 @end smallexample
8183
8184 In this example, the directory @file{/home/me} must already exist and be
8185 writeable. In addition, the directory @file{/home/me/sources} (specified by
8186 @code{-d sources}) must exist and be readable. Note the optional spaces after
8187 @code{-c} and @code{-d}.
8188
8189 @smallexample
8190 $ gnatname -P/home/me/proj -x "*_nt_body.ada" -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
8191 @end smallexample
8192
8193 Note that several switches @code{-d} may be used, even in conjunction with one
8194 or several switches @code{-D}. Several Naming Patterns and one excluded pattern
8195 are used in this example.
8196
8197
8198 @c *****************************************
8199 @c * G N A T  P r o j e c t  M a n a g e r *
8200 @c *****************************************
8201 @node GNAT Project Manager
8202 @chapter GNAT Project Manager
8203
8204 @menu
8205 * Introduction::
8206 * Examples of Project Files::
8207 * Project File Syntax::
8208 * Objects and Sources in Project Files::
8209 * Importing Projects::
8210 * Project Extension::
8211 * External References in Project Files::
8212 * Packages in Project Files::
8213 * Variables from Imported Projects::
8214 * Naming Schemes::
8215 * Library Projects::
8216 * Switches Related to Project Files::
8217 * Tools Supporting Project Files::
8218 * An Extended Example::
8219 * Project File Complete Syntax::
8220 @end menu
8221
8222
8223 @c ****************
8224 @c * Introduction *
8225 @c ****************
8226
8227 @node Introduction
8228 @section Introduction
8229
8230 @noindent
8231 This chapter describes GNAT's @emph{Project Manager}, a facility that
8232 lets you configure various properties for a collection of source files.  In
8233 particular, you can specify:
8234 @itemize @bullet
8235 @item
8236 The directory or set of directories containing the source files, and/or the
8237 names of the specific source files themselves
8238 @item
8239 The directory in which the compiler's output
8240 (@file{ALI} files, object files, tree files) will be placed
8241 @item
8242 The directory in which the executable programs will be placed
8243 @item
8244 Switch settings for any of the project-enabled tools (@command{gnatmake},
8245 compiler, binder, linker, @code{gnatls}, @code{gnatxref}, @code{gnatfind});
8246 you can apply these settings either globally or to individual units
8247 @item
8248 The source files containing the main subprogram(s) to be built
8249 @item
8250 The source programming language(s) (currently Ada and/or C)
8251 @item
8252 Source file naming conventions; you can specify these either globally or for
8253 individual units
8254 @end itemize
8255
8256 @menu
8257 * Project Files::
8258 @end menu
8259
8260 @node Project Files
8261 @subsection Project Files
8262
8263 @noindent
8264 A @dfn{project} is a specific set of values for these properties.  You can
8265 define a project's settings in a @dfn{project file}, a text file with an
8266 Ada-like syntax; a property value is either a string or a list of strings.
8267 Properties that are not explicitly set receive default values.  A project
8268 file may interrogate the values of @dfn{external variables} (user-defined
8269 command-line switches or environment variables), and it may specify property
8270 settings conditionally, based on the value of such variables.
8271
8272 In simple cases, a project's source files depend only on other source files
8273 in the same project, or on the predefined libraries.  ("Dependence" is in
8274 the technical sense; for example, one Ada unit "with"ing another.)  However,
8275 the Project Manager also allows much more sophisticated arrangements,
8276 with the source files in one project depending on source files in other
8277 projects:
8278 @itemize @bullet
8279 @item
8280 One project can @emph{import} other projects containing needed source files.
8281 @item
8282 You can organize GNAT projects in a hierarchy: a @emph{child} project
8283 can extend a @emph{parent} project, inheriting the parent's source files and
8284 optionally overriding any of them with alternative versions
8285 @end itemize
8286
8287 @noindent
8288 More generally, the Project Manager lets you structure large development
8289 efforts into hierarchical subsystems, with build decisions deferred to the
8290 subsystem level and thus different compilation environments (switch settings)
8291 used for different subsystems.
8292
8293 The Project Manager is invoked through the @option{-P@emph{projectfile}}
8294 switch to @command{gnatmake} or to the @command{gnat} front driver.
8295 If you want to define (on the command line) an external variable that is
8296 queried by the project file, additionally use the
8297 @option{-X@emph{vbl}=@emph{value}} switch.
8298 The Project Manager parses and interprets the project file, and drives the
8299 invoked tool based on the project settings.
8300
8301 The Project Manager supports a wide range of development strategies,
8302 for systems of all sizes.  Some typical practices that are easily handled:
8303 @itemize @bullet
8304 @item
8305 Using a common set of source files, but generating object files in different
8306 directories via different switch settings
8307 @item
8308 Using a mostly-shared set of source files, but with different versions of
8309 some unit or units
8310 @end itemize
8311
8312 @noindent
8313 The destination of an executable can be controlled inside a project file
8314 using the @option{-o} switch. In the absence of such a switch either inside
8315 the project file or on the command line, any executable files generated by
8316 @command{gnatmake} will be placed in the directory @code{Exec_Dir} specified
8317 in the project file. If no @code{Exec_Dir} is specified, they will be placed
8318 in the object directory of the project.
8319
8320 You can use project files to achieve some of the effects of a source
8321 versioning system (for example, defining separate projects for
8322 the different sets of sources that comprise different releases) but the
8323 Project Manager is independent of any source configuration management tools
8324 that might be used by the developers.
8325
8326 The next section introduces the main features of GNAT's project facility
8327 through a sequence of examples; subsequent sections will present the syntax
8328 and semantics in more detail.
8329
8330
8331 @c *****************************
8332 @c * Examples of Project Files *
8333 @c *****************************
8334
8335 @node Examples of Project Files
8336 @section Examples of Project Files
8337 @noindent
8338 This section illustrates some of the typical uses of project files and
8339 explains their basic structure and behavior.
8340
8341 @menu
8342 * Common Sources with Different Switches and Different Output Directories::
8343 * Using External Variables::
8344 * Importing Other Projects::
8345 * Extending a Project::
8346 @end menu
8347
8348 @node Common Sources with Different Switches and Different Output Directories
8349 @subsection Common Sources with Different Switches and Different Output Directories
8350
8351 @menu
8352 * Source Files::
8353 * Specifying the Object Directory::
8354 * Specifying the Exec Directory::
8355 * Project File Packages::
8356 * Specifying Switch Settings::
8357 * Main Subprograms::
8358 * Source File Naming Conventions::
8359 * Source Language(s)::
8360 @end menu
8361
8362 @noindent
8363 Assume that the Ada source files @file{pack.ads}, @file{pack.adb}, and
8364 @file{proc.adb} are in the @file{/common} directory.  The file
8365 @file{proc.adb} contains an Ada main subprogram @code{Proc} that "with"s
8366 package @code{Pack}.  We want to compile these source files under two sets
8367 of switches:
8368 @itemize @bullet
8369 @item
8370 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
8371 and the @option{-gnata}, @option{-gnato}, and @option{-gnatE} switches to the
8372 compiler; the compiler's output is to appear in @file{/common/debug}
8373 @item
8374 When preparing a release version, we want to pass the @option{-O2} switch to
8375 the compiler; the compiler's output is to appear in @file{/common/release}
8376 @end itemize
8377
8378 @noindent
8379 The GNAT project files shown below, respectively @file{debug.gpr} and
8380 @file{release.gpr} in the @file{/common} directory, achieve these effects.
8381
8382 Diagrammatically:
8383 @smallexample
8384 @group
8385 /common
8386   debug.gpr
8387   release.gpr
8388   pack.ads
8389   pack.adb
8390   proc.adb
8391 @end group
8392 @group
8393 /common/debug @{-g, -gnata, -gnato, -gnatE@}
8394   proc.ali, proc.o
8395   pack.ali, pack.o
8396 @end group
8397 @group
8398 /common/release @{-O2@}
8399   proc.ali, proc.o
8400   pack.ali, pack.o
8401 @end group
8402 @end smallexample
8403 Here are the project files:
8404 @smallexample
8405 @group
8406 project Debug is
8407   for Object_Dir use "debug";
8408   for Main use ("proc");
8409
8410   package Builder is
8411     for Default_Switches ("Ada") use ("-g");
8412   end Builder;
8413 @end group
8414
8415 @group
8416   package Compiler is
8417     for Default_Switches ("Ada")
8418        use ("-fstack-check", "-gnata", "-gnato", "-gnatE");
8419   end Compiler;
8420 end Debug;
8421 @end group
8422 @end smallexample
8423
8424 @smallexample
8425 @group
8426 project Release is
8427   for Object_Dir use "release";
8428   for Exec_Dir use ".";
8429   for Main use ("proc");
8430
8431   package Compiler is
8432     for Default_Switches ("Ada") use ("-O2");
8433   end Compiler;
8434 end Release;
8435 @end group
8436 @end smallexample
8437
8438 @noindent
8439 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
8440 insensitive), and analogously the project defined by @file{release.gpr} is
8441 @code{"Release"}.  For consistency the file should have the same name as the
8442 project, and the project file's extension should be @code{"gpr"}. These
8443 conventions are not required, but a warning is issued if they are not followed.
8444
8445 If the current directory is @file{/temp}, then the command
8446 @smallexample
8447 gnatmake -P/common/debug.gpr
8448 @end smallexample
8449
8450 @noindent
8451 generates object and ALI files in @file{/common/debug}, and the @code{proc}
8452 executable also in @file{/common/debug}, using the switch settings defined in
8453 the project file.
8454
8455 Likewise, the command
8456 @smallexample
8457 gnatmake -P/common/release.gpr
8458 @end smallexample
8459
8460 @noindent
8461 generates object and ALI files in @file{/common/release}, and the @code{proc}
8462 executable in @file{/common}, using the switch settings from the project file.
8463
8464 @node Source Files
8465 @unnumberedsubsubsec Source Files
8466
8467 @noindent
8468 If a project file does not explicitly specify a set of source directories or
8469 a set of source files, then by default the project's source files are the
8470 Ada source files in the project file directory.  Thus @file{pack.ads},
8471 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
8472
8473 @node Specifying the Object Directory
8474 @unnumberedsubsubsec Specifying the Object Directory
8475
8476 @noindent
8477 Several project properties are modeled by Ada-style @emph{attributes};
8478 you define the property by supplying the equivalent of an Ada attribute
8479 definition clause in the project file.
8480 A project's object directory is such a property; the corresponding
8481 attribute is @code{Object_Dir}, and its value is a string expression.  A
8482 directory may be specified either as absolute or as relative; in the latter
8483 case, it is relative to the project file directory.  Thus the compiler's
8484 output is directed to @file{/common/debug} (for the @code{Debug} project)
8485 and to @file{/common/release} (for the @code{Release} project).  If
8486 @code{Object_Dir} is not specified, then the default is the project file
8487 directory.
8488
8489 @node Specifying the Exec Directory
8490 @unnumberedsubsubsec Specifying the Exec Directory
8491
8492 @noindent
8493 A project's exec directory is another property; the corresponding
8494 attribute is @code{Exec_Dir}, and its value is also a string expression,
8495 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
8496 then the default is the object directory (which may also be the project file
8497 directory if attribute @code{Object_Dir} is not specified). Thus the executable
8498 is placed in @file{/common/debug} for the @code{Debug} project (attribute
8499 @code{Exec_Dir} not specified) and in @file{/common} for the @code{Release}
8500 project.
8501
8502 @node Project File Packages
8503 @unnumberedsubsubsec Project File Packages
8504
8505 @noindent
8506 A GNAT tool integrated with the Project Manager is modeled by a
8507 corresponding package in the project file.
8508 The @code{Debug} project defines the packages @code{Builder}
8509 (for @command{gnatmake}) and @code{Compiler};
8510 the @code{Release} project defines only the @code{Compiler} package.
8511
8512 The Ada package syntax is not to be taken literally.  Although packages in
8513 project files bear a surface resemblance to packages in Ada source code, the
8514 notation is simply a way to convey a grouping of properties for a named
8515 entity.  Indeed, the package names permitted in project files are restricted
8516 to a predefined set, corresponding to the project-aware tools, and the contents
8517 of packages are limited to a small set of constructs.
8518 The packages in the example above contain attribute definitions.
8519
8520
8521 @node Specifying Switch Settings
8522 @unnumberedsubsubsec Specifying Switch Settings
8523
8524 @noindent
8525 Switch settings for a project-aware tool can be specified through attributes
8526 in the package corresponding to the tool.
8527 The example above illustrates one of the relevant attributes,
8528 @code{Default_Switches}, defined in the packages in both project files.
8529 Unlike simple attributes like @code{Source_Dirs}, @code{Default_Switches} is
8530 known as an @emph{associative array}.  When you define this attribute, you must
8531 supply an "index" (a literal string), and the effect of the attribute
8532 definition is to set the value of the "array" at the specified "index".
8533 For the @code{Default_Switches} attribute, the index is a programming
8534 language (in our case, Ada) , and the value specified (after @code{use})
8535 must be a list of string expressions.
8536
8537 The attributes permitted in project files are restricted to a predefined set.
8538 Some may appear at project level, others in packages.
8539 For any attribute that is an associate array, the index must always be a
8540 literal string, but the restrictions on this string (e.g., a file name or a
8541 language name) depend on the individual attribute.
8542 Also depending on the attribute, its specified value will need to be either a
8543 string or a string list.
8544
8545 In the @code{Debug} project, we set the switches for two tools,
8546 @command{gnatmake} and the compiler, and thus we include corresponding
8547 packages, with each package defining the @code{Default_Switches} attribute
8548 with index @code{"Ada"}.
8549 Note that the package corresponding to
8550 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
8551 similar, but with just the @code{Compiler} package.
8552
8553 In project @code{Debug} above the switches starting with @option{-gnat} that
8554 are specified in package @code{Compiler} could have been placed in package
8555 @code{Builder}, since @command{gnatmake} transmits all such switches to the
8556 compiler.
8557
8558 @node Main Subprograms
8559 @unnumberedsubsubsec Main Subprograms
8560
8561 @noindent
8562 One of the properties of a project is its list of main subprograms (actually
8563 a list of names of source files containing main subprograms, with the file
8564 extension optional.  This property is captured in the @code{Main} attribute,
8565 whose value is a list of strings.  If a project defines the @code{Main}
8566 attribute, then you do not need to identify the main subprogram(s) when
8567 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
8568
8569 @node Source File Naming Conventions
8570 @unnumberedsubsubsec Source File Naming Conventions
8571
8572 @noindent
8573 Since the project files do not specify any source file naming conventions,
8574 the GNAT defaults are used.  The mechanism for defining source file naming
8575 conventions -- a package named @code{Naming} -- will be described below
8576 (@pxref{Naming Schemes}).
8577
8578 @node Source Language(s)
8579 @unnumberedsubsubsec Source Language(s)
8580
8581 @noindent
8582 Since the project files do not specify a @code{Languages} attribute, by
8583 default the GNAT tools assume that the language of the project file is Ada.
8584 More generally, a project can comprise source files
8585 in Ada, C, and/or other languages.
8586
8587 @node Using External Variables
8588 @subsection Using External Variables
8589
8590 @noindent
8591 Instead of supplying different project files for debug and release, we can
8592 define a single project file that queries an external variable (set either
8593 on the command line or via an environment variable) in order to
8594 conditionally define the appropriate settings.  Again, assume that the
8595 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
8596 located in directory @file{/common}.  The following project file,
8597 @file{build.gpr}, queries the external variable named @code{STYLE} and
8598 defines an object directory and switch settings based on whether the value
8599 is @code{"deb"} (debug) or @code{"rel"} (release), where the default is
8600 @code{"deb"}.
8601
8602 @smallexample
8603 @group
8604 project Build is
8605   for Main use ("proc");
8606
8607   type Style_Type is ("deb", "rel");
8608   Style : Style_Type := external ("STYLE", "deb");
8609
8610   case Style is
8611     when "deb" =>
8612       for Object_Dir use "debug";
8613
8614     when "rel" =>
8615       for Object_Dir use "release";
8616       for Exec_Dir use ".";
8617   end case;
8618 @end group
8619
8620 @group
8621   package Builder is
8622
8623     case Style is
8624       when "deb" =>
8625         for Default_Switches ("Ada") use ("-g");
8626     end case;
8627
8628   end Builder;
8629 @end group
8630
8631 @group
8632   package Compiler is
8633
8634     case Style is
8635       when "deb" =>
8636         for Default_Switches ("Ada") use ("-gnata", "-gnato", "-gnatE");
8637
8638       when "rel" =>
8639         for Default_Switches ("Ada") use ("-O2");
8640     end case;
8641
8642   end Compiler;
8643
8644 end Build;
8645 @end group
8646 @end smallexample
8647
8648 @noindent
8649 @code{Style_Type} is an example of a @emph{string type}, which is the project
8650 file analog of an Ada enumeration type but containing string literals rather
8651 than identifiers.  @code{Style} is declared as a variable of this type.
8652
8653 The form @code{external("STYLE", "deb")} is known as an
8654 @emph{external reference}; its first argument is the name of an
8655 @emph{external variable}, and the second argument is a default value to be
8656 used if the external variable doesn't exist.  You can define an external
8657 variable on the command line via the @option{-X} switch, or you can use an
8658 environment variable as an external variable.
8659
8660 Each @code{case} construct is expanded by the Project Manager based on the
8661 value of @code{Style}. Thus the command
8662 @smallexample
8663 gnatmake -P/common/build.gpr -XSTYLE=deb
8664 @end smallexample
8665
8666 @noindent
8667 is equivalent to the @command{gnatmake} invocation using the project file
8668 @file{debug.gpr} in the earlier example.  So is the command
8669 @smallexample
8670 gnatmake -P/common/build.gpr
8671 @end smallexample
8672
8673 @noindent
8674 since @code{"deb"} is the default for @code{STYLE}.
8675
8676 Analogously,
8677 @smallexample
8678 gnatmake -P/common/build.gpr -XSTYLE=rel
8679 @end smallexample
8680
8681 @noindent
8682 is equivalent to the @command{gnatmake} invocation using the project file
8683 @file{release.gpr} in the earlier example.
8684
8685
8686 @node Importing Other Projects
8687 @subsection Importing Other Projects
8688
8689 @noindent
8690 A compilation unit in a source file in one project may depend on compilation
8691 units in source files in other projects.  To obtain this behavior, the
8692 dependent project must @emph{import} the projects containing the needed source
8693 files.  This effect is embodied in syntax similar to an Ada @code{with} clause,
8694 but the "with"ed entities are strings denoting project files.
8695
8696 As an example, suppose that the two projects @code{GUI_Proj} and
8697 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
8698 @file{comm_proj.gpr} in directories @file{/gui} and @file{/comm},
8699 respectively.  Assume that the source files for @code{GUI_Proj} are
8700 @file{gui.ads} and @file{gui.adb}, and that the source files for
8701 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, with each set of
8702 files located in its respective project file directory.  Diagrammatically:
8703
8704 @smallexample
8705 @group
8706 /gui
8707   gui_proj.gpr
8708   gui.ads
8709   gui.adb
8710 @end group
8711
8712 @group
8713 /comm
8714   comm_proj.gpr
8715   comm.ads
8716   comm.adb
8717 @end group
8718 @end smallexample
8719
8720 @noindent
8721 We want to develop an application in directory @file{/app} that "with"s the
8722 packages @code{GUI} and @code{Comm}, using the properties of the
8723 corresponding project files (e.g. the switch settings and object directory).
8724 Skeletal code for a main procedure might be something like the following:
8725
8726 @smallexample
8727 @group
8728 with GUI, Comm;
8729 procedure App_Main is
8730    ...
8731 begin
8732    ...
8733 end App_Main;
8734 @end group
8735 @end smallexample
8736
8737 @noindent
8738 Here is a project file, @file{app_proj.gpr}, that achieves the desired
8739 effect:
8740
8741 @smallexample
8742 @group
8743 with "/gui/gui_proj", "/comm/comm_proj";
8744 project App_Proj is
8745    for Main use ("app_main");
8746 end App_Proj;
8747 @end group
8748 @end smallexample
8749
8750 @noindent
8751 Building an executable is achieved through the command:
8752 @smallexample
8753 gnatmake -P/app/app_proj
8754 @end smallexample
8755 @noindent
8756 which will generate the @code{app_main} executable in the directory where
8757 @file{app_proj.gpr} resides.
8758
8759 If an imported project file uses the standard extension (@code{gpr}) then
8760 (as illustrated above) the @code{with} clause can omit the extension.
8761
8762 Our example specified an absolute path for each imported project file.
8763 Alternatively, you can omit the directory if either
8764 @itemize @bullet
8765 @item
8766 The imported project file is in the same directory as the importing project
8767 file, or
8768 @item
8769 You have defined an environment variable @code{ADA_PROJECT_PATH} that
8770 includes the directory containing the needed project file.
8771 @end itemize
8772
8773 @noindent
8774 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{/gui} and
8775 @file{/comm}, then our project file @file{app_proj.gpr} could be written as
8776 follows:
8777
8778 @smallexample
8779 @group
8780 with "gui_proj", "comm_proj";
8781 project App_Proj is
8782    for Main use ("app_main");
8783 end App_Proj;
8784 @end group
8785 @end smallexample
8786
8787 @noindent
8788 Importing other projects raises the possibility of ambiguities.  For
8789 example, the same unit might be present in different imported projects, or
8790 it might be present in both the importing project and an imported project.
8791 Both of these conditions are errors.  Note that in the current version of
8792 the Project Manager, it is illegal to have an ambiguous unit even if the
8793 unit is never referenced by the importing project.  This restriction may be
8794 relaxed in a future release.
8795
8796 @node Extending a Project
8797 @subsection Extending a Project
8798
8799 @noindent
8800 A common situation in large software systems is to have multiple
8801 implementations for a common interface; in Ada terms, multiple versions of a
8802 package body for the same specification.  For example, one implementation
8803 might be safe for use in tasking programs, while another might only be used
8804 in sequential applications.  This can be modeled in GNAT using the concept
8805 of @emph{project extension}.  If one project (the "child") @emph{extends}
8806 another project (the "parent") then by default all source files of the
8807 parent project are inherited by the child, but the child project can
8808 override any of the parent's source files with new versions, and can also
8809 add new files.  This facility is the project analog of extension in
8810 Object-Oriented Programming.  Project hierarchies are permitted (a child
8811 project may be the parent of yet another project), and a project that
8812 inherits one project can also import other projects.
8813
8814 As an example, suppose that directory @file{/seq} contains the project file
8815 @file{seq_proj.gpr} and the source files @file{pack.ads}, @file{pack.adb},
8816 and @file{proc.adb}:
8817
8818 @smallexample
8819 @group
8820 /seq
8821   pack.ads
8822   pack.adb
8823   proc.adb
8824   seq_proj.gpr
8825 @end group
8826 @end smallexample
8827
8828 @noindent
8829 Note that the project file can simply be empty (that is, no attribute or
8830 package is defined):
8831
8832 @smallexample
8833 @group
8834 project Seq_Proj is
8835 end Seq_Proj;
8836 @end group
8837 @end smallexample
8838
8839 @noindent
8840 implying that its source files are all the Ada source files in the project
8841 directory.
8842
8843 Suppose we want to supply an alternate version of @file{pack.adb}, in
8844 directory @file{/tasking}, but use the existing versions of @file{pack.ads}
8845 and @file{proc.adb}.  We can define a project @code{Tasking_Proj} that
8846 inherits @code{Seq_Proj}:
8847
8848 @smallexample
8849 @group
8850 /tasking
8851   pack.adb
8852   tasking_proj.gpr
8853 @end group
8854
8855 @group
8856 project Tasking_Proj extends "/seq/seq_proj" is
8857 end Tasking_Proj;
8858 @end group
8859 @end smallexample
8860
8861 @noindent
8862 The version of @file{pack.adb} used in a build depends on which project file
8863 is specified.
8864
8865 Note that we could have designed this using project import rather than
8866 project inheritance; a @code{base} project would contain the sources for
8867 @file{pack.ads} and @file{proc.adb}, a sequential project would import
8868 @code{base} and add @file{pack.adb}, and likewise a tasking project would
8869 import @code{base} and add a different version of @file{pack.adb}.  The
8870 choice depends on whether other sources in the original project need to be
8871 overridden.  If they do, then project extension is necessary, otherwise,
8872 importing is sufficient.
8873
8874
8875 @c ***********************
8876 @c * Project File Syntax *
8877 @c ***********************
8878
8879 @node Project File Syntax
8880 @section Project File Syntax
8881
8882 @menu
8883 * Basic Syntax::
8884 * Packages::
8885 * Expressions::
8886 * String Types::
8887 * Variables::
8888 * Attributes::
8889 * Associative Array Attributes::
8890 * case Constructions::
8891 @end menu
8892
8893 @noindent
8894 This section describes the structure of project files.
8895
8896 A project may be an @emph{independent project}, entirely defined by a single
8897 project file. Any Ada source file in an independent project depends only
8898 on the predefined library and other Ada source files in the same project.
8899
8900 @noindent
8901 A project may also @dfn{depend on} other projects, in either or both of the following ways:
8902 @itemize @bullet
8903 @item It may import any number of projects
8904 @item It may extend at most one other project
8905 @end itemize
8906
8907 @noindent
8908 The dependence relation is a directed acyclic graph (the subgraph reflecting
8909 the "extends" relation is a tree).
8910
8911 A project's @dfn{immediate sources} are the source files directly defined by
8912 that project, either implicitly by residing in the project file's directory,
8913 or explicitly through any of the source-related attributes described below.
8914 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
8915 of @var{proj} together with the immediate sources (unless overridden) of any
8916 project on which @var{proj} depends (either directly or indirectly).
8917
8918 @node Basic Syntax
8919 @subsection Basic Syntax
8920
8921 @noindent
8922 As seen in the earlier examples, project files have an Ada-like syntax.
8923 The minimal project file is:
8924 @smallexample
8925 @group
8926 project Empty is
8927
8928 end Empty;
8929 @end group
8930 @end smallexample
8931
8932 @noindent
8933 The identifier @code{Empty} is the name of the project.
8934 This project name must be present after the reserved
8935 word @code{end} at the end of the project file, followed by a semi-colon.
8936
8937 Any name in a project file, such as the project name or a variable name,
8938 has the same syntax as an Ada identifier.
8939
8940 The reserved words of project files are the Ada reserved words plus
8941 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
8942 reserved words currently used in project file syntax are:
8943
8944 @itemize @bullet
8945 @item
8946 @code{case}
8947 @item
8948 @code{end}
8949 @item
8950 @code{for}
8951 @item
8952 @code{is}
8953 @item
8954 @code{others}
8955 @item
8956 @code{package}
8957 @item
8958 @code{renames}
8959 @item
8960 @code{type}
8961 @item
8962 @code{use}
8963 @item
8964 @code{when}
8965 @item
8966 @code{with}
8967 @end itemize
8968
8969 @noindent
8970 Comments in project files have the same syntax as in Ada, two consecutives
8971 hyphens through the end of the line.
8972
8973 @node Packages
8974 @subsection Packages
8975
8976 @noindent
8977 A project file may contain @emph{packages}. The name of a package must be one
8978 of the identifiers (case insensitive) from a predefined list, and a package
8979 with a given name may only appear once in a project file. The predefined list
8980 includes the following packages:
8981
8982 @itemize @bullet
8983 @item
8984 @code{Naming}
8985 @item
8986 @code{Builder}
8987 @item
8988 @code{Compiler}
8989 @item
8990 @code{Binder}
8991 @item
8992 @code{Linker}
8993 @item
8994 @code{Finder}
8995 @item
8996 @code{Cross_Reference}
8997 @item
8998 @code{gnatls}
8999 @end itemize
9000
9001 @noindent
9002 (The complete list of the package names and their attributes can be found
9003 in file @file{prj-attr.adb}).
9004
9005 @noindent
9006 In its simplest form, a package may be empty:
9007
9008 @smallexample
9009 @group
9010 project Simple is
9011   package Builder is
9012   end Builder;
9013 end Simple;
9014 @end group
9015 @end smallexample
9016
9017 @noindent
9018 A package may contain @emph{attribute declarations},
9019 @emph{variable declarations} and @emph{case constructions}, as will be
9020 described below.
9021
9022 When there is ambiguity between a project name and a package name,
9023 the name always designates the project. To avoid possible confusion, it is
9024 always a good idea to avoid naming a project with one of the
9025 names allowed for packages or any name that starts with @code{gnat}.
9026
9027
9028 @node Expressions
9029 @subsection Expressions
9030
9031 @noindent
9032 An @emph{expression} is either a @emph{string expression} or a
9033 @emph{string list expression}.
9034
9035 A @emph{string expression} is either a @emph{simple string expression} or a
9036 @emph{compound string expression}.
9037
9038 A @emph{simple string expression} is one of the following:
9039 @itemize @bullet
9040 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
9041 @item A string-valued variable reference (see @ref{Variables})
9042 @item A string-valued attribute reference (see @ref{Attributes})
9043 @item An external reference (see @ref{External References in Project Files})
9044 @end itemize
9045
9046 @noindent
9047 A @emph{compound string expression} is a concatenation of string expressions,
9048 using @code{"&"}
9049 @smallexample
9050        Path & "/" & File_Name & ".ads"
9051 @end smallexample
9052
9053 @noindent
9054 A @emph{string list expression} is either a
9055 @emph{simple string list expression} or a
9056 @emph{compound string list expression}.
9057
9058 A @emph{simple string list expression} is one of the following:
9059 @itemize @bullet
9060 @item A parenthesized list of zero or more string expressions, separated by commas
9061 @smallexample
9062    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
9063    Empty_List := ();
9064 @end smallexample
9065 @item A string list-valued variable reference
9066 @item A string list-valued attribute reference
9067 @end itemize
9068
9069 @noindent
9070 A @emph{compound string list expression} is the concatenation (using
9071 @code{"&"}) of a simple string list expression and an expression.  Note that
9072 each term in a compound string list expression, except the first, may be
9073 either a string expression or a string list expression.
9074
9075 @smallexample
9076 @group
9077    File_Name_List := () & File_Name; --  One string in this list
9078    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
9079    --  Two strings
9080    Big_List := File_Name_List & Extended_File_Name_List;
9081    --  Concatenation of two string lists: three strings
9082    Illegal_List := "gnat.adc" & Extended_File_Name_List;
9083    --  Illegal: must start with a string list
9084 @end group
9085 @end smallexample
9086
9087
9088 @node String Types
9089 @subsection String Types
9090
9091 @noindent
9092 The value of a variable may be restricted to a list of string literals.
9093 The restricted list of string literals is given in a
9094 @emph{string type declaration}.
9095
9096 Here is an example of a string type declaration:
9097
9098 @smallexample
9099    type OS is ("NT, "nt", "Unix", "Linux", "other OS");
9100 @end smallexample
9101
9102 @noindent
9103 Variables of a string type are called @emph{typed variables}; all other
9104 variables are called @emph{untyped variables}. Typed variables are
9105 particularly useful in @code{case} constructions
9106 (see @ref{case Constructions}).
9107
9108 A string type declaration starts with the reserved word @code{type}, followed
9109 by the name of the string type (case-insensitive), followed by the reserved
9110 word @code{is}, followed by a parenthesized list of one or more string literals
9111 separated by commas, followed by a semicolon.
9112
9113 The string literals in the list are case sensitive and must all be different.
9114 They may include any graphic characters allowed in Ada, including spaces.
9115
9116 A string type may only be declared at the project level, not inside a package.
9117
9118 A string type may be referenced by its name if it has been declared in the same
9119 project file, or by its project name, followed by a dot,
9120 followed by the string type name.
9121
9122
9123 @node Variables
9124 @subsection Variables
9125
9126 @noindent
9127 A variable may be declared at the project file level, or in a package.
9128 Here are some examples of variable declarations:
9129
9130 @smallexample
9131 @group
9132    This_OS : OS := external ("OS"); --  a typed variable declaration
9133    That_OS := "Linux";              --  an untyped variable declaration
9134 @end group
9135 @end smallexample
9136
9137 @noindent
9138 A @emph{typed variable declaration} includes the variable name, followed by a colon,
9139 followed by the name of a string type, followed by @code{:=}, followed by
9140 a simple string expression.
9141
9142 An @emph{untyped variable declaration} includes the variable name,
9143 followed by @code{:=}, followed by an expression.  Note that, despite the
9144 terminology, this form of "declaration" resembles more an assignment
9145 than a declaration in Ada.  It is a declaration in several senses:
9146 @itemize @bullet
9147 @item
9148 The variable name does not need to be defined previously
9149 @item
9150 The declaration establishes the @emph{kind} (string versus string list) of the
9151 variable, and later declarations of the same variable need to be consistent
9152 with this
9153 @end itemize
9154
9155 @noindent
9156 A string variable declaration (typed or untyped) declares a variable
9157 whose value is a string. This variable may be used as a string expression.
9158 @smallexample
9159    File_Name       := "readme.txt";
9160    Saved_File_Name := File_Name & ".saved";
9161 @end smallexample
9162
9163 @noindent
9164 A string list variable declaration declares a variable whose value is a list
9165 of strings. The list may contain any number (zero or more) of strings.
9166
9167 @smallexample
9168    Empty_List := ();
9169    List_With_One_Element := ("-gnaty");
9170    List_With_Two_Elements := List_With_One_Element & "-gnatg";
9171    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
9172                  "pack2.ada", "util_.ada", "util.ada");
9173 @end smallexample
9174
9175 @noindent
9176 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.
9177
9178 The same untyped variable may be declared several times.
9179 In this case, the new value replaces the old one,
9180 and any subsequent reference to the variable uses the new value.
9181 However, as noted above, if a variable has been declared as a string, all subsequent
9182 declarations must give it a string value. Similarly, if a variable has
9183 been declared as a string list, all subsequent declarations
9184 must give it a string list value.
9185
9186 A @emph{variable reference} may take several forms:
9187
9188 @itemize @bullet
9189 @item The simple variable name, for a variable in the current package (if any) or in the current project
9190 @item A context name, followed by a dot, followed by the variable name.
9191 @end itemize
9192
9193 @noindent
9194 A @emph{context} may be one of the following:
9195
9196 @itemize @bullet
9197 @item The name of an existing package in the current project
9198 @item The name of an imported project of the current project
9199 @item The name of an ancestor project (i.e., a project extended by the current project, either directly or indirectly)
9200 @item An imported/parent project name, followed by a dot, followed by a package name
9201 @end itemize
9202
9203 @noindent
9204 A variable reference may be used in an expression.
9205
9206
9207 @node Attributes
9208 @subsection Attributes
9209
9210 @noindent
9211 A project (and its packages) may have @emph{attributes} that define the project's properties.
9212 Some attributes have values that are strings;
9213 others have values that are string lists.
9214
9215 There are two categories of attributes: @emph{simple attributes} and @emph{associative arrays}
9216 (see @ref{Associative Array Attributes}).
9217
9218 The names of the attributes are restricted; there is a list of project
9219 attributes, and a list of package attributes for each package.
9220 The names are not case sensitive.
9221
9222 The project attributes are as follows (all are simple attributes):
9223
9224 @multitable @columnfractions .4 .3
9225 @item @emph{Attribute Name}
9226 @tab @emph{Value}
9227 @item @code{Source_Files}
9228 @tab string list
9229 @item @code{Source_Dirs}
9230 @tab string list
9231 @item @code{Source_List_File}
9232 @tab string
9233 @item @code{Object_Dir}
9234 @tab string
9235 @item @code{Exec_Dir}
9236 @tab string
9237 @item @code{Main}
9238 @tab string list
9239 @item @code{Languages}
9240 @tab string list
9241 @item @code{Library_Dir}
9242 @tab string
9243 @item @code{Library_Name}
9244 @tab string
9245 @item @code{Library_Kind}
9246 @tab string
9247 @item @code{Library_Elaboration}
9248 @tab string
9249 @item @code{Library_Version}
9250 @tab string
9251 @end multitable
9252
9253 @noindent
9254 The attributes for package @code{Naming} are as follows
9255 (see @ref{Naming Schemes}):
9256
9257 @multitable @columnfractions .4 .2 .2 .2
9258 @item Attribute Name @tab Category @tab Index @tab Value
9259 @item @code{Specification_Suffix}
9260 @tab associative array
9261 @tab language name
9262 @tab string
9263 @item @code{Implementation_Suffix}
9264 @tab associative array
9265 @tab language name
9266 @tab string
9267 @item @code{Separate_Suffix}
9268 @tab simple attribute
9269 @tab n/a
9270 @tab string
9271 @item @code{Casing}
9272 @tab simple attribute
9273 @tab n/a
9274 @tab string
9275 @item @code{Dot_Replacement}
9276 @tab simple attribute
9277 @tab n/a
9278 @tab string
9279 @item @code{Specification}
9280 @tab associative array
9281 @tab Ada unit name
9282 @tab string
9283 @item @code{Implementation}
9284 @tab associative array
9285 @tab Ada unit name
9286 @tab string
9287 @item @code{Specification_Exceptions}
9288 @tab associative array
9289 @tab language name
9290 @tab string list
9291 @item @code{Implementation_Exceptions}
9292 @tab associative array
9293 @tab language name
9294 @tab string list
9295 @end multitable
9296
9297 @noindent
9298 The attributes for package @code{Builder}, @code{Compiler}, @code{Binder},
9299 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
9300 are as follows (see @ref{Switches and Project Files}).
9301
9302 @multitable @columnfractions .4 .2 .2 .2
9303 @item Attribute Name @tab Category @tab Index @tab Value
9304 @item @code{Default_Switches}
9305 @tab associative array
9306 @tab language name
9307 @tab string list
9308 @item @code{Switches}
9309 @tab associative array
9310 @tab file name
9311 @tab string list
9312 @end multitable
9313
9314 @noindent
9315 In addition, package @code{Builder} has a single string attribute
9316 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
9317 string attribute @code{Global_Configuration_Pragmas}.
9318
9319 @noindent
9320 The attribute for package @code{Glide} are not documented: they are for
9321 internal use only.
9322
9323 @noindent
9324 Each simple attribute has a default value: the empty string (for string-valued
9325 attributes) and the empty list (for string list-valued attributes).
9326
9327 Similar to variable declarations, an attribute declaration defines a new value
9328 for an attribute.
9329
9330 Examples of simple attribute declarations:
9331
9332 @smallexample
9333    for Object_Dir use "objects";
9334    for Source_Dirs use ("units", "test/drivers");
9335 @end smallexample
9336
9337 @noindent
9338 A @dfn{simple attribute declaration} starts with the reserved word @code{for},
9339 followed by the name of the attribute, followed by the reserved word
9340 @code{use}, followed by an expression (whose kind depends on the attribute),
9341 followed by a semicolon.
9342
9343 Attributes may be referenced in expressions.
9344 The general form for such a reference is @code{<entity>'<attribute>}:
9345 the entity for which the attribute is defined,
9346 followed by an apostrophe, followed by the name of the attribute.
9347 For associative array attributes, a litteral string between parentheses
9348 need to be supplied as index.
9349
9350 Examples are:
9351
9352 @smallexample
9353   project'Object_Dir
9354   Naming'Dot_Replacement
9355   Imported_Project'Source_Dirs
9356   Imported_Project.Naming'Casing
9357   Builder'Default_Switches("Ada")
9358 @end smallexample
9359
9360 @noindent
9361 The entity may be:
9362 @itemize @bullet
9363 @item @code{project} for an attribute of the current project
9364 @item The name of an existing package of the current project
9365 @item The name of an imported project
9366 @item The name of a parent project (extended by the current project)
9367 @item An imported/parent project name, followed by a dot,
9368       followed by a package name
9369 @end itemize
9370
9371 @noindent
9372 Example:
9373 @smallexample
9374 @group
9375    project Prj is
9376      for Source_Dirs use project'Source_Dirs & "units";
9377      for Source_Dirs use project'Source_Dirs & "test/drivers"
9378    end Prj;
9379 @end group
9380 @end smallexample
9381
9382 @noindent
9383 In the first attribute declaration, initially the attribute @code{Source_Dirs}
9384 has the default value: an empty string list. After this declaration,
9385 @code{Source_Dirs} is a string list of one element: "units".
9386 After the second attribute declaration @code{Source_Dirs} is a string list of
9387 two elements: "units" and "test/drivers".
9388
9389 Note: this example is for illustration only. In practice,
9390 the project file would contain only one attribute declaration:
9391
9392 @smallexample
9393    for Source_Dirs use ("units", "test/drivers");
9394 @end smallexample
9395
9396
9397 @node Associative Array Attributes
9398 @subsection Associative Array Attributes
9399
9400 @noindent
9401 Some attributes are defined as @emph{associative arrays}. An associative
9402 array may be regarded as a function that takes a string as a parameter
9403 and delivers a string or string list value as its result.
9404
9405 Here are some examples of associative array attribute declarations:
9406
9407 @smallexample
9408    for Implementation ("main") use "Main.ada";
9409    for Switches ("main.ada") use ("-v", "-gnatv");
9410    for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g";
9411 @end smallexample
9412
9413 @noindent
9414 Like untyped variables and simple attributes, associative array attributes may be declared several times. Each declaration supplies a new value for the
9415 attribute, replacing the previous setting.
9416
9417
9418 @node case Constructions
9419 @subsection @code{case} Constructions
9420
9421 @noindent
9422 A @code{case} construction is used in a project file to effect conditional
9423 behavior.
9424 Here is a typical example:
9425
9426 @smallexample
9427 @group
9428 project MyProj is
9429    type OS_Type is ("Linux", "Unix", "NT", "VMS");
9430
9431    OS : OS_Type := external ("OS", "Linux");
9432 @end group
9433
9434 @group
9435    package Compiler is
9436      case OS is
9437        when "Linux" | "Unix" =>
9438          for Default_Switches ("Ada") use ("-gnath");
9439        when "NT" =>
9440          for Default_Switches ("Ada") use ("-gnatP");
9441        when others =>
9442      end case;
9443    end Compiler;
9444 end MyProj;
9445 @end group
9446 @end smallexample
9447
9448 @noindent
9449 The syntax of a @code{case} construction is based on the Ada case statement
9450 (although there is no @code{null} construction for empty alternatives).
9451
9452 Following the reserved word @code{case} there is the case variable (a typed
9453 string variable), the reserved word @code{is}, and then a sequence of one or
9454 more alternatives.
9455 Each alternative comprises the reserved word @code{when}, either a list of
9456 literal strings separated by the @code{"|"} character or the reserved word
9457 @code{others},  and the @code{"=>"} token.
9458 Each literal string must belong to the string type that is the type of the
9459 case variable.
9460 An @code{others} alternative, if present, must occur last.
9461 The @code{end case;} sequence terminates the case construction.
9462
9463 After each @code{=>}, there are zero or more constructions.  The only
9464 constructions allowed in a case construction are other case constructions and
9465 attribute declarations. String type declarations, variable declarations and
9466 package declarations are not allowed.
9467
9468 The value of the case variable is often given by an external reference
9469 (see @ref{External References in Project Files}).
9470
9471
9472 @c ****************************************
9473 @c * Objects and Sources in Project Files *
9474 @c ****************************************
9475
9476 @node Objects and Sources in Project Files
9477 @section Objects and Sources in Project Files
9478
9479 @menu
9480 * Object Directory::
9481 * Exec Directory::
9482 * Source Directories::
9483 * Source File Names::
9484 @end menu
9485
9486 @noindent
9487 Each project has exactly one object directory and one or more source
9488 directories. The source directories must contain at least one source file,
9489 unless  the project file explicitly specifies that no source files are present
9490 (see @ref{Source File Names}).
9491
9492
9493 @node Object Directory
9494 @subsection Object Directory
9495
9496 @noindent
9497 The object directory for a project is the directory containing the compiler's
9498 output (such as @file{ALI} files and object files) for the project's immediate
9499 sources. Note that for inherited sources (when extending a parent project) the
9500 parent project's object directory is used.
9501
9502 The object directory is given by the value of the attribute @code{Object_Dir}
9503 in the project file.
9504
9505 @smallexample
9506    for Object_Dir use "objects";
9507 @end smallexample
9508
9509 @noindent
9510 The attribute @var{Object_Dir} has a string value, the path name of the object
9511 directory. The path name may be absolute or relative to the directory of the
9512 project file. This directory must already exist, and be readable and writable.
9513
9514 By default, when the attribute @code{Object_Dir} is not given an explicit value
9515 or when its value is the empty string, the object directory is the same as the
9516 directory containing the project file.
9517
9518
9519 @node Exec Directory
9520 @subsection Exec Directory
9521
9522 @noindent
9523 The exec directory for a project is the directory containing the executables
9524 for the project's main subprograms.
9525
9526 The exec directory is given by the value of the attribute @code{Exec_Dir}
9527 in the project file.
9528
9529 @smallexample
9530    for Exec_Dir use "executables";
9531 @end smallexample
9532
9533 @noindent
9534 The attribute @var{Exec_Dir} has a string value, the path name of the exec
9535 directory. The path name may be absolute or relative to the directory of the
9536 project file. This directory must already exist, and be writable.
9537
9538 By default, when the attribute @code{Exec_Dir} is not given an explicit value
9539 or when its value is the empty string, the exec directory is the same as the
9540 object directory of the project file.
9541
9542
9543 @node Source Directories
9544 @subsection Source Directories
9545
9546 @noindent
9547 The source directories of a project are specified by the project file
9548 attribute @code{Source_Dirs}.
9549
9550 This attribute's value is a string list. If the attribute is not given an
9551 explicit value, then there is only one source directory, the one where the
9552 project file resides.
9553
9554 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
9555 as in
9556
9557 @smallexample
9558     for Source_Dirs use ();
9559 @end smallexample
9560
9561 @noindent
9562 indicates that the project contains no source files.
9563
9564 Otherwise, each string in the string list designates one or more
9565 source directories.
9566
9567 @smallexample
9568    for Source_Dirs use ("sources", "test/drivers");
9569 @end smallexample
9570
9571 @noindent
9572 If a string in the list ends with @code{"/**"},  then the directory whose path
9573 name precedes the two asterisks, as well as all its subdirectories
9574 (recursively), are source directories.
9575
9576 @smallexample
9577    for Source_Dirs use ("/system/sources/**");
9578 @end smallexample
9579
9580 @noindent
9581 Here the directory @code{/system/sources} and all of its subdirectories
9582 (recursively) are source directories.
9583
9584 To specify that the source directories are the directory of the project file
9585 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
9586 @smallexample
9587    for Source_Dirs use ("./**");
9588 @end smallexample
9589
9590 @noindent
9591 Each of the source directories must exist and be readable.
9592
9593
9594 @node Source File Names
9595 @subsection Source File Names
9596
9597 @noindent
9598 In a project that contains source files, their names may be specified by the
9599 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
9600 (a string). Source file names never include any directory information.
9601
9602 If the attribute @code{Source_Files} is given an explicit value, then each
9603 element of the list is a source file name.
9604
9605 @smallexample
9606    for Source_Files use ("main.adb");
9607    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
9608 @end smallexample
9609
9610 @noindent
9611 If the attribute @code{Source_Files} is not given an explicit value,
9612 but the attribute @code{Source_List_File} is given a string value,
9613 then the source file names are contained in the text file whose path name
9614 (absolute or relative to the directory of the project file) is the
9615 value of the attribute @code{Source_List_File}.
9616
9617 Each line in the file that is not empty or is not a comment
9618 contains a source file name. A comment line starts with two hyphens.
9619
9620 @smallexample
9621    for Source_List_File use "source_list.txt";
9622 @end smallexample
9623
9624 @noindent
9625 By default, if neither the attribute @code{Source_Files} nor the attribute
9626 @code{Source_List_File} is given an explicit value, then each file in the
9627 source directories that conforms to the project's naming scheme
9628 (see @ref{Naming Schemes}) is an immediate source of the project.
9629
9630 A warning is issued if both attributes @code{Source_Files} and
9631 @code{Source_List_File} are given explicit values. In this case, the attribute
9632 @code{Source_Files} prevails.
9633
9634 Each source file name must be the name of one and only one existing source file
9635 in one of the source directories.
9636
9637 A @code{Source_Files} attribute defined with an empty list as its value
9638 indicates that there are no source files in the project.
9639
9640 Except for projects that are clearly specified as containing no Ada source
9641 files (@code{Source_Dirs} or @code{Source_Files} specified as an empty list,
9642 or @code{Languages} specified without @code{"Ada"} in the list)
9643 @smallexample
9644    for Source_Dirs use ();
9645    for Source_Files use ();
9646    for Languages use ("C", "C++");
9647 @end smallexample
9648
9649 @noindent
9650 a project must contain at least one immediate source.
9651
9652 Projects with no source files are useful as template packages
9653 (see @ref{Packages in Project Files}) for other projects; in particular to
9654 define a package @code{Naming} (see @ref{Naming Schemes}).
9655
9656
9657 @c ****************************
9658 @c * Importing Projects *
9659 @c ****************************
9660
9661 @node  Importing Projects
9662 @section Importing Projects
9663
9664 @noindent
9665 An immediate source of a project P may depend on source files that
9666 are neither immediate sources of P nor in the predefined library.
9667 To get this effect, P must @emph{import} the projects that contain the needed
9668 source files.
9669
9670 @smallexample
9671 @group
9672   with "project1", "utilities.gpr";
9673   with "/namings/apex.gpr";
9674   project Main is
9675     ...
9676 @end group
9677 @end smallexample
9678
9679 @noindent
9680 As can be seen in this example, the syntax for importing projects is similar
9681 to the syntax for importing compilation units in Ada. However, project files
9682 use literal strings instead of names, and the @code{with} clause identifies
9683 project files rather than packages.
9684
9685 Each literal string is the file name or path name (absolute or relative) of a
9686 project file. If a string is simply a file name, with no path, then its
9687 location is determined by the @emph{project path}:
9688
9689 @itemize @bullet
9690 @item
9691 If the environment variable @env{ADA_PROJECT_PATH} exists, then the project
9692 path includes all the directories in this environment variable, plus the
9693 directory of the project file.
9694
9695 @item
9696 If the environment variable @env{ADA_PROJECT_PATH} does not exist,
9697 then the project path contains only one directory, namely the one where
9698 the project file is located.
9699 @end itemize
9700
9701 @noindent
9702 If a relative pathname is used as in
9703
9704 @smallexample
9705   with "tests/proj";
9706 @end smallexample
9707
9708 @noindent
9709 then the path is relative to the directory where the importing project file is
9710 located. Any symbolic link will be fully resolved in the directory
9711 of the importing project file before the imported project file is looked up.
9712
9713 When the @code{with}'ed project file name does not have an extension,
9714 the default is @file{.gpr}. If a file with this extension is not found, then
9715 the file name as specified in the @code{with} clause (no extension) will be
9716 used. In the above example, if a file @code{project1.gpr} is found, then it
9717 will be used; otherwise, if a file @code{project1} exists then it will be used;
9718 if neither file exists, this is an error.
9719
9720 A warning is issued if the name of the project file does not match the
9721 name of the project; this check is case insensitive.
9722
9723 Any source file that is an immediate source of the imported project can be
9724 used by the immediate sources of the importing project, and recursively. Thus
9725 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
9726 sources of @code{A} may depend on the immediate sources of @code{C}, even if
9727 @code{A} does not import @code{C} explicitly. However, this is not recommended,
9728 because if and when @code{B} ceases to import @code{C}, some sources in
9729 @code{A} will no longer compile.
9730
9731 A side effect of this capability is that cyclic dependences are not permitted:
9732 if @code{A} imports @code{B} (directly or indirectly) then @code{B} is not
9733 allowed to import @code{A}.
9734
9735
9736 @c *********************
9737 @c * Project Extension *
9738 @c *********************
9739
9740 @node Project Extension
9741 @section Project Extension
9742
9743 @noindent
9744 During development of a large system, it is sometimes necessary to use
9745 modified versions of some of the source files without changing the original
9746 sources. This can be achieved through a facility known as
9747 @emph{project extension}.
9748
9749 @smallexample
9750    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
9751 @end smallexample
9752
9753 @noindent
9754 The project file for the project being extended (the @emph{parent}) is
9755 identified by the literal string that follows the reserved word @code{extends},
9756 which itself follows the name of the extending project (the @emph{child}).
9757
9758 By default, a child project inherits all the sources of its parent.
9759 However, inherited sources can be overridden: a unit with the same name as one
9760 in the parent will hide the original unit.
9761 Inherited sources are considered to be sources (but not immediate sources)
9762 of the child project; see @ref{Project File Syntax}.
9763
9764 An inherited source file retains any switches specified in the parent project.
9765
9766 For example if the project @code{Utilities} contains the specification and the
9767 body of an Ada package @code{Util_IO}, then the project
9768 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
9769 The original body of @code{Util_IO} will not be considered in program builds.
9770 However, the package specification will still be found in the project
9771 @code{Utilities}.
9772
9773 A child project can have only one parent but it may import any number of other
9774 projects.
9775
9776 A project is not allowed to import directly or indirectly at the same time a
9777 child project and any of its ancestors.
9778
9779
9780 @c ****************************************
9781 @c * External References in Project Files *
9782 @c ****************************************
9783
9784 @node  External References in Project Files
9785 @section External References in Project Files
9786
9787 @noindent
9788 A project file may contain references to external variables; such references
9789 are called @emph{external references}.
9790
9791 An external variable is either defined as part of the environment (an
9792 environment variable in Unix, for example) or else specified on the command
9793 line via the @option{-X@emph{vbl}=@emph{value}} switch. If both, then the
9794 command line value is used.
9795
9796 An external reference is denoted by the built-in function
9797 @code{external}, which returns a string value.  This function has two forms:
9798 @itemize @bullet
9799 @item @code{external (external_variable_name)}
9800 @item @code{external (external_variable_name, default_value)}
9801 @end itemize
9802
9803 @noindent
9804 Each parameter must be a string literal.  For example:
9805
9806 @smallexample
9807    external ("USER")
9808    external ("OS", "Linux")
9809 @end smallexample
9810
9811 @noindent
9812 In the form with one parameter, the function returns the value of
9813 the external variable given as parameter. If this name is not present in the
9814 environment, then the returned value is an empty string.
9815
9816 In the form with two string parameters, the second parameter is
9817 the value returned when the variable given as the first parameter is not
9818 present in the environment. In the example above, if @code{"OS"} is not
9819 the name of an environment variable and is not passed on the command line,
9820 then the returned value will be @code{"Linux"}.
9821
9822 An external reference may be part of a string expression or of a string
9823 list expression, to define variables or attributes.
9824
9825 @smallexample
9826 @group
9827    type Mode_Type is ("Debug", "Release");
9828    Mode : Mode_Type := external ("MODE");
9829    case Mode is
9830      when "Debug" =>
9831         ...
9832 @end group
9833 @end smallexample
9834
9835
9836 @c *****************************
9837 @c * Packages in Project Files *
9838 @c *****************************
9839
9840 @node  Packages in Project Files
9841 @section Packages in Project Files
9842
9843 @noindent
9844 The @emph{package} is the project file feature that defines the settings for
9845 project-aware tools.
9846 For each such tool you can declare a corresponding package; the names for these
9847 packages are preset (see @ref{Packages}) but are not case sensitive.
9848 A package may contain variable declarations, attribute declarations, and case
9849 constructions.
9850
9851 @smallexample
9852 @group
9853    project Proj is
9854       package Builder is  -- used by gnatmake
9855          for Default_Switches ("Ada") use ("-v", "-g");
9856       end Builder;
9857    end Proj;
9858 @end group
9859 @end smallexample
9860
9861 @noindent
9862 A package declaration starts with the reserved word @code{package},
9863 followed by the package name (case insensitive), followed by the reserved word
9864 @code{is}. It ends with the reserved word @code{end}, followed by the package
9865 name, finally followed by a semi-colon.
9866
9867 Most of the packages have an attribute @code{Default_Switches}.
9868 This attribute is an associative array, and its value is a string list.
9869 The index of the associative array is the name of a programming language (case
9870 insensitive). This attribute indicates the switch or switches to be used
9871 with the corresponding tool.
9872
9873 Some packages also have another attribute, @code{Switches}, an associative
9874 array whose value is a string list. The index is the name of a source file.
9875 This attribute indicates the switch or switches to be used by the corresponding
9876 tool when dealing with this specific file.
9877
9878 Further information on these switch-related attributes is found in
9879 @ref{Switches and Project Files}.
9880
9881 A package may be declared as a @emph{renaming} of another package; e.g., from
9882 the project file for an imported project.
9883
9884 @smallexample
9885 @group
9886   with "/global/apex.gpr";
9887   project Example is
9888     package Naming renames Apex.Naming;
9889     ...
9890   end Example;
9891 @end group
9892 @end smallexample
9893
9894 @noindent
9895 Packages that are renamed in other project files often come from project files
9896 that have no sources: they are just used as templates. Any modification in the
9897 template will be reflected automatically in all the project files that rename
9898 a package from the template.
9899
9900 In addition to the tool-oriented packages, you can also declare a package
9901 named @code{Naming} to establish specialized source file naming conventions
9902 (see @ref{Naming Schemes}).
9903
9904
9905 @c ************************************
9906 @c * Variables from Imported Projects *
9907 @c ************************************
9908
9909 @node Variables from Imported Projects
9910 @section Variables from Imported Projects
9911
9912 @noindent
9913 An attribute or variable defined in an imported or parent project can
9914 be used in expressions in the importing / extending project.
9915 Such an attribute or variable is prefixed with the name of the project
9916 and (if relevant) the name of package where it is defined.
9917
9918 @smallexample
9919 @group
9920   with "imported";
9921   project Main extends "base" is
9922      Var1 := Imported.Var;
9923      Var2 := Base.Var & ".new";
9924 @end group
9925
9926 @group
9927      package Builder is
9928         for Default_Switches ("Ada") use Imported.Builder.Ada_Switches &
9929                          "-gnatg" & "-v";
9930      end Builder;
9931 @end group
9932
9933 @group
9934      package Compiler is
9935         for Default_Switches ("Ada") use Base.Compiler.Ada_Switches;
9936      end Compiler;
9937   end Main;
9938 @end group
9939 @end smallexample
9940
9941 @noindent
9942 In this example:
9943
9944 @itemize @bullet
9945 @item
9946 @code{Var1} is a copy of the variable @code{Var} defined in the project file
9947 @file{"imported.gpr"}
9948 @item
9949 the value of @code{Var2} is a copy of the value of variable @code{Var}
9950 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
9951 @item
9952 attribute @code{Default_Switches ("Ada")} in package @code{Builder}
9953 is a string list that includes in its value a copy of variable
9954 @code{Ada_Switches} defined in the @code{Builder} package in project file
9955 @file{imported.gpr} plus two new elements: @option{"-gnatg"} and @option{"-v"};
9956 @item
9957 attribute @code{Default_Switches ("Ada")} in package @code{Compiler}
9958 is a copy of the variable @code{Ada_Switches} defined in the @code{Compiler}
9959 package in project file @file{base.gpr}, the project being extended.
9960 @end itemize
9961
9962
9963 @c ******************
9964 @c * Naming Schemes *
9965 @c ******************
9966
9967 @node  Naming Schemes
9968 @section Naming Schemes
9969
9970 @noindent
9971 Sometimes an Ada software system is ported from a foreign compilation
9972 environment to GNAT, with file names that do not use the default GNAT
9973 conventions. Instead of changing all the file names (which for a variety of
9974 reasons might not be possible), you can define the relevant file naming scheme
9975 in the @code{Naming} package in your project file.  For example, the following
9976 package models the Apex file naming rules:
9977
9978 @smallexample
9979 @group
9980   package Naming is
9981     for Casing                        use "lowercase";
9982     for Dot_Replacement               use ".";
9983     for Specification_Suffix ("Ada")  use ".1.ada";
9984     for Implementation_Suffix ("Ada") use ".2.ada";
9985   end Naming;
9986 @end group
9987 @end smallexample
9988
9989 @noindent
9990 You can define the following attributes in package @code{Naming}:
9991
9992 @table @code
9993
9994 @item @var{Casing}
9995 This must be a string with one of the three values @code{"lowercase"},
9996 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
9997
9998 @noindent
9999 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
10000
10001 @item @var{Dot_Replacement}
10002 This must be a string whose value satisfies the following conditions:
10003
10004 @itemize @bullet
10005 @item It must not be empty
10006 @item It cannot start or end with an alphanumeric character
10007 @item It cannot be a single underscore
10008 @item It cannot start with an underscore followed by an alphanumeric
10009 @item It cannot contain a dot @code{'.'} except if it the entire string is @code{"."}
10010 @end itemize
10011
10012 @noindent
10013 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
10014
10015 @item @var{Specification_Suffix}
10016 This is an associative array (indexed by the programming language name, case
10017 insensitive) whose value is a string that must satisfy the following
10018 conditions:
10019
10020 @itemize @bullet
10021 @item It must not be empty
10022 @item It cannot start with an alphanumeric character
10023 @item It cannot start with an underscore followed by an alphanumeric character
10024 @end itemize
10025 @noindent
10026 If @code{Specification_Suffix ("Ada")} is not specified, then the default is
10027 @code{".ads"}.
10028
10029 @item @var{Implementation_Suffix}
10030 This is an associative array (indexed by the programming language name, case
10031 insensitive) whose value is a string that must satisfy the following
10032 conditions:
10033
10034 @itemize @bullet
10035 @item It must not be empty
10036 @item It cannot start with an alphanumeric character
10037 @item It cannot start with an underscore followed by an alphanumeric character
10038 @item It cannot be a suffix of @code{Specification_Suffix}
10039 @end itemize
10040 @noindent
10041 If @code{Implementation_Suffix ("Ada")} is not specified, then the default is
10042 @code{".adb"}.
10043
10044 @item @var{Separate_Suffix}
10045 This must be a string whose value satisfies the same conditions as
10046 @code{Implementation_Suffix}.
10047
10048 @noindent
10049 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
10050 value as @code{Implementation_Suffix ("Ada")}.
10051
10052 @item @var{Specification}
10053 @noindent
10054 You can use the @code{Specification} attribute, an associative array, to define
10055 the source file name for an individual Ada compilation unit's spec. The array
10056 index must be a string literal that identifies the Ada unit (case insensitive).
10057 The value of this attribute must be a string that identifies the file that
10058 contains this unit's spec (case sensitive or insensitive depending on the
10059 operating system).
10060
10061 @smallexample
10062    for Specification ("MyPack.MyChild") use "mypack.mychild.spec";
10063 @end smallexample
10064
10065 @item @var{Implementation}
10066
10067 You can use the @code{Implementation} attribute, an associative array, to
10068 define the source file name for an individual Ada compilation unit's body
10069 (possibly a subunit).  The array index must be a string literal that identifies
10070 the Ada unit (case insensitive).  The value of this attribute must be a string
10071 that identifies the file that contains this unit's body or subunit (case
10072 sensitive or insensitive depending on the operating system).
10073
10074 @smallexample
10075    for Implementation ("MyPack.MyChild") use "mypack.mychild.body";
10076 @end smallexample
10077 @end table
10078
10079
10080 @c ********************
10081 @c * Library Projects *
10082 @c ********************
10083
10084 @node Library Projects
10085 @section Library Projects
10086
10087 @noindent
10088 @emph{Library projects} are projects whose object code is placed in a library.
10089 (Note that this facility is not yet supported on all platforms)
10090
10091 To create a library project, you need to define in its project file
10092 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
10093 Additionally, you may define the library-related attributes
10094 @code{Library_Kind}, @code{Library_Version} and @code{Library_Elaboration}.
10095
10096 The @code{Library_Name} attribute has a string value that must start with a
10097 letter and include only letters and digits.
10098
10099 The @code{Library_Dir} attribute has a string value that designates the path
10100 (absolute or relative) of the directory where the library will reside.
10101 It must designate an existing directory, and this directory needs to be
10102 different from the project's object directory. It also needs to be writable.
10103
10104 If both @code{Library_Name} and @code{Library_Dir} are specified and
10105 are legal, then the project file defines a library project.  The optional
10106 library-related attributes are checked only for such project files.
10107
10108 The @code{Library_Kind} attribute has a string value that must be one of the
10109 following (case insensitive): @code{"static"}, @code{"dynamic"} or
10110 @code{"relocatable"}. If this attribute is not specified, the library is a
10111 static library. Otherwise, the library may be dynamic or relocatable.
10112 Depending on the operating system, there may or may not be a distinction
10113 between dynamic and relocatable libraries. For example, on Unix there is no
10114 such distinction.
10115
10116 The @code{Library_Version} attribute has a string value whose interpretation
10117 is platform dependent. On Unix, it is used only for dynamic/relocatable
10118 libraries as the internal name of the library (the @code{"soname"}). If the
10119 library file name (built from the @code{Library_Name}) is different from the
10120 @code{Library_Version}, then the library file will be a symbolic link to the
10121 actual file whose name will be @code{Library_Version}.
10122
10123 Example (on Unix):
10124
10125 @smallexample
10126 @group
10127 project Plib is
10128
10129    Version := "1";
10130
10131    for Library_Dir use "lib_dir";
10132    for Library_Name use "dummy";
10133    for Library_Kind use "relocatable";
10134    for Library_Version use "libdummy.so." & Version;
10135
10136 end Plib;
10137 @end group
10138 @end smallexample
10139
10140 @noindent
10141 Directory @file{lib_dir} will contain the internal library file whose name
10142 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
10143 @file{libdummy.so.1}.
10144
10145 When @command{gnatmake} detects that a project file (not the main project file)
10146 is a library project file, it will check all immediate sources of the project
10147 and rebuild the library if any of the sources have been recompiled.
10148 All @file{ALI} files will also be copied from the object directory to the
10149 library directory. To build executables, @command{gnatmake} will use the
10150 library rather than the individual object files.
10151
10152
10153 @c *************************************
10154 @c * Switches Related to Project Files *
10155 @c *************************************
10156 @node Switches Related to Project Files
10157 @section Switches Related to Project Files
10158
10159 @noindent
10160 The following switches are used by GNAT tools that support project files:
10161
10162 @table @code
10163
10164 @item @option{-P@var{project}}
10165 Indicates the name of a project file. This project file will be parsed with
10166 the verbosity indicated by @option{-vP@emph{x}}, if any, and using the external
10167 references indicated by @option{-X} switches, if any.
10168
10169 @noindent
10170 There must be only one @option{-P} switch on the command line.
10171
10172 @noindent
10173 Since the Project Manager parses the project file only after all the switches
10174 on the command line are checked, the order of the switches @option{-P},
10175 @option{-Vp@emph{x}} or @option{-X} is not significant.
10176
10177 @item @option{-X@var{name=value}}
10178 Indicates that external variable @var{name} has the value @var{value}.
10179 The Project Manager will use this value for occurrences of
10180 @code{external(name)} when parsing the project file.
10181
10182 @noindent
10183 If @var{name} or @var{value} includes a space, then @var{name=value} should be
10184 put between quotes.
10185 @smallexample
10186   -XOS=NT
10187   -X"user=John Doe"
10188 @end smallexample
10189
10190 @noindent
10191 Several @option{-X} switches can be used simultaneously.
10192 If several @option{-X} switches specify the same @var{name}, only the last one
10193 is used.
10194
10195 @noindent
10196 An external variable specified with a @option{-X} switch takes precedence
10197 over the value of the same name in the environment.
10198
10199 @item @option{-vP@emph{x}}
10200 Indicates the verbosity of the parsing of GNAT project files.
10201 @option{-vP0} means Default (no output for syntactically correct project
10202 files);
10203 @option{-vP1} means Medium;
10204 @option{-vP2} means High.
10205 @noindent
10206 The default is Default.
10207 @noindent
10208 If several @option{-vP@emph{x}} switches are present, only the last one is
10209 used.
10210
10211 @end table
10212
10213
10214 @c **********************************
10215 @c * Tools Supporting Project Files *
10216 @c **********************************
10217
10218 @node  Tools Supporting Project Files
10219 @section Tools Supporting Project Files
10220
10221 @menu
10222 * gnatmake and Project Files::
10223 * The GNAT Driver and Project Files::
10224 * Glide and Project Files::
10225 @end menu
10226
10227 @node gnatmake and Project Files
10228 @subsection gnatmake and Project Files
10229
10230 @noindent
10231 This section covers two topics related to @command{gnatmake} and project files:
10232 defining switches for @command{gnatmake} and for the tools that it invokes;
10233 and the use of the @code{Main} attribute.
10234
10235 @menu
10236 * Switches and Project Files::
10237 * Project Files and Main Subprograms::
10238 @end menu
10239
10240 @node Switches and Project Files
10241 @subsubsection Switches and Project Files
10242
10243 @noindent
10244 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
10245 @code{Linker}, you can specify a @code{Default_Switches} attribute, a
10246 @code{Switches} attribute, or both; as their names imply, these switch-related
10247 attributes affect which switches are used for which files when
10248 @command{gnatmake} is invoked.  As will be explained below, these
10249 package-contributed switches precede the switches passed on the
10250 @command{gnatmake} command line.
10251
10252 The @code{Default_Switches} attribute is an associative array indexed by
10253 language name (case insensitive) and returning a string list.  For example:
10254
10255 @smallexample
10256 @group
10257 package Compiler is
10258   for Default_Switches ("Ada") use ("-gnaty", "-v");
10259 end Compiler;
10260 @end group
10261 @end smallexample
10262
10263 @noindent
10264 The @code{Switches} attribute is also an associative array, indexed by a file
10265 name (which may or may not be case sensitive, depending on the operating
10266 system) and returning a string list.  For example:
10267
10268 @smallexample
10269 @group
10270 package Builder is
10271    for Switches ("main1.adb") use ("-O2");
10272    for Switches ("main2.adb") use ("-g");
10273 end Builder;
10274 @end group
10275 @end smallexample
10276
10277 @noindent
10278 For the @code{Builder} package, the file names should designate source files
10279 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
10280 file names should designate @file{ALI} or source files for main subprograms.
10281 In each case just the file name (without explicit extension) is acceptable.
10282
10283 For each tool used in a program build (@command{gnatmake}, the compiler, the
10284 binder, and the linker), its corresponding package @dfn{contributes} a set of
10285 switches for each file on which the tool is invoked, based on the
10286 switch-related attributes defined in the package. In particular, the switches
10287 that each of these packages contributes for a given file @var{f} comprise:
10288
10289 @itemize @bullet
10290 @item
10291 the value of attribute @code{Switches (@var{f})}, if it is specified in the
10292 package for the given file,
10293 @item
10294 otherwise, the value of @code{Default_Switches ("Ada")}, if it is specified in
10295 the package.
10296 @end itemize
10297
10298 @noindent
10299 If neither of these attributes is defined in the package, then the package does
10300 not contribute any switches for the given file.
10301
10302 When @command{gnatmake} is invoked on a file, the switches comprise two sets,
10303 in the following order: those contributed for the file by the @code{Builder}
10304 package; and the switches passed on the command line.
10305
10306 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
10307 the switches passed to the tool comprise three sets, in the following order:
10308
10309 @enumerate
10310 @item
10311 the applicable switches contributed for the file by the @code{Builder} package
10312 in the project file supplied on the command line;
10313
10314 @item
10315 those contributed for the file by the package (in the relevant project file --
10316 see below) corresponding to the tool; and
10317
10318 @item
10319 the applicable switches passed on the command line.
10320 @end enumerate
10321
10322 @noindent
10323 The term @emph{applicable switches} reflects the fact that @command{gnatmake}
10324 switches may or may not be passed to individual tools, depending on the
10325 individual switch.
10326
10327 @command{gnatmake} may invoke the compiler on source files from different
10328 projects. The Project Manager will use the appropriate project file to
10329 determine the @code{Compiler} package for each source file being compiled.
10330 Likewise for the @code{Binder} and @code{Linker} packages.
10331
10332 As an example, consider the following package in a project file:
10333
10334 @smallexample
10335 @group
10336 project Proj1 is
10337    package Compiler is
10338       for Default_Switches ("Ada") use ("-g");
10339       for Switches ("a.adb") use ("-O1");
10340       for Switches ("b.adb") use ("-O2", "-gnaty");
10341    end Compiler;
10342 end Proj1;
10343 @end group
10344 @end smallexample
10345
10346 @noindent
10347 If @command{gnatmake} is invoked with this project file, and it needs to
10348 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
10349 @file{a.adb} will be compiled with the switch @option{-O1}, @file{b.adb}
10350 with switches @option{-O2} and @option{-gnaty}, and @file{c.adb} with
10351 @option{-g}.
10352
10353 Another example illustrates the ordering of the switches contributed by
10354 different packages:
10355
10356 @smallexample
10357 @group
10358 project Proj2 is
10359    package Builder is
10360       for Switches ("main.adb") use ("-g", "-O1", "-f");
10361    end Builder;
10362 @end group
10363
10364 @group
10365    package Compiler is
10366       for Switches ("main.adb") use ("-O2");
10367    end Compiler;
10368 end Proj2;
10369 @end group
10370 @end smallexample
10371
10372 @noindent
10373 If you issue the command:
10374
10375 @smallexample
10376     gnatmake -PProj2 -O0 main
10377 @end smallexample
10378
10379 @noindent
10380 then the compiler will be invoked on @file{main.adb} with the following sequence of switches
10381
10382 @smallexample
10383    -g -O1 -O2 -O0
10384 @end smallexample
10385
10386 with the last @option{-O} switch having precedence over the earlier ones;
10387 several other switches (such as @option{-c}) are added implicitly.
10388
10389 The switches @option{-g} and @option{-O1} are contributed by package
10390 @code{Builder},  @option{-O2} is contributed by the package @code{Compiler}
10391 and @option{-O0} comes from the command line.
10392
10393 The @option{-g} switch will also be passed in the invocation of
10394 @command{gnatlink.}
10395
10396 A final example illustrates switch contributions from packages in different
10397 project files:
10398
10399 @smallexample
10400 @group
10401 project Proj3 is
10402    for Source_Files use ("pack.ads", "pack.adb");
10403    package Compiler is
10404       for Default_Switches ("Ada") use ("-gnata");
10405    end Compiler;
10406 end Proj3;
10407 @end group
10408
10409 @group
10410 with "Proj3";
10411 project Proj4 is
10412    for Source_Files use ("foo_main.adb", "bar_main.adb");
10413    package Builder is
10414       for Switches ("foo_main.adb") use ("-s", "-g");
10415    end Builder;
10416 end Proj4;
10417 @end group
10418
10419 @group
10420 -- Ada source file:
10421 with Pack;
10422 procedure Foo_Main is
10423    ...
10424 end Foo_Main;
10425 @end group
10426 @end smallexample
10427
10428 If the command is
10429 @smallexample
10430 gnatmake -PProj4 foo_main.adb -cargs -gnato
10431 @end smallexample
10432
10433 @noindent
10434 then the switches passed to the compiler for @file{foo_main.adb} are
10435 @option{-g} (contributed by the package @code{Proj4.Builder}) and
10436 @option{-gnato} (passed on the command line).
10437 When the imported package @code{Pack} is compiled, the switches used are
10438 @option{-g} from @code{Proj4.Builder}, @option{-gnata} (contributed from
10439 package @code{Proj3.Compiler}, and @option{-gnato} from the command line.
10440
10441
10442 @node Project Files and Main Subprograms
10443 @subsubsection Project Files and Main Subprograms
10444
10445 @noindent
10446 When using a project file, you can invoke @command{gnatmake}
10447 with several main subprograms, by specifying their source files on the command
10448 line.  Each of these needs to be an immediate source file of the project.
10449
10450 @smallexample
10451     gnatmake -Pprj main1 main2 main3
10452 @end smallexample
10453
10454 @noindent
10455 When using a project file, you can also invoke @command{gnatmake} without
10456 explicitly specifying any main, and the effect depends on whether you have
10457 defined the @code{Main} attribute.  This attribute has a string list value,
10458 where each element in the list is the name of a source file (the file
10459 extension is optional) containing a main subprogram.
10460
10461 If the @code{Main} attribute is defined in a project file as a non-empty
10462 string list and the switch @option{-u} is not used on the command line, then
10463 invoking @command{gnatmake} with this project file but without any main on the
10464 command line is equivalent to invoking @command{gnatmake} with all the file
10465 names in the @code{Main} attribute on the command line.
10466
10467 Example:
10468 @smallexample
10469 @group
10470    project Prj is
10471       for Main use ("main1", "main2", "main3");
10472    end Prj;
10473 @end group
10474 @end smallexample
10475
10476 @noindent
10477 With this project file, @code{"gnatmake -Pprj"} is equivalent to
10478 @code{"gnatmake -Pprj main1 main2 main3"}.
10479
10480 When the project attribute @code{Main} is not specified, or is specified
10481 as an empty string list, or when the switch @option{-u} is used on the command
10482 line, then invoking @command{gnatmake} with no main on the command line will
10483 result in all immediate sources of the project file being checked, and
10484 potentially recompiled. Depending on the presence of the switch @option{-u},
10485 sources from other project files on which the immediate sources of the main
10486 project file depend are also checked and potentially recompiled. In other
10487 words, the @option{-u} switch is applied to all of the immediate sources of themain project file.
10488
10489
10490 @node The GNAT Driver and Project Files
10491 @subsection The GNAT Driver and Project Files
10492
10493 @noindent
10494 A number of GNAT tools, other than @command{gnatmake} are project-aware:
10495 @command{gnatbind}, @command{gnatfind}, @command{gnatlink}, @command{gnatls}
10496 and @command{gnatxref}. However, none of these tools can be invoked directly
10497 with a project file switch (@code{-P}). They need to be invoke through the
10498 @command{gnat} driver.
10499
10500 The @command{gnat} driver is a front-end that accepts a number of commands and
10501 call the corresponding tool. It has been designed initially for VMS to convert
10502 VMS style qualifiers to Unix style switches, but it is now available to all
10503 the GNAT supported platforms.
10504
10505 On non VMS platforms, the @command{gnat} driver accepts the following commands
10506 (case insensitive):
10507
10508 @itemize @bullet
10509 @item
10510 BIND to invoke @command{gnatbind}
10511 @item
10512 CHOP to invoke @command{gnatchop}
10513 @item
10514 COMP or COMPILE to invoke the compiler
10515 @item
10516 ELIM to invoke @command{gnatelim}
10517 @item
10518 FIND to invoke @command{gnatfind}
10519 @item
10520 KR or KRUNCH to invoke @command{gnatkr}
10521 @item
10522 LINK to invoke @command{gnatlink}
10523 @item
10524 LS or LIST to invoke @command{gnatls}
10525 @item
10526 MAKE to invoke @command{gnatmake}
10527 @item
10528 NAME to invoke @command{gnatname}
10529 @item
10530 PREP or PREPROCESS to invoke @command{gnatprep}
10531 @item
10532 PSTA or STANDARD to invoke @command{gnatpsta}
10533 @item
10534 STUB to invoke @command{gnatstub}
10535 @item
10536 XREF to invoke @command{gnatxref}
10537 @end itemize
10538
10539 @noindent
10540 Note that the compiler is invoked using the command @command{gnatmake -f -u}.
10541
10542 @noindent
10543 Following the command, you may put switches and arguments for the invoked
10544 tool.
10545
10546 @smallexample
10547   gnat bind -C main.ali
10548   gnat ls -a main
10549   gnat chop foo.txt
10550 @end smallexample
10551
10552 @noindent
10553 In addition, for command BIND, FIND, LS or LIST, LINK and XREF, the project
10554 file related switches (@code{-P}, @code{-X} and @code{-vPx}) may be used in
10555 addition to the switches of the invoking tool.
10556
10557 @noindent
10558 For each of these command, there is possibly a package in the main project that
10559 corresponds to the invoked tool.
10560
10561 @itemize @bullet
10562 @item
10563 package @code{Binder} for command BIND (invoking @code{gnatbind})
10564
10565 @item
10566 package @code{Finder} for command FIND (invoking @code{gnatfind})
10567
10568 @item
10569 package @code{Gnatls} for command LS or LIST (invoking @code{gnatls})
10570
10571 @item
10572 package @code{Linker} for command LINK (invoking @code{gnatlink})
10573
10574 @item
10575 package @code{Cross_Reference} for command XREF (invoking @code{gnatlink})
10576
10577 @end itemize
10578
10579 @noindent
10580 Package @code{Gnatls} has a unique attribute @code{Switches}, a simple variable
10581 with a string list value. It contains switches for the invocation of
10582 @code{gnatls}.
10583
10584 @smallexample
10585 @group
10586 project Proj1 is
10587    package gnatls is
10588       for Switches use ("-a", "-v");
10589    end gnatls;
10590 end Proj1;
10591 @end group
10592 @end smallexample
10593
10594 @noindent
10595 All other packages contains a switch @code{Default_Switches}, an associative
10596 array, indexed by the programming language (case insensitive) and having a
10597 string list value. @code{Default_Switches ("Ada")} contains the switches for
10598 the invocation of the tool corresponding to the package.
10599
10600 @smallexample
10601 @group
10602 project Proj is
10603
10604    for Source_Dirs use ("./**");
10605
10606    package gnatls is
10607       for Switches use ("-a", "-v");
10608    end gnatls;
10609 @end group
10610 @group
10611
10612    package Binder is
10613       for Default_Switches ("Ada") use ("-C", "-e");
10614    end Binder;
10615 @end group
10616 @group
10617
10618    package Linker is
10619       for Default_Switches ("Ada") use ("-C");
10620    end Linker;
10621 @end group
10622 @group
10623
10624    package Finder is
10625       for Default_Switches ("Ada") use ("-a", "-f");
10626    end Finder;
10627 @end group
10628 @group
10629
10630    package Cross_Reference is
10631       for Default_Switches ("Ada") use ("-a", "-f", "-d", "-u");
10632    end Cross_Reference;
10633 end Proj;
10634 @end group
10635 @end smallexample
10636
10637 @noindent
10638 With the above project file, commands such as
10639
10640 @smallexample
10641    gnat ls -Pproj main
10642    gnat xref -Pproj main
10643    gnat bind -Pproj main.ali
10644 @end smallexample
10645
10646 @noindent
10647 will set up the environment properly and invoke the tool with the switches
10648 found in the package corresponding to the tool.
10649
10650
10651 @node Glide and Project Files
10652 @subsection Glide and Project Files
10653
10654 @noindent
10655 Glide will automatically recognize the @file{.gpr} extension for
10656 project files, and will
10657 convert them to its own internal format automatically. However, it
10658 doesn't provide a syntax-oriented editor for modifying these
10659 files.
10660 The project file will be loaded as text when you select the menu item
10661 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
10662 You can edit this text and save the @file{gpr} file;
10663 when you next select this project file in Glide it
10664 will be automatically reloaded.
10665
10666 Glide uses the @code{gnatlist} attribute in the @code{Ide} package, whose value
10667 is something like @code{powerpc-wrs-vxworks-gnatls}, to compute the
10668 cross-prefix.  From this information the correct location for the
10669 GNAT runtime, and thus also the correct cross-references, can be
10670 determined.
10671
10672
10673 @node An Extended Example
10674 @section An Extended Example
10675
10676 @noindent
10677 Suppose that we have two programs, @var{prog1} and @var{prog2}, with the sources
10678 in the respective directories. We would like to build them with a single
10679 @command{gnatmake} command, and we would like to place their object files into
10680 @file{.build} subdirectories of the source directories. Furthermore, we would
10681 like to have to have two separate subdirectories in @file{.build}  --
10682 @file{release} and @file{debug} -- which will contain the object files compiled with
10683 different set of compilation flags.
10684
10685 In other words, we have the following structure:
10686
10687 @smallexample
10688 @group
10689    main
10690      |- prog1
10691      |    |- .build
10692      |         | debug
10693      |         | release
10694      |- prog2
10695           |- .build
10696                | debug
10697                | release
10698 @end group
10699 @end smallexample
10700
10701 @noindent
10702 Here are the project files that we need to create in a directory @file{main}
10703 to maintain this structure:
10704
10705 @enumerate
10706
10707 @item We create a @code{Common} project with a package @code{Compiler} that
10708 specifies the compilation switches:
10709
10710 @smallexample
10711 File "common.gpr":
10712 @group
10713 @b{project} Common @b{is}
10714
10715    @b{for} Source_Dirs @b{use} (); -- No source files
10716 @end group
10717
10718 @group
10719    @b{type} Build_Type @b{is} ("release", "debug");
10720    Build : Build_Type := External ("BUILD", "debug");
10721 @end group
10722 @group
10723    @b{package} Compiler @b{is}
10724       @b{case} Build @b{is}
10725          @b{when} "release" =>
10726            @b{for} Default_Switches ("Ada") @b{use} ("-O2");
10727          @b{when} "debug"   =>
10728            @b{for} Default_Switches ("Ada") @b{use} ("-g");
10729       @b{end case};
10730    @b{end} Compiler;
10731
10732 @b{end} Common;
10733 @end group
10734 @end smallexample
10735
10736 @item We create separate projects for the two programs:
10737
10738 @smallexample
10739 @group
10740 File "prog1.gpr":
10741
10742 @b{with} "common";
10743 @b{project} Prog1 @b{is}
10744
10745     @b{for} Source_Dirs @b{use} ("prog1");
10746     @b{for} Object_Dir  @b{use} "prog1/.build/" & Common.Build;
10747
10748     @b{package} Compiler @b{renames} Common.Compiler;
10749
10750 @b{end} Prog1;
10751 @end group
10752 @end smallexample
10753
10754 @smallexample
10755 @group
10756 File "prog2.gpr":
10757
10758 @b{with} "common";
10759 @b{project} Prog2 @b{is}
10760
10761     @b{for} Source_Dirs @b{use} ("prog2");
10762     @b{for} Object_Dir  @b{use} "prog2/.build/" & Common.Build;
10763
10764     @b{package} Compiler @b{renames} Common.Compiler;
10765
10766 @end group
10767 @b{end} Prog2;
10768 @end smallexample
10769
10770 @item We create a wrapping project @var{Main}:
10771
10772 @smallexample
10773 @group
10774 File "main.gpr":
10775
10776 @b{with} "common";
10777 @b{with} "prog1";
10778 @b{with} "prog2";
10779 @b{project} Main @b{is}
10780
10781    @b{package} Compiler @b{renames} Common.Compiler;
10782
10783 @b{end} Main;
10784 @end group
10785 @end smallexample
10786
10787 @item Finally we need to create a dummy procedure that @code{with}s (either
10788 explicitly or implicitly) all the sources of our two programs.
10789
10790 @end enumerate
10791
10792 @noindent
10793 Now we can build the programs using the command
10794
10795 @smallexample
10796    gnatmake -Pmain dummy
10797 @end smallexample
10798
10799 @noindent
10800 for the Debug mode, or
10801
10802 @smallexample
10803    gnatmake -Pmain -XBUILD=release
10804 @end smallexample
10805
10806 @noindent
10807 for the Release mode.
10808
10809
10810 @c ********************************
10811 @c * Project File Complete Syntax *
10812 @c ********************************
10813
10814 @node Project File Complete Syntax
10815 @section Project File Complete Syntax
10816
10817 @smallexample
10818 project ::=
10819   context_clause project_declaration
10820
10821 context_clause ::=
10822   @{with_clause@}
10823
10824 with_clause ::=
10825   @b{with} literal_string @{ , literal_string @} ;
10826
10827 project_declaration ::=
10828   @b{project} <project_>simple_name [ @b{extends} literal_string ] @b{is}
10829     @{declarative_item@}
10830   @b{end} <project_>simple_name;
10831
10832 declarative_item ::=
10833   package_declaration |
10834   typed_string_declaration |
10835   other_declarative_item
10836
10837 package_declaration ::=
10838   @b{package} <package_>simple_name package_completion
10839
10840 package_completion ::=
10841   package_body | package_renaming
10842
10843 package body ::=
10844   @b{is}
10845     @{other_declarative_item@}
10846   @b{end} <package_>simple_name ;
10847
10848 package_renaming ::==
10849   @b{renames} <project_>simple_name.<package_>simple_name ;
10850
10851 typed_string_declaration ::=
10852   @b{type} <typed_string_>_simple_name @b{is}
10853    ( literal_string @{, literal_string@} );
10854
10855 other_declarative_item ::=
10856   attribute_declaration |
10857   typed_variable_declaration |
10858   variable_declaration |
10859   case_construction
10860
10861 attribute_declaration ::=
10862   @b{for} attribute @b{use} expression ;
10863
10864 attribute ::=
10865   <simple_attribute_>simple_name |
10866   <associative_array_attribute_>simple_name ( literal_string )
10867
10868 typed_variable_declaration ::=
10869   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
10870
10871 variable_declaration ::=
10872   <variable_>simple_name := expression;
10873
10874 expression ::=
10875   term @{& term@}
10876
10877 term ::=
10878   literal_string |
10879   string_list |
10880   <variable_>name |
10881   external_value |
10882   attribute_reference
10883
10884 literal_string ::=
10885   (same as Ada)
10886
10887 string_list ::=
10888   ( <string_>expression @{ , <string_>expression @} )
10889
10890 external_value ::=
10891   @b{external} ( literal_string [, literal_string] )
10892
10893 attribute_reference ::=
10894   attribute_parent ' <simple_attribute_>simple_name [ ( literal_string ) ]
10895
10896 attribute_parent ::=
10897   @b{project} |
10898   <project_or_package>simple_name |
10899   <project_>simple_name . <package_>simple_name
10900
10901 case_construction ::=
10902   @b{case} <typed_variable_>name @b{is}
10903     @{case_item@}
10904   @b{end case} ;
10905
10906 case_item ::=
10907   @b{when} discrete_choice_list => @{case_construction | attribute_declaration@}
10908
10909 discrete_choice_list ::=
10910   literal_string @{| literal_string@}
10911
10912 name ::=
10913   simple_name @{. simple_name@}
10914
10915 simple_name ::=
10916   identifier (same as Ada)
10917
10918 @end smallexample
10919
10920
10921 @node Elaboration Order Handling in GNAT
10922 @chapter Elaboration Order Handling in GNAT
10923 @cindex Order of elaboration
10924 @cindex Elaboration control
10925
10926 @menu
10927 * Elaboration Code in Ada 95::
10928 * Checking the Elaboration Order in Ada 95::
10929 * Controlling the Elaboration Order in Ada 95::
10930 * Controlling Elaboration in GNAT - Internal Calls::
10931 * Controlling Elaboration in GNAT - External Calls::
10932 * Default Behavior in GNAT - Ensuring Safety::
10933 * Elaboration Issues for Library Tasks::
10934 * Mixing Elaboration Models::
10935 * What to Do If the Default Elaboration Behavior Fails::
10936 * Elaboration for Access-to-Subprogram Values::
10937 * Summary of Procedures for Elaboration Control::
10938 * Other Elaboration Order Considerations::
10939 @end menu
10940
10941 @noindent
10942 This chapter describes the handling of elaboration code in Ada 95 and
10943 in GNAT, and discusses how the order of elaboration of program units can
10944 be controlled in GNAT, either automatically or with explicit programming
10945 features.
10946
10947 @node Elaboration Code in Ada 95
10948 @section Elaboration Code in Ada 95
10949
10950 @noindent
10951 Ada 95 provides rather general mechanisms for executing code at elaboration
10952 time, that is to say before the main program starts executing. Such code arises
10953 in three contexts:
10954
10955 @table @asis
10956 @item Initializers for variables.
10957 Variables declared at the library level, in package specs or bodies, can
10958 require initialization that is performed at elaboration time, as in:
10959 @smallexample
10960 @cartouche
10961 Sqrt_Half : Float := Sqrt (0.5);
10962 @end cartouche
10963 @end smallexample
10964
10965 @item Package initialization code
10966 Code in a @code{BEGIN-END} section at the outer level of a package body is
10967 executed as part of the package body elaboration code.
10968
10969 @item Library level task allocators
10970 Tasks that are declared using task allocators at the library level
10971 start executing immediately and hence can execute at elaboration time.
10972 @end table
10973
10974 @noindent
10975 Subprogram calls are possible in any of these contexts, which means that
10976 any arbitrary part of the program may be executed as part of the elaboration
10977 code. It is even possible to write a program which does all its work at
10978 elaboration time, with a null main program, although stylistically this
10979 would usually be considered an inappropriate way to structure
10980 a program.
10981
10982 An important concern arises in the context of elaboration code:
10983 we have to be sure that it is executed in an appropriate order. What we
10984 have is a series of elaboration code sections, potentially one section
10985 for each unit in the program. It is important that these execute
10986 in the correct order. Correctness here means that, taking the above
10987 example of the declaration of @code{Sqrt_Half},
10988 if some other piece of
10989 elaboration code references @code{Sqrt_Half},
10990 then it must run after the
10991 section of elaboration code that contains the declaration of
10992 @code{Sqrt_Half}.
10993
10994 There would never be any order of elaboration problem if we made a rule
10995 that whenever you @code{with} a unit, you must elaborate both the spec and body
10996 of that unit before elaborating the unit doing the @code{with}'ing:
10997
10998 @smallexample
10999 @group
11000 @cartouche
11001 @b{with} Unit_1;
11002 @b{package} Unit_2 @b{is} ...
11003 @end cartouche
11004 @end group
11005 @end smallexample
11006
11007 @noindent
11008 would require that both the body and spec of @code{Unit_1} be elaborated
11009 before the spec of @code{Unit_2}. However, a rule like that would be far too
11010 restrictive. In particular, it would make it impossible to have routines
11011 in separate packages that were mutually recursive.
11012
11013 You might think that a clever enough compiler could look at the actual
11014 elaboration code and determine an appropriate correct order of elaboration,
11015 but in the general case, this is not possible. Consider the following
11016 example.
11017
11018 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
11019 that references
11020 the variable @code{Sqrt_1}, which is declared in the elaboration code
11021 of the body of @code{Unit_1}:
11022
11023 @smallexample
11024 @cartouche
11025 Sqrt_1 : Float := Sqrt (0.1);
11026 @end cartouche
11027 @end smallexample
11028
11029 @noindent
11030 The elaboration code of the body of @code{Unit_1} also contains:
11031
11032 @smallexample
11033 @group
11034 @cartouche
11035 @b{if} expression_1 = 1 @b{then}
11036    Q := Unit_2.Func_2;
11037 @b{end if};
11038 @end cartouche
11039 @end group
11040 @end smallexample
11041
11042 @noindent
11043 @code{Unit_2} is exactly parallel,
11044 it has a procedure @code{Func_2} that references
11045 the variable @code{Sqrt_2}, which is declared in the elaboration code of
11046 the body @code{Unit_2}:
11047
11048 @smallexample
11049 @cartouche
11050 Sqrt_2 : Float := Sqrt (0.1);
11051 @end cartouche
11052 @end smallexample
11053
11054 @noindent
11055 The elaboration code of the body of @code{Unit_2} also contains:
11056
11057 @smallexample
11058 @group
11059 @cartouche
11060 @b{if} expression_2 = 2 @b{then}
11061    Q := Unit_1.Func_1;
11062 @b{end if};
11063 @end cartouche
11064 @end group
11065 @end smallexample
11066
11067 @noindent
11068 Now the question is, which of the following orders of elaboration is
11069 acceptable:
11070
11071 @smallexample
11072 @group
11073 Spec of Unit_1
11074 Spec of Unit_2
11075 Body of Unit_1
11076 Body of Unit_2
11077 @end group
11078 @end smallexample
11079
11080 @noindent
11081 or
11082
11083 @smallexample
11084 @group
11085 Spec of Unit_2
11086 Spec of Unit_1
11087 Body of Unit_2
11088 Body of Unit_1
11089 @end group
11090 @end smallexample
11091
11092 @noindent
11093 If you carefully analyze the flow here, you will see that you cannot tell
11094 at compile time the answer to this question.
11095 If @code{expression_1} is not equal to 1,
11096 and @code{expression_2} is not equal to 2,
11097 then either order is acceptable, because neither of the function calls is
11098 executed. If both tests evaluate to true, then neither order is acceptable
11099 and in fact there is no correct order.
11100
11101 If one of the two expressions is true, and the other is false, then one
11102 of the above orders is correct, and the other is incorrect. For example,
11103 if @code{expression_1} = 1 and @code{expression_2} /= 2,
11104 then the call to @code{Func_2}
11105 will occur, but not the call to @code{Func_1.}
11106 This means that it is essential
11107 to elaborate the body of @code{Unit_1} before
11108 the body of @code{Unit_2}, so the first
11109 order of elaboration is correct and the second is wrong.
11110
11111 By making @code{expression_1} and @code{expression_2}
11112 depend on input data, or perhaps
11113 the time of day, we can make it impossible for the compiler or binder
11114 to figure out which of these expressions will be true, and hence it
11115 is impossible to guarantee a safe order of elaboration at run time.
11116
11117 @node Checking the Elaboration Order in Ada 95
11118 @section Checking the Elaboration Order in Ada 95
11119
11120 @noindent
11121 In some languages that involve the same kind of elaboration problems,
11122 e.g. Java and C++, the programmer is expected to worry about these
11123 ordering problems himself, and it is common to
11124 write a program in which an incorrect elaboration order  gives
11125 surprising results, because it references variables before they
11126 are initialized.
11127 Ada 95 is designed to be a safe language, and a programmer-beware approach is
11128 clearly not sufficient. Consequently, the language provides three lines
11129 of defense:
11130
11131 @table @asis
11132 @item Standard rules
11133 Some standard rules restrict the possible choice of elaboration
11134 order. In particular, if you @code{with} a unit, then its spec is always
11135 elaborated before the unit doing the @code{with}. Similarly, a parent
11136 spec is always elaborated before the child spec, and finally
11137 a spec is always elaborated before its corresponding body.
11138
11139 @item Dynamic elaboration checks
11140 @cindex Elaboration checks
11141 @cindex Checks, elaboration
11142 Dynamic checks are made at run time, so that if some entity is accessed
11143 before it is elaborated (typically  by means of a subprogram call)
11144 then the exception (@code{Program_Error}) is raised.
11145
11146 @item Elaboration control
11147 Facilities are provided for the programmer to specify the desired order
11148 of elaboration.
11149 @end table
11150
11151 Let's look at these facilities in more detail. First, the rules for
11152 dynamic checking. One possible rule would be simply to say that the
11153 exception is raised if you access a variable which has not yet been
11154 elaborated. The trouble with this approach is that it could require
11155 expensive checks on every variable reference. Instead Ada 95 has two
11156 rules which are a little more restrictive, but easier to check, and
11157 easier to state:
11158
11159 @table @asis
11160 @item Restrictions on calls
11161 A subprogram can only be called at elaboration time if its body
11162 has been elaborated. The rules for elaboration given above guarantee
11163 that the spec of the subprogram has been elaborated before the
11164 call, but not the body. If this rule is violated, then the
11165 exception @code{Program_Error} is raised.
11166
11167 @item Restrictions on instantiations
11168 A generic unit can only be instantiated if the body of the generic
11169 unit has been elaborated. Again, the rules for elaboration given above
11170 guarantee that the spec of the generic unit has been elaborated
11171 before the instantiation, but not the body. If this rule is
11172 violated, then the exception @code{Program_Error} is raised.
11173 @end table
11174
11175 @noindent
11176 The idea is that if the body has been elaborated, then any variables
11177 it references must have been elaborated; by checking for the body being
11178 elaborated we guarantee that none of its references causes any
11179 trouble. As we noted above, this is a little too restrictive, because a
11180 subprogram that has no non-local references in its body may in fact be safe
11181 to call. However, it really would be unsafe to rely on this, because
11182 it would mean that the caller was aware of details of the implementation
11183 in the body. This goes against the basic tenets of Ada.
11184
11185 A plausible implementation can be described as follows.
11186 A Boolean variable is associated with each subprogram
11187 and each generic unit. This variable is initialized to False, and is set to
11188 True at the point body is elaborated. Every call or instantiation checks the
11189 variable, and raises @code{Program_Error} if the variable is False.
11190
11191 Note that one might think that it would be good enough to have one Boolean
11192 variable for each package, but that would not deal with cases of trying
11193 to call a body in the same package as the call
11194 that has not been elaborated yet.
11195 Of course a compiler may be able to do enough analysis to optimize away
11196 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
11197 does such optimizations, but still the easiest conceptual model is to
11198 think of there being one variable per subprogram.
11199
11200 @node Controlling the Elaboration Order in Ada 95
11201 @section Controlling the Elaboration Order in Ada 95
11202
11203 @noindent
11204 In the previous section we discussed the rules in Ada 95 which ensure
11205 that @code{Program_Error} is raised if an incorrect elaboration order is
11206 chosen. This prevents erroneous executions, but we need mechanisms to
11207 specify a correct execution and avoid the exception altogether.
11208 To achieve this, Ada 95 provides a number of features for controlling
11209 the order of elaboration. We discuss these features in this section.
11210
11211 First, there are several ways of indicating to the compiler that a given
11212 unit has no elaboration problems:
11213
11214 @table @asis
11215 @item packages that do not require a body
11216 In Ada 95, a library package that does not require a body does not permit
11217 a body. This means that if we have a such a package, as in:
11218
11219 @smallexample
11220 @group
11221 @cartouche
11222 @b{package} Definitions @b{is}
11223    @b{generic}
11224       @b{type} m @b{is new} integer;
11225    @b{package} Subp @b{is}
11226       @b{type} a @b{is array} (1 .. 10) @b{of} m;
11227       @b{type} b @b{is array} (1 .. 20) @b{of} m;
11228    @b{end} Subp;
11229 @b{end} Definitions;
11230 @end cartouche
11231 @end group
11232 @end smallexample
11233
11234 @noindent
11235 A package that @code{with}'s @code{Definitions} may safely instantiate
11236 @code{Definitions.Subp} because the compiler can determine that there
11237 definitely is no package body to worry about in this case
11238
11239 @item pragma Pure
11240 @cindex pragma Pure
11241 @findex Pure
11242 Places sufficient restrictions on a unit to guarantee that
11243 no call to any subprogram in the unit can result in an
11244 elaboration problem. This means that the compiler does not need
11245 to worry about the point of elaboration of such units, and in
11246 particular, does not need to check any calls to any subprograms
11247 in this unit.
11248
11249 @item pragma Preelaborate
11250 @findex Preelaborate
11251 @cindex pragma Preelaborate
11252 This pragma places slightly less stringent restrictions on a unit than
11253 does pragma Pure,
11254 but these restrictions are still sufficient to ensure that there
11255 are no elaboration problems with any calls to the unit.
11256
11257 @item pragma Elaborate_Body
11258 @findex Elaborate_Body
11259 @cindex pragma Elaborate_Body
11260 This pragma requires that the body of a unit be elaborated immediately
11261 after its spec. Suppose a unit @code{A} has such a pragma,
11262 and unit @code{B} does
11263 a @code{with} of unit @code{A}. Recall that the standard rules require
11264 the spec of unit @code{A}
11265 to be elaborated before the @code{with}'ing unit; given the pragma in
11266 @code{A}, we also know that the body of @code{A}
11267 will be elaborated before @code{B}, so
11268 that calls to @code{A} are safe and do not need a check.
11269 @end table
11270
11271 @noindent
11272 Note that,
11273 unlike pragma @code{Pure} and pragma @code{Preelaborate},
11274 the use of
11275 @code{Elaborate_Body} does not guarantee that the program is
11276 free of elaboration problems, because it may not be possible
11277 to satisfy the requested elaboration order.
11278 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
11279 If a programmer
11280 marks @code{Unit_1} as @code{Elaborate_Body},
11281 and not @code{Unit_2,} then the order of
11282 elaboration will be:
11283
11284 @smallexample
11285 @group
11286 Spec of Unit_2
11287 Spec of Unit_1
11288 Body of Unit_1
11289 Body of Unit_2
11290 @end group
11291 @end smallexample
11292
11293 @noindent
11294 Now that means that the call to @code{Func_1} in @code{Unit_2}
11295 need not be checked,
11296 it must be safe. But the call to @code{Func_2} in
11297 @code{Unit_1} may still fail if
11298 @code{Expression_1} is equal to 1,
11299 and the programmer must still take
11300 responsibility for this not being the case.
11301
11302 If all units carry a pragma @code{Elaborate_Body}, then all problems are
11303 eliminated, except for calls entirely within a body, which are
11304 in any case fully under programmer control. However, using the pragma
11305 everywhere is not always possible.
11306 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
11307 we marked both of them as having pragma @code{Elaborate_Body}, then
11308 clearly there would be no possible elaboration order.
11309
11310 The above pragmas allow a server to guarantee safe use by clients, and
11311 clearly this is the preferable approach. Consequently a good rule in
11312 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
11313 and if this is not possible,
11314 mark them as @code{Elaborate_Body} if possible.
11315 As we have seen, there are situations where neither of these
11316 three pragmas can be used.
11317 So we also provide methods for clients to control the
11318 order of elaboration of the servers on which they depend:
11319
11320 @table @asis
11321 @item pragma Elaborate (unit)
11322 @findex Elaborate
11323 @cindex pragma Elaborate
11324 This pragma is placed in the context clause, after a @code{with} clause,
11325 and it requires that the body of the named unit be elaborated before
11326 the unit in which the pragma occurs. The idea is to use this pragma
11327 if the current unit calls at elaboration time, directly or indirectly,
11328 some subprogram in the named unit.
11329
11330 @item pragma Elaborate_All (unit)
11331 @findex Elaborate_All
11332 @cindex pragma Elaborate_All
11333 This is a stronger version of the Elaborate pragma. Consider the
11334 following example:
11335
11336 @smallexample
11337 Unit A @code{with}'s unit B and calls B.Func in elab code
11338 Unit B @code{with}'s unit C, and B.Func calls C.Func
11339 @end smallexample
11340
11341 @noindent
11342 Now if we put a pragma @code{Elaborate (B)}
11343 in unit @code{A}, this ensures that the
11344 body of @code{B} is elaborated before the call, but not the
11345 body of @code{C}, so
11346 the call to @code{C.Func} could still cause @code{Program_Error} to
11347 be raised.
11348
11349 The effect of a pragma @code{Elaborate_All} is stronger, it requires
11350 not only that the body of the named unit be elaborated before the
11351 unit doing the @code{with}, but also the bodies of all units that the
11352 named unit uses, following @code{with} links transitively. For example,
11353 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
11354 then it requires
11355 not only that the body of @code{B} be elaborated before @code{A},
11356 but also the
11357 body of @code{C}, because @code{B} @code{with}'s @code{C}.
11358 @end table
11359
11360 @noindent
11361 We are now in a position to give a usage rule in Ada 95 for avoiding
11362 elaboration problems, at least if dynamic dispatching and access to
11363 subprogram values are not used. We will handle these cases separately
11364 later.
11365
11366 The rule is simple. If a unit has elaboration code that can directly or
11367 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
11368 a generic unit in a @code{with}'ed unit,
11369 then if the @code{with}'ed unit does not have
11370 pragma @code{Pure} or @code{Preelaborate}, then the client should have
11371 a pragma @code{Elaborate_All}
11372 for the @code{with}'ed unit. By following this rule a client is
11373 assured that calls can be made without risk of an exception.
11374 If this rule is not followed, then a program may be in one of four
11375 states:
11376
11377 @table @asis
11378 @item No order exists
11379 No order of elaboration exists which follows the rules, taking into
11380 account any @code{Elaborate}, @code{Elaborate_All},
11381 or @code{Elaborate_Body} pragmas. In
11382 this case, an Ada 95 compiler must diagnose the situation at bind
11383 time, and refuse to build an executable program.
11384
11385 @item One or more orders exist, all incorrect
11386 One or more acceptable elaboration orders exists, and all of them
11387 generate an elaboration order problem. In this case, the binder
11388 can build an executable program, but @code{Program_Error} will be raised
11389 when the program is run.
11390
11391 @item Several orders exist, some right, some incorrect
11392 One or more acceptable elaboration orders exists, and some of them
11393 work, and some do not. The programmer has not controlled
11394 the order of elaboration, so the binder may or may not pick one of
11395 the correct orders, and the program may or may not raise an
11396 exception when it is run. This is the worst case, because it means
11397 that the program may fail when moved to another compiler, or even
11398 another version of the same compiler.
11399
11400 @item One or more orders exists, all correct
11401 One ore more acceptable elaboration orders exist, and all of them
11402 work. In this case the program runs successfully. This state of
11403 affairs can be guaranteed by following the rule we gave above, but
11404 may be true even if the rule is not followed.
11405 @end table
11406
11407 @noindent
11408 Note that one additional advantage of following our Elaborate_All rule
11409 is that the program continues to stay in the ideal (all orders OK) state
11410 even if maintenance
11411 changes some bodies of some subprograms. Conversely, if a program that does
11412 not follow this rule happens to be safe at some point, this state of affairs
11413 may deteriorate silently as a result of maintenance changes.
11414
11415 You may have noticed that the above discussion did not mention
11416 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
11417 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
11418 code in the body makes calls to some other unit, so it is still necessary
11419 to use @code{Elaborate_All} on such units.
11420
11421 @node Controlling Elaboration in GNAT - Internal Calls
11422 @section Controlling Elaboration in GNAT - Internal Calls
11423
11424 @noindent
11425 In the case of internal calls, i.e. calls within a single package, the
11426 programmer has full control over the order of elaboration, and it is up
11427 to the programmer to elaborate declarations in an appropriate order. For
11428 example writing:
11429
11430 @smallexample
11431 @group
11432 @cartouche
11433 @b{function} One @b{return} Float;
11434
11435 Q : Float := One;
11436
11437 @b{function} One @b{return} Float @b{is}
11438 @b{begin}
11439      return 1.0;
11440 @b{end} One;
11441 @end cartouche
11442 @end group
11443 @end smallexample
11444
11445 @noindent
11446 will obviously raise @code{Program_Error} at run time, because function
11447 One will be called before its body is elaborated. In this case GNAT will
11448 generate a warning that the call will raise @code{Program_Error}:
11449
11450 @smallexample
11451 @group
11452 @cartouche
11453  1. procedure y is
11454  2.    function One return Float;
11455  3.
11456  4.    Q : Float := One;
11457                     |
11458     >>> warning: cannot call "One" before body is elaborated
11459     >>> warning: Program_Error will be raised at run time
11460
11461  5.
11462  6.    function One return Float is
11463  7.    begin
11464  8.         return 1.0;
11465  9.    end One;
11466 10.
11467 11. begin
11468 12.    null;
11469 13. end;
11470 @end cartouche
11471 @end group
11472 @end smallexample
11473
11474 @noindent
11475 Note that in this particular case, it is likely that the call is safe, because
11476 the function @code{One} does not access any global variables.
11477 Nevertheless in Ada 95, we do not want the validity of the check to depend on
11478 the contents of the body (think about the separate compilation case), so this
11479 is still wrong, as we discussed in the previous sections.
11480
11481 The error is easily corrected by rearranging the declarations so that the
11482 body of One appears before the declaration containing the call
11483 (note that in Ada 95,
11484 declarations can appear in any order, so there is no restriction that
11485 would prevent this reordering, and if we write:
11486
11487 @smallexample
11488 @group
11489 @cartouche
11490 @b{function} One @b{return} Float;
11491
11492 @b{function} One @b{return} Float @b{is}
11493 @b{begin}
11494      return 1.0;
11495 @b{end} One;
11496
11497 Q : Float := One;
11498 @end cartouche
11499 @end group
11500 @end smallexample
11501
11502 @noindent
11503 then all is well, no warning is generated, and no
11504 @code{Program_Error} exception
11505 will be raised.
11506 Things are more complicated when a chain of subprograms is executed:
11507
11508 @smallexample
11509 @group
11510 @cartouche
11511 @b{function} A @b{return} Integer;
11512 @b{function} B @b{return} Integer;
11513 @b{function} C @b{return} Integer;
11514
11515 @b{function} B @b{return} Integer @b{is begin return} A; @b{end};
11516 @b{function} C @b{return} Integer @b{is begin return} B; @b{end};
11517
11518 X : Integer := C;
11519
11520 @b{function} A @b{return} Integer @b{is begin return} 1; @b{end};
11521 @end cartouche
11522 @end group
11523 @end smallexample
11524
11525 @noindent
11526 Now the call to @code{C}
11527 at elaboration time in the declaration of @code{X} is correct, because
11528 the body of @code{C} is already elaborated,
11529 and the call to @code{B} within the body of
11530 @code{C} is correct, but the call
11531 to @code{A} within the body of @code{B} is incorrect, because the body
11532 of @code{A} has not been elaborated, so @code{Program_Error}
11533 will be raised on the call to @code{A}.
11534 In this case GNAT will generate a
11535 warning that @code{Program_Error} may be
11536 raised at the point of the call. Let's look at the warning:
11537
11538 @smallexample
11539 @group
11540 @cartouche
11541  1. procedure x is
11542  2.    function A return Integer;
11543  3.    function B return Integer;
11544  4.    function C return Integer;
11545  5.
11546  6.    function B return Integer is begin return A; end;
11547                                                     |
11548     >>> warning: call to "A" before body is elaborated may
11549                  raise Program_Error
11550     >>> warning: "B" called at line 7
11551     >>> warning: "C" called at line 9
11552
11553  7.    function C return Integer is begin return B; end;
11554  8.
11555  9.    X : Integer := C;
11556 10.
11557 11.    function A return Integer is begin return 1; end;
11558 12.
11559 13. begin
11560 14.    null;
11561 15. end;
11562 @end cartouche
11563 @end group
11564 @end smallexample
11565
11566 @noindent
11567 Note that the message here says "may raise", instead of the direct case,
11568 where the message says "will be raised". That's because whether
11569 @code{A} is
11570 actually called depends in general on run-time flow of control.
11571 For example, if the body of @code{B} said
11572
11573 @smallexample
11574 @group
11575 @cartouche
11576 @b{function} B @b{return} Integer @b{is}
11577 @b{begin}
11578    @b{if} some-condition-depending-on-input-data @b{then}
11579       @b{return} A;
11580    @b{else}
11581       @b{return} 1;
11582    @b{end if};
11583 @b{end} B;
11584 @end cartouche
11585 @end group
11586 @end smallexample
11587
11588 @noindent
11589 then we could not know until run time whether the incorrect call to A would
11590 actually occur, so @code{Program_Error} might
11591 or might not be raised. It is possible for a compiler to
11592 do a better job of analyzing bodies, to
11593 determine whether or not @code{Program_Error}
11594 might be raised, but it certainly
11595 couldn't do a perfect job (that would require solving the halting problem
11596 and is provably impossible), and because this is a warning anyway, it does
11597 not seem worth the effort to do the analysis. Cases in which it
11598 would be relevant are rare.
11599
11600 In practice, warnings of either of the forms given
11601 above will usually correspond to
11602 real errors, and should be examined carefully and eliminated.
11603 In the rare case where a warning is bogus, it can be suppressed by any of
11604 the following methods:
11605
11606 @itemize @bullet
11607 @item
11608 Compile with the @option{-gnatws} switch set
11609
11610 @item
11611 Suppress @code{Elaboration_Checks} for the called subprogram
11612
11613 @item
11614 Use pragma @code{Warnings_Off} to turn warnings off for the call
11615 @end itemize
11616
11617 @noindent
11618 For the internal elaboration check case,
11619 GNAT by default generates the
11620 necessary run-time checks to ensure
11621 that @code{Program_Error} is raised if any
11622 call fails an elaboration check. Of course this can only happen if a
11623 warning has been issued as described above. The use of pragma
11624 @code{Suppress (Elaboration_Checks)} may (but is not guaranteed to) suppress
11625 some of these checks, meaning that it may be possible (but is not
11626 guaranteed) for a program to be able to call a subprogram whose body
11627 is not yet elaborated, without raising a @code{Program_Error} exception.
11628
11629 @node Controlling Elaboration in GNAT - External Calls
11630 @section Controlling Elaboration in GNAT - External Calls
11631
11632 @noindent
11633 The previous section discussed the case in which the execution of a
11634 particular thread of elaboration code occurred entirely within a
11635 single unit. This is the easy case to handle, because a programmer
11636 has direct and total control over the order of elaboration, and
11637 furthermore, checks need only be generated in cases which are rare
11638 and which the compiler can easily detect.
11639 The situation is more complex when separate compilation is taken into account.
11640 Consider the following:
11641
11642 @smallexample
11643 @cartouche
11644 @group
11645 @b{package} Math @b{is}
11646    @b{function} Sqrt (Arg : Float) @b{return} Float;
11647 @b{end} Math;
11648
11649 @b{package body} Math @b{is}
11650    @b{function} Sqrt (Arg : Float) @b{return} Float @b{is}
11651    @b{begin}
11652          ...
11653    @b{end} Sqrt;
11654 @b{end} Math;
11655 @end group
11656 @group
11657 @b{with} Math;
11658 @b{package} Stuff @b{is}
11659    X : Float := Math.Sqrt (0.5);
11660 @b{end} Stuff;
11661
11662 @b{with} Stuff;
11663 @b{procedure} Main @b{is}
11664 @b{begin}
11665    ...
11666 @b{end} Main;
11667 @end group
11668 @end cartouche
11669 @end smallexample
11670
11671 @noindent
11672 where @code{Main} is the main program. When this program is executed, the
11673 elaboration code must first be executed, and one of the jobs of the
11674 binder is to determine the order in which the units of a program are
11675 to be elaborated. In this case we have four units: the spec and body
11676 of @code{Math},
11677 the spec of @code{Stuff} and the body of @code{Main}).
11678 In what order should the four separate sections of elaboration code
11679 be executed?
11680
11681 There are some restrictions in the order of elaboration that the binder
11682 can choose. In particular, if unit U has a @code{with}
11683 for a package @code{X}, then you
11684 are assured that the spec of @code{X}
11685 is elaborated before U , but you are
11686 not assured that the body of @code{X}
11687 is elaborated before U.
11688 This means that in the above case, the binder is allowed to choose the
11689 order:
11690
11691 @smallexample
11692 spec of Math
11693 spec of Stuff
11694 body of Math
11695 body of Main
11696 @end smallexample
11697
11698 @noindent
11699 but that's not good, because now the call to @code{Math.Sqrt}
11700 that happens during
11701 the elaboration of the @code{Stuff}
11702 spec happens before the body of @code{Math.Sqrt} is
11703 elaborated, and hence causes @code{Program_Error} exception to be raised.
11704 At first glance, one might say that the binder is misbehaving, because
11705 obviously you want to elaborate the body of something you @code{with}
11706 first, but
11707 that is not a general rule that can be followed in all cases. Consider
11708
11709 @smallexample
11710 @group
11711 @cartouche
11712 @b{package} X @b{is} ...
11713
11714 @b{package} Y @b{is} ...
11715
11716 @b{with} X;
11717 @b{package body} Y @b{is} ...
11718
11719 @b{with} Y;
11720 @b{package body} X @b{is} ...
11721 @end cartouche
11722 @end group
11723 @end smallexample
11724
11725 @noindent
11726 This is a common arrangement, and, apart from the order of elaboration
11727 problems that might arise in connection with elaboration code, this works fine.
11728 A rule that says that you must first elaborate the body of anything you
11729 @code{with} cannot work in this case:
11730 the body of @code{X} @code{with}'s @code{Y},
11731 which means you would have to
11732 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
11733 which means
11734 you have to elaborate the body of @code{X} first, but ... and we have a
11735 loop that cannot be broken.
11736
11737 It is true that the binder can in many cases guess an order of elaboration
11738 that is unlikely to cause a @code{Program_Error}
11739 exception to be raised, and it tries to do so (in the
11740 above example of @code{Math/Stuff/Spec}, the GNAT binder will
11741 by default
11742 elaborate the body of @code{Math} right after its spec, so all will be well).
11743
11744 However, a program that blindly relies on the binder to be helpful can
11745 get into trouble, as we discussed in the previous sections, so
11746 GNAT
11747 provides a number of facilities for assisting the programmer in
11748 developing programs that are robust with respect to elaboration order.
11749
11750 @node Default Behavior in GNAT - Ensuring Safety
11751 @section Default Behavior in GNAT - Ensuring Safety
11752
11753 @noindent
11754 The default behavior in GNAT ensures elaboration safety. In its
11755 default mode GNAT implements the
11756 rule we previously described as the right approach. Let's restate it:
11757
11758 @itemize
11759 @item
11760 @emph{If a unit has elaboration code that can directly or indirectly make a
11761 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
11762 in a @code{with}'ed unit, then if the @code{with}'ed unit
11763 does not have pragma @code{Pure} or
11764 @code{Preelaborate}, then the client should have an
11765 @code{Elaborate_All} for the @code{with}'ed unit.}
11766 @end itemize
11767
11768 @noindent
11769 By following this rule a client
11770 is assured that calls and instantiations can be made without risk of an exception.
11771
11772 In this mode GNAT traces all calls that are potentially made from
11773 elaboration code, and puts in any missing implicit @code{Elaborate_All}
11774 pragmas.
11775 The advantage of this approach is that no elaboration problems
11776 are possible if the binder can find an elaboration order that is
11777 consistent with these implicit @code{Elaborate_All} pragmas. The
11778 disadvantage of this approach is that no such order may exist.
11779
11780 If the binder does not generate any diagnostics, then it means that it
11781 has found an elaboration order that is guaranteed to be safe. However,
11782 the binder may still be relying on implicitly generated
11783 @code{Elaborate_All} pragmas so portability to other compilers than
11784 GNAT is not guaranteed.
11785
11786 If it is important to guarantee portability, then the compilations should
11787 use the
11788 @option{-gnatwl}
11789 (warn on elaboration problems) switch. This will cause warning messages
11790 to be generated indicating the missing @code{Elaborate_All} pragmas.
11791 Consider the following source program:
11792
11793 @smallexample
11794 @group
11795 @cartouche
11796 @b{with} k;
11797 @b{package} j @b{is}
11798   m : integer := k.r;
11799 @b{end};
11800 @end cartouche
11801 @end group
11802 @end smallexample
11803
11804 @noindent
11805 where it is clear that there
11806 should be a pragma @code{Elaborate_All}
11807 for unit @code{k}. An implicit pragma will be generated, and it is
11808 likely that the binder will be able to honor it. However,
11809 it is safer to include the pragma explicitly in the source. If this
11810 unit is compiled with the
11811 @option{-gnatwl}
11812 switch, then the compiler outputs a warning:
11813
11814 @smallexample
11815 @group
11816 @cartouche
11817 1. with k;
11818 2. package j is
11819 3.   m : integer := k.r;
11820                      |
11821    >>> warning: call to "r" may raise Program_Error
11822    >>> warning: missing pragma Elaborate_All for "k"
11823
11824 4. end;
11825 @end cartouche
11826 @end group
11827 @end smallexample
11828
11829 @noindent
11830 and these warnings can be used as a guide for supplying manually
11831 the missing pragmas.
11832
11833 This default mode is more restrictive than the Ada Reference
11834 Manual, and it is possible to construct programs which will compile
11835 using the dynamic model described there, but will run into a
11836 circularity using the safer static model we have described.
11837
11838 Of course any Ada compiler must be able to operate in a mode
11839 consistent with the requirements of the Ada Reference Manual,
11840 and in particular must have the capability of implementing the
11841 standard dynamic model of elaboration with run-time checks.
11842
11843 In GNAT, this standard mode can be achieved either by the use of
11844 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
11845 command, or by the use of the configuration pragma:
11846
11847 @smallexample
11848 pragma Elaboration_Checks (RM);
11849 @end smallexample
11850
11851 @noindent
11852 Either approach will cause the unit affected to be compiled using the
11853 standard dynamic run-time elaboration checks described in the Ada
11854 Reference Manual. The static model is generally preferable, since it
11855 is clearly safer to rely on compile and link time checks rather than
11856 run-time checks. However, in the case of legacy code, it may be
11857 difficult to meet the requirements of the static model. This
11858 issue is further discussed in
11859 @ref{What to Do If the Default Elaboration Behavior Fails}.
11860
11861 Note that the static model provides a strict subset of the allowed
11862 behavior and programs of the Ada Reference Manual, so if you do
11863 adhere to the static model and no circularities exist,
11864 then you are assured that your program will
11865 work using the dynamic model.
11866
11867 @node Elaboration Issues for Library Tasks
11868 @section Elaboration Issues for Library Tasks
11869 @cindex Library tasks, elaboration issues
11870 @cindex Elaboration of library tasks
11871
11872 @noindent
11873 In this section we examine special elaboration issues that arise for
11874 programs that declare library level tasks.
11875
11876 Generally the model of execution of an Ada program is that all units are
11877 elaborated, and then execution of the program starts. However, the
11878 declaration of library tasks definitely does not fit this model. The
11879 reason for this is that library tasks start as soon as they are declared
11880 (more precisely, as soon as the statement part of the enclosing package
11881 body is reached), that is to say before elaboration
11882 of the program is complete. This means that if such a task calls a
11883 subprogram, or an entry in another task, the callee may or may not be
11884 elaborated yet, and in the standard
11885 Reference Manual model of dynamic elaboration checks, you can even
11886 get timing dependent Program_Error exceptions, since there can be
11887 a race between the elaboration code and the task code.
11888
11889 The static model of elaboration in GNAT seeks to avoid all such
11890 dynamic behavior, by being conservative, and the conservative
11891 approach in this particular case is to assume that all the code
11892 in a task body is potentially executed at elaboration time if
11893 a task is declared at the library level.
11894
11895 This can definitely result in unexpected circularities. Consider
11896 the following example
11897
11898 @smallexample
11899 package Decls is
11900   task Lib_Task is
11901      entry Start;
11902   end Lib_Task;
11903
11904   type My_Int is new Integer;
11905
11906   function Ident (M : My_Int) return My_Int;
11907 end Decls;
11908
11909 with Utils;
11910 package body Decls is
11911   task body Lib_Task is
11912   begin
11913      accept Start;
11914      Utils.Put_Val (2);
11915   end Lib_Task;
11916
11917   function Ident (M : My_Int) return My_Int is
11918   begin
11919      return M;
11920   end Ident;
11921 end Decls;
11922
11923 with Decls;
11924 package Utils is
11925   procedure Put_Val (Arg : Decls.My_Int);
11926 end Utils;
11927
11928 with Text_IO;
11929 package body Utils is
11930   procedure Put_Val (Arg : Decls.My_Int) is
11931   begin
11932      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
11933   end Put_Val;
11934 end Utils;
11935
11936 with Decls;
11937 procedure Main is
11938 begin
11939    Decls.Lib_Task.Start;
11940 end;
11941 @end smallexample
11942
11943 @noindent
11944 If the above example is compiled in the default static elaboration
11945 mode, then a circularity occurs. The circularity comes from the call
11946 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
11947 this call occurs in elaboration code, we need an implicit pragma
11948 @code{Elaborate_All} for @code{Utils}. This means that not only must
11949 the spec and body of @code{Utils} be elaborated before the body
11950 of @code{Decls}, but also the spec and body of any unit that is
11951 @code{with'ed} by the body of @code{Utils} must also be elaborated before
11952 the body of @code{Decls}. This is the transitive implication of
11953 pragma @code{Elaborate_All} and it makes sense, because in general
11954 the body of @code{Put_Val} might have a call to something in a
11955 @code{with'ed} unit.
11956
11957 In this case, the body of Utils (actually its spec) @code{with's}
11958 @code{Decls}. Unfortunately this means that the body of @code{Decls}
11959 must be elaborated before itself, in case there is a call from the
11960 body of @code{Utils}.
11961
11962 Here is the exact chain of events we are worrying about:
11963
11964 @enumerate
11965 @item
11966 In the body of @code{Decls} a call is made from within the body of a library
11967 task to a subprogram in the package @code{Utils}. Since this call may
11968 occur at elaboration time (given that the task is activated at elaboration
11969 time), we have to assume the worst, i.e. that the
11970 call does happen at elaboration time.
11971
11972 @item
11973 This means that the body and spec of @code{Util} must be elaborated before
11974 the body of @code{Decls} so that this call does not cause an access before
11975 elaboration.
11976
11977 @item
11978 Within the body of @code{Util}, specifically within the body of
11979 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
11980 by this package.
11981
11982 @item
11983 One such @code{with}'ed package is package @code{Decls}, so there
11984 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
11985 In fact there is such a call in this example, but we would have to
11986 assume that there was such a call even if it were not there, since
11987 we are not supposed to write the body of @code{Decls} knowing what
11988 is in the body of @code{Utils}; certainly in the case of the
11989 static elaboration model, the compiler does not know what is in
11990 other bodies and must assume the worst.
11991
11992 @item
11993 This means that the spec and body of @code{Decls} must also be
11994 elaborated before we elaborate the unit containing the call, but
11995 that unit is @code{Decls}! This means that the body of @code{Decls}
11996 must be elaborated before itself, and that's a circularity.
11997 @end enumerate
11998
11999 @noindent
12000 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
12001 the body of @code{Decls} you will get a true Ada Reference Manual
12002 circularity that makes the program illegal.
12003
12004 In practice, we have found that problems with the static model of
12005 elaboration in existing code often arise from library tasks, so
12006 we must address this particular situation.
12007
12008 Note that if we compile and run the program above, using the dynamic model of
12009 elaboration (that is to say use the @option{-gnatE} switch),
12010 then it compiles, binds,
12011 links, and runs, printing the expected result of 2. Therefore in some sense
12012 the circularity here is only apparent, and we need to capture
12013 the properties of this program that  distinguish it from other library-level
12014 tasks that have real elaboration problems.
12015
12016 We have four possible answers to this question:
12017
12018 @itemize @bullet
12019
12020 @item
12021 Use the dynamic model of elaboration.
12022
12023 If we use the @option{-gnatE} switch, then as noted above, the program works.
12024 Why is this? If we examine the task body, it is apparent that the task cannot
12025 proceed past the
12026 @code{accept} statement until after elaboration has been completed, because
12027 the corresponding entry call comes from the main program, not earlier.
12028 This is why the dynamic model works here. But that's really giving
12029 up on a precise analysis, and we prefer to take this approach only if we cannot
12030 solve the
12031 problem in any other manner. So let us examine two ways to reorganize
12032 the program to avoid the potential elaboration problem.
12033
12034 @item
12035 Split library tasks into separate packages.
12036
12037 Write separate packages, so that library tasks are isolated from
12038 other declarations as much as possible. Let us look at a variation on
12039 the above program.
12040
12041 @smallexample
12042 package Decls1 is
12043   task Lib_Task is
12044      entry Start;
12045   end Lib_Task;
12046 end Decls1;
12047
12048 with Utils;
12049 package body Decls1 is
12050   task body Lib_Task is
12051   begin
12052      accept Start;
12053      Utils.Put_Val (2);
12054   end Lib_Task;
12055 end Decls1;
12056
12057 package Decls2 is
12058   type My_Int is new Integer;
12059   function Ident (M : My_Int) return My_Int;
12060 end Decls2;
12061
12062 with Utils;
12063 package body Decls2 is
12064   function Ident (M : My_Int) return My_Int is
12065   begin
12066      return M;
12067   end Ident;
12068 end Decls2;
12069
12070 with Decls2;
12071 package Utils is
12072   procedure Put_Val (Arg : Decls2.My_Int);
12073 end Utils;
12074
12075 with Text_IO;
12076 package body Utils is
12077   procedure Put_Val (Arg : Decls2.My_Int) is
12078   begin
12079      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
12080   end Put_Val;
12081 end Utils;
12082
12083 with Decls1;
12084 procedure Main is
12085 begin
12086    Decls1.Lib_Task.Start;
12087 end;
12088 @end smallexample
12089
12090 @noindent
12091 All we have done is to split @code{Decls} into two packages, one
12092 containing the library task, and one containing everything else. Now
12093 there is no cycle, and the program compiles, binds, links and executes
12094 using the default static model of elaboration.
12095
12096 @item
12097 Declare separate task types.
12098
12099 A significant part of the problem arises because of the use of the
12100 single task declaration form. This means that the elaboration of
12101 the task type, and the elaboration of the task itself (i.e. the
12102 creation of the task) happen at the same time. A good rule
12103 of style in Ada 95 is to always create explicit task types. By
12104 following the additional step of placing task objects in separate
12105 packages from the task type declaration, many elaboration problems
12106 are avoided. Here is another modified example of the example program:
12107
12108 @smallexample
12109 package Decls is
12110   task type Lib_Task_Type is
12111      entry Start;
12112   end Lib_Task_Type;
12113
12114   type My_Int is new Integer;
12115
12116   function Ident (M : My_Int) return My_Int;
12117 end Decls;
12118
12119 with Utils;
12120 package body Decls is
12121   task body Lib_Task_Type is
12122   begin
12123      accept Start;
12124      Utils.Put_Val (2);
12125   end Lib_Task_Type;
12126
12127   function Ident (M : My_Int) return My_Int is
12128   begin
12129      return M;
12130   end Ident;
12131 end Decls;
12132
12133 with Decls;
12134 package Utils is
12135   procedure Put_Val (Arg : Decls.My_Int);
12136 end Utils;
12137
12138 with Text_IO;
12139 package body Utils is
12140   procedure Put_Val (Arg : Decls.My_Int) is
12141   begin
12142      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
12143   end Put_Val;
12144 end Utils;
12145
12146 with Decls;
12147 package Declst is
12148    Lib_Task : Decls.Lib_Task_Type;
12149 end Declst;
12150
12151 with Declst;
12152 procedure Main is
12153 begin
12154    Declst.Lib_Task.Start;
12155 end;
12156 @end smallexample
12157
12158 @noindent
12159 What we have done here is to replace the @code{task} declaration in
12160 package @code{Decls} with a @code{task type} declaration. Then we
12161 introduce a separate package @code{Declst} to contain the actual
12162 task object. This separates the elaboration issues for
12163 the @code{task type}
12164 declaration, which causes no trouble, from the elaboration issues
12165 of the task object, which is also unproblematic, since it is now independent
12166 of the elaboration of  @code{Utils}.
12167 This separation of concerns also corresponds to
12168 a generally sound engineering principle of separating declarations
12169 from instances. This version of the program also compiles, binds, links,
12170 and executes, generating the expected output.
12171
12172 @item
12173 Use No_Entry_Calls_In_Elaboration_Code restriction.
12174 @cindex No_Entry_Calls_In_Elaboration_Code
12175
12176 The previous two approaches described how a program can be restructured
12177 to avoid the special problems caused by library task bodies. in practice,
12178 however, such restructuring may be difficult to apply to existing legacy code,
12179 so we must consider solutions that do not require massive rewriting.
12180
12181 Let us consider more carefully why our original sample program works
12182 under the dynamic model of elaboration. The reason is that the code
12183 in the task body blocks immediately on the @code{accept}
12184 statement. Now of course there is nothing to prohibit elaboration
12185 code from making entry calls (for example from another library level task),
12186 so we cannot tell in isolation that
12187 the task will not execute the accept statement  during elaboration.
12188
12189 However, in practice it is very unusual to see elaboration code
12190 make any entry calls, and the pattern of tasks starting
12191 at elaboration time and then immediately blocking on @code{accept} or
12192 @code{select} statements is very common. What this means is that
12193 the compiler is being too pessimistic when it analyzes the
12194 whole package body as though it might be executed at elaboration
12195 time.
12196
12197 If we know that the elaboration code contains no entry calls, (a very safe
12198 assumption most of the time, that could almost be made the default
12199 behavior), then we can compile all units of the program under control
12200 of the following configuration pragma:
12201
12202 @smallexample
12203 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
12204 @end smallexample
12205
12206 @noindent
12207 This pragma can be placed in the @file{gnat.adc} file in the usual
12208 manner. If we take our original unmodified program and compile it
12209 in the presence of a @file{gnat.adc} containing the above pragma,
12210 then once again, we can compile, bind, link, and execute, obtaining
12211 the expected result. In the presence of this pragma, the compiler does
12212 not trace calls in a task body, that appear after the first @code{accept}
12213 or @code{select} statement, and therefore does not report a potential
12214 circularity in the original program.
12215
12216 The compiler will check to the extent it can that the above
12217 restriction is not violated, but it is not always possible to do a
12218 complete check at compile time, so it is important to use this
12219 pragma only if the stated restriction is in fact met, that is to say
12220 no task receives an entry call before elaboration of all units is completed.
12221
12222 @end itemize
12223
12224 @node Mixing Elaboration Models
12225 @section Mixing Elaboration Models
12226 @noindent
12227 So far, we have assumed that the entire program is either compiled
12228 using the dynamic model or static model, ensuring consistency. It
12229 is possible to mix the two models, but rules have to be followed
12230 if this mixing is done to ensure that elaboration checks are not
12231 omitted.
12232
12233 The basic rule is that @emph{a unit compiled with the static model cannot
12234 be @code{with'ed} by a unit compiled with the dynamic model}. The
12235 reason for this is that in the static model, a unit assumes that
12236 its clients guarantee to use (the equivalent of) pragma
12237 @code{Elaborate_All} so that no elaboration checks are required
12238 in inner subprograms, and this assumption is violated if the
12239 client is compiled with dynamic checks.
12240
12241 The precise rule is as follows. A unit that is compiled with dynamic
12242 checks can only @code{with} a unit that meets at least one of the
12243 following criteria:
12244
12245 @itemize @bullet
12246
12247 @item
12248 The @code{with'ed} unit is itself compiled with dynamic elaboration
12249 checks (that is with the @option{-gnatE} switch.
12250
12251 @item
12252 The @code{with'ed} unit is an internal GNAT implementation unit from
12253 the System, Interfaces, Ada, or GNAT hierarchies.
12254
12255 @item
12256 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
12257
12258 @item
12259 The @code{with'ing} unit (that is the client) has an explicit pragma
12260 @code{Elaborate_All} for the @code{with'ed} unit.
12261
12262 @end itemize
12263
12264 @noindent
12265 If this rule is violated, that is if a unit with dynamic elaboration
12266 checks @code{with's} a unit that does not meet one of the above four
12267 criteria, then the binder (@code{gnatbind}) will issue a warning
12268 similar to that in the following example:
12269
12270 @smallexample
12271 warning: "x.ads" has dynamic elaboration checks and with's
12272 warning:   "y.ads" which has static elaboration checks
12273 @end smallexample
12274
12275 @noindent
12276 These warnings indicate that the rule has been violated, and that as a result
12277 elaboration checks may be missed in the resulting executable file.
12278 This warning may be suppressed using the @code{-ws} binder switch
12279 in the usual manner.
12280
12281 One useful application of this mixing rule is in the case of a subsystem
12282 which does not itself @code{with} units from the remainder of the
12283 application. In this case, the entire subsystem can be compiled with
12284 dynamic checks to resolve a circularity in the subsystem, while
12285 allowing the main application that uses this subsystem to be compiled
12286 using the more reliable default static model.
12287
12288 @node What to Do If the Default Elaboration Behavior Fails
12289 @section What to Do If the Default Elaboration Behavior Fails
12290
12291 @noindent
12292 If the binder cannot find an acceptable order, it outputs detailed
12293 diagnostics. For example:
12294 @smallexample
12295 @group
12296 @iftex
12297 @leftskip=0cm
12298 @end iftex
12299 error: elaboration circularity detected
12300 info:   "proc (body)" must be elaborated before "pack (body)"
12301 info:     reason: Elaborate_All probably needed in unit "pack (body)"
12302 info:     recompile "pack (body)" with -gnatwl
12303 info:                             for full details
12304 info:       "proc (body)"
12305 info:         is needed by its spec:
12306 info:       "proc (spec)"
12307 info:         which is withed by:
12308 info:       "pack (body)"
12309 info:  "pack (body)" must be elaborated before "proc (body)"
12310 info:     reason: pragma Elaborate in unit "proc (body)"
12311 @end group
12312
12313 @end smallexample
12314
12315 @noindent
12316 In this case we have a cycle that the binder cannot break. On the one
12317 hand, there is an explicit pragma Elaborate in @code{proc} for
12318 @code{pack}. This means that the body of @code{pack} must be elaborated
12319 before the body of @code{proc}. On the other hand, there is elaboration
12320 code in @code{pack} that calls a subprogram in @code{proc}. This means
12321 that for maximum safety, there should really be a pragma
12322 Elaborate_All in @code{pack} for @code{proc} which would require that
12323 the body of @code{proc} be elaborated before the body of
12324 @code{pack}. Clearly both requirements cannot be satisfied.
12325 Faced with a circularity of this kind, you have three different options.
12326
12327 @table @asis
12328 @item Fix the program
12329 The most desirable option from the point of view of long-term maintenance
12330 is to rearrange the program so that the elaboration problems are avoided.
12331 One useful technique is to place the elaboration code into separate
12332 child packages. Another is to move some of the initialization code to
12333 explicitly called subprograms, where the program controls the order
12334 of initialization explicitly. Although this is the most desirable option,
12335 it may be impractical and involve too much modification, especially in
12336 the case of complex legacy code.
12337
12338 @item Perform dynamic checks
12339 If the compilations are done using the
12340 @option{-gnatE}
12341 (dynamic elaboration check) switch, then GNAT behaves in
12342 a quite different manner. Dynamic checks are generated for all calls
12343 that could possibly result in raising an exception. With this switch,
12344 the compiler does not generate implicit @code{Elaborate_All} pragmas.
12345 The behavior then is exactly as specified in the Ada 95 Reference Manual.
12346 The binder will generate an executable program that may or may not
12347 raise @code{Program_Error}, and then it is the programmer's job to ensure
12348 that it does not raise an exception. Note that it is important to
12349 compile all units with the switch, it cannot be used selectively.
12350
12351 @item Suppress checks
12352 The drawback of dynamic checks is that they generate a
12353 significant overhead at run time, both in space and time. If you
12354 are absolutely sure that your program cannot raise any elaboration
12355 exceptions, and you still want to use the dynamic elaboration model,
12356 then you can use the configuration pragma
12357 @code{Suppress (Elaboration_Checks)} to suppress all such checks. For
12358 example this pragma could be placed in the @file{gnat.adc} file.
12359
12360 @item Suppress checks selectively
12361 When you know that certain calls in elaboration code cannot possibly
12362 lead to an elaboration error, and the binder nevertheless generates warnings
12363 on those calls and inserts Elaborate_All pragmas that lead to elaboration
12364 circularities, it is possible to remove those warnings locally and obtain
12365 a program that will bind. Clearly this can be unsafe, and it is the
12366 responsibility of the programmer to make sure that the resulting program has
12367 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
12368 be used with different granularity to suppress warnings and break
12369 elaboration circularities:
12370
12371 @itemize @bullet
12372 @item
12373 Place the pragma that names the called subprogram in the declarative part
12374 that contains the call.
12375
12376 @item
12377 Place the pragma in the declarative part, without naming an entity. This
12378 disables warnings on all calls in the corresponding  declarative region.
12379
12380 @item
12381 Place the pragma in the package spec that declares the called subprogram,
12382 and name the subprogram. This disables warnings on all elaboration calls to
12383 that subprogram.
12384
12385 @item
12386 Place the pragma in the package spec that declares the called subprogram,
12387 without naming any entity. This disables warnings on all elaboration calls to
12388 all subprograms declared in this spec.
12389 @end itemize
12390
12391 @noindent
12392 These four cases are listed in order of decreasing safety, and therefore
12393 require increasing programmer care in their application. Consider the
12394 following program:
12395 @smallexample
12396
12397 package Pack1 is
12398   function F1 return Integer;
12399   X1 : Integer;
12400 end Pack1;
12401
12402 package Pack2 is
12403   function F2 return Integer;
12404   function Pure (x : integer) return integer;
12405   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
12406   --  pragma Suppress (Elaboration_Check);              -- (4)
12407 end Pack2;
12408
12409 with Pack2;
12410 package body Pack1 is
12411   function F1 return Integer is
12412   begin
12413     return 100;
12414   end F1;
12415   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
12416 begin
12417   declare
12418     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
12419     --  pragma Suppress(Elaboration_Check);             -- (2)
12420   begin
12421     X1 := Pack2.F2 + 1;                --  Elab. call (2)
12422   end;
12423 end Pack1;
12424
12425 with Pack1;
12426 package body Pack2 is
12427   function F2 return Integer is
12428   begin
12429      return Pack1.F1;
12430   end F2;
12431   function Pure (x : integer) return integer is
12432   begin
12433      return x ** 3 - 3 * x;
12434   end;
12435 end Pack2;
12436
12437 with Pack1, Ada.Text_IO;
12438 procedure Proc3 is
12439 begin
12440   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
12441 end Proc3;
12442 @end smallexample
12443 In the absence of any pragmas, an attempt to bind this program produces
12444 the following diagnostics:
12445 @smallexample
12446 @group
12447 @iftex
12448 @leftskip=.5cm
12449 @end iftex
12450 error: elaboration circularity detected
12451 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
12452 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
12453 info:       recompile "pack1 (body)" with -gnatwl for full details
12454 info:          "pack1 (body)"
12455 info:             must be elaborated along with its spec:
12456 info:          "pack1 (spec)"
12457 info:             which is withed by:
12458 info:          "pack2 (body)"
12459 info:             which must be elaborated along with its spec:
12460 info:          "pack2 (spec)"
12461 info:             which is withed by:
12462 info:          "pack1 (body)"
12463 @end group
12464 @end smallexample
12465 The sources of the circularity are the two calls to @code{Pack2.Pure} and
12466 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
12467 F2 is safe, even though F2 calls F1, because the call appears after the
12468 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
12469 remove the warning on the call. It is also possible to use pragma (2)
12470 because there are no other potentially unsafe calls in the block.
12471
12472 @noindent
12473 The call to @code{Pure} is safe because this function does not depend on the
12474 state of @code{Pack2}. Therefore any call to this function is safe, and it
12475 is correct to place pragma (3) in the corresponding package spec.
12476
12477 @noindent
12478 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
12479 warnings on all calls to functions declared therein. Note that this is not
12480 necessarily safe, and requires more detailed examination of the subprogram
12481 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
12482 be already elaborated.
12483 @end table
12484
12485 @noindent
12486 It is hard to generalize on which of these four approaches should be
12487 taken. Obviously if it is possible to fix the program so that the default
12488 treatment works, this is preferable, but this may not always be practical.
12489 It is certainly simple enough to use
12490 @option{-gnatE}
12491 but the danger in this case is that, even if the GNAT binder
12492 finds a correct elaboration order, it may not always do so,
12493 and certainly a binder from another Ada compiler might not. A
12494 combination of testing and analysis (for which the warnings generated
12495 with the
12496 @option{-gnatwl}
12497 switch can be useful) must be used to ensure that the program is free
12498 of errors. One switch that is useful in this testing is the
12499 @code{-p (pessimistic elaboration order)}
12500 switch for
12501 @code{gnatbind}.
12502 Normally the binder tries to find an order that has the best chance of
12503 of avoiding elaboration problems. With this switch, the binder
12504 plays a devil's advocate role, and tries to choose the order that
12505 has the best chance of failing. If your program works even with this
12506 switch, then it has a better chance of being error free, but this is still
12507 not a guarantee.
12508
12509 For an example of this approach in action, consider the C-tests (executable
12510 tests) from the ACVC suite. If these are compiled and run with the default
12511 treatment, then all but one of them succeed without generating any error
12512 diagnostics from the binder. However, there is one test that fails, and
12513 this is not surprising, because the whole point of this test is to ensure
12514 that the compiler can handle cases where it is impossible to determine
12515 a correct order statically, and it checks that an exception is indeed
12516 raised at run time.
12517
12518 This one test must be compiled and run using the
12519 @option{-gnatE}
12520 switch, and then it passes. Alternatively, the entire suite can
12521 be run using this switch. It is never wrong to run with the dynamic
12522 elaboration switch if your code is correct, and we assume that the
12523 C-tests are indeed correct (it is less efficient, but efficiency is
12524 not a factor in running the ACVC tests.)
12525
12526 @node Elaboration for Access-to-Subprogram Values
12527 @section Elaboration for Access-to-Subprogram Values
12528 @cindex Access-to-subprogram
12529
12530 @noindent
12531 The introduction of access-to-subprogram types in Ada 95 complicates
12532 the handling of elaboration. The trouble is that it becomes
12533 impossible to tell at compile time which procedure
12534 is being called. This means that it is not possible for the binder
12535 to analyze the elaboration requirements in this case.
12536
12537 If at the point at which the access value is created
12538 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
12539 the body of the subprogram is
12540 known to have been elaborated, then the access value is safe, and its use
12541 does not require a check. This may be achieved by appropriate arrangement
12542 of the order of declarations if the subprogram is in the current unit,
12543 or, if the subprogram is in another unit, by using pragma
12544 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
12545 on the referenced unit.
12546
12547 If the referenced body is not known to have been elaborated at the point
12548 the access value is created, then any use of the access value must do a
12549 dynamic check, and this dynamic check will fail and raise a
12550 @code{Program_Error} exception if the body has not been elaborated yet.
12551 GNAT will generate the necessary checks, and in addition, if the
12552 @option{-gnatwl}
12553 switch is set, will generate warnings that such checks are required.
12554
12555 The use of dynamic dispatching for tagged types similarly generates
12556 a requirement for dynamic checks, and premature calls to any primitive
12557 operation of a tagged type before the body of the operation has been elaborated,
12558 will result in the raising of @code{Program_Error}.
12559
12560 @node Summary of Procedures for Elaboration Control
12561 @section Summary of Procedures for Elaboration Control
12562 @cindex Elaboration control
12563
12564 @noindent
12565 First, compile your program with the default options, using none of
12566 the special elaboration control switches. If the binder successfully
12567 binds your program, then you can be confident that, apart from issues
12568 raised by the use of access-to-subprogram types and dynamic dispatching,
12569 the program is free of elaboration errors. If it is important that the
12570 program be portable, then use the
12571 @option{-gnatwl}
12572 switch to generate warnings about missing @code{Elaborate_All}
12573 pragmas, and supply the missing pragmas.
12574
12575 If the program fails to bind using the default static elaboration
12576 handling, then you can fix the program to eliminate the binder
12577 message, or recompile the entire program with the
12578 @option{-gnatE} switch to generate dynamic elaboration checks,
12579 and, if you are sure there really are no elaboration problems,
12580 use a global pragma @code{Suppress (Elaboration_Checks)}.
12581
12582 @node Other Elaboration Order Considerations
12583 @section Other Elaboration Order Considerations
12584 @noindent
12585 This section has been entirely concerned with the issue of finding a valid
12586 elaboration order, as defined by the Ada Reference Manual. In a case
12587 where several elaboration orders are valid, the task is to find one
12588 of the possible valid elaboration orders (and the static model in GNAT
12589 will ensure that this is achieved).
12590
12591 The purpose of the elaboration rules in the Ada Reference Manual is to
12592 make sure that no entity is accessed before it has been elaborated. For
12593 a subprogram, this means that the spec and body must have been elaborated
12594 before the subprogram is called. For an object, this means that the object
12595 must have been elaborated before its value is read or written. A violation
12596 of either of these two requirements is an access before elaboration order,
12597 and this section has been all about avoiding such errors.
12598
12599 In the case where more than one order of elaboration is possible, in the
12600 sense that access before elaboration errors are avoided, then any one of
12601 the orders is "correct" in the sense that it meets the requirements of
12602 the Ada Reference Manual, and no such error occurs.
12603
12604 However, it may be the case for a given program, that there are
12605 constraints on the order of elaboration that come not from consideration
12606 of avoiding elaboration errors, but rather from extra-lingual logic
12607 requirements. Consider this example:
12608
12609 @smallexample
12610 with Init_Constants;
12611 package Constants is
12612    X : Integer := 0;
12613    Y : Integer := 0;
12614 end Constants;
12615
12616 package Init_Constants is
12617    procedure Calc;
12618 end Init_Constants;
12619
12620 with Constants;
12621 package body Init_Constants is
12622    procedure Calc is begin null; end;
12623 begin
12624    Constants.X := 3;
12625    Constants.Y := 4;
12626 end Init_Constants;
12627
12628 with Constants;
12629 package Calc is
12630    Z : Integer := Constants.X + Constants.Y;
12631 end Calc;
12632
12633 with Calc;
12634 with Text_IO; use Text_IO;
12635 procedure Main is
12636 begin
12637    Put_Line (Calc.Z'Img);
12638 end Main;
12639 @end smallexample
12640
12641 @noindent
12642 In this example, there is more than one valid order of elaboration. For
12643 example both the following are correct orders:
12644
12645 @smallexample
12646 Init_Constants spec
12647 Constants spec
12648 Calc spec
12649 Main body
12650 Init_Constants body
12651
12652   and
12653
12654 Init_Constants spec
12655 Init_Constants body
12656 Constants spec
12657 Calc spec
12658 Main body
12659 @end smallexample
12660
12661 @noindent
12662 There is no language rule to prefer one or the other, both are correct
12663 from an order of elaboration point of view. But the programmatic effects
12664 of the two orders are very different. In the first, the elaboration routine
12665 of @code{Calc} initializes @code{Z} to zero, and then the main program
12666 runs with this value of zero. But in the second order, the elaboration
12667 routine of @code{Calc} runs after the body of Init_Constants has set
12668 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
12669 runs.
12670
12671 One could perhaps by applying pretty clever non-artificial intelligence
12672 to the situation guess that it is more likely that the second order of
12673 elaboration is the one desired, but there is no formal linguistic reason
12674 to prefer one over the other. In fact in this particular case, GNAT will
12675 prefer the second order, because of the rule that bodies are elaborated
12676 as soon as possible, but it's just luck that this is what was wanted
12677 (if indeed the second order was preferred).
12678
12679 If the program cares about the order of elaboration routines in a case like
12680 this, it is important to specify the order required. In this particular
12681 case, that could have been achieved by adding to the spec of Calc:
12682
12683 @smallexample
12684 pragma Elaborate_All (Constants);
12685 @end smallexample
12686
12687 @noindent
12688 which requires that the body (if any) and spec of @code{Constants},
12689 as well as the body and spec of any unit @code{with}'ed by
12690 @code{Constants} be elaborated before @code{Calc} is elaborated.
12691
12692 Clearly no automatic method can always guess which alternative you require,
12693 and if you are working with legacy code that had constraints of this kind
12694 which were not properly specified by adding @code{Elaborate} or
12695 @code{Elaborate_All} pragmas, then indeed it is possible that two different
12696 compilers can choose different orders.
12697
12698 The @code{gnatbind}
12699 @code{-p} switch may be useful in smoking
12700 out problems. This switch causes bodies to be elaborated as late as possible
12701 instead of as early as possible. In the example above, it would have forced
12702 the choice of the first elaboration order. If you get different results
12703 when using this switch, and particularly if one set of results is right,
12704 and one is wrong as far as you are concerned, it shows that you have some
12705 missing @code{Elaborate} pragmas. For the example above, we have the
12706 following output:
12707
12708 @smallexample
12709 gnatmake -f -q main
12710 main
12711  7
12712 gnatmake -f -q main -bargs -p
12713 main
12714  0
12715 @end smallexample
12716
12717 @noindent
12718 It is of course quite unlikely that both these results are correct, so
12719 it is up to you in a case like this to investigate the source of the
12720 difference, by looking at the two elaboration orders that are chosen,
12721 and figuring out which is correct, and then adding the necessary
12722 @code{Elaborate_All} pragmas to ensure the desired order.
12723
12724 @node The Cross-Referencing Tools gnatxref and gnatfind
12725 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12726 @findex gnatxref
12727 @findex gnatfind
12728
12729 @noindent
12730 The compiler generates cross-referencing information (unless
12731 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12732 This information indicates where in the source each entity is declared and
12733 referenced. Note that entities in package Standard are not included, but
12734 entities in all other predefined units are included in the output.
12735
12736 Before using any of these two tools, you need to compile successfully your
12737 application, so that GNAT gets a chance to generate the cross-referencing
12738 information.
12739
12740 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12741 information to provide the user with the capability to easily locate the
12742 declaration and references to an entity. These tools are quite similar,
12743 the difference being that @code{gnatfind} is intended for locating
12744 definitions and/or references to a specified entity or entities, whereas
12745 @code{gnatxref} is oriented to generating a full report of all
12746 cross-references.
12747
12748 To use these tools, you must not compile your application using the
12749 @option{-gnatx} switch on the @file{gnatmake} command line (@inforef{The
12750 GNAT Make Program gnatmake,,gnat_ug}). Otherwise, cross-referencing
12751 information will not be generated.
12752
12753 @menu
12754 * gnatxref Switches::
12755 * gnatfind Switches::
12756 * Project Files for gnatxref and gnatfind::
12757 * Regular Expressions in gnatfind and gnatxref::
12758 * Examples of gnatxref Usage::
12759 * Examples of gnatfind Usage::
12760 @end menu
12761
12762 @node gnatxref Switches
12763 @section @code{gnatxref} Switches
12764
12765 @noindent
12766 The command lines for @code{gnatxref} is:
12767 @smallexample
12768 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
12769 @end smallexample
12770
12771 @noindent
12772 where
12773
12774 @table @code
12775 @item sourcefile1, sourcefile2
12776 identifies the source files for which a report is to be generated. The
12777 'with'ed units will be processed too. You must provide at least one file.
12778
12779 These file names are considered to be regular expressions, so for instance
12780 specifying 'source*.adb' is the same as giving every file in the current
12781 directory whose name starts with 'source' and whose extension is 'adb'.
12782
12783 @end table
12784
12785 @noindent
12786 The switches can be :
12787 @table @code
12788 @item -a
12789 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12790 the read-only files found in the library search path. Otherwise, these files
12791 will be ignored. This option can be used to protect Gnat sources or your own
12792 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12793 much faster, and their output much smaller.
12794
12795 @item -aIDIR
12796 When looking for source files also look in directory DIR. The order in which
12797 source file search is undertaken is the same as for @file{gnatmake}.
12798
12799 @item -aODIR
12800 When searching for library and object files, look in directory
12801 DIR. The order in which library files are searched is the same as for
12802 @file{gnatmake}.
12803
12804 @item -nostdinc
12805 Do not look for sources in the system default directory.
12806
12807 @item -nostdlib
12808 Do not look for library files in the system default directory.
12809
12810 @item --RTS=@var{rts-path}
12811 @cindex @code{--RTS} (@code{gnatxref})
12812 Specifies the default location of the runtime library. Same meaning as the
12813 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
12814
12815 @item -d
12816 If this switch is set @code{gnatxref} will output the parent type
12817 reference for each matching derived types.
12818
12819 @item -f
12820 If this switch is set, the output file names will be preceded by their
12821 directory (if the file was found in the search path). If this switch is
12822 not set, the directory will not be printed.
12823
12824 @item -g
12825 If this switch is set, information is output only for library-level
12826 entities, ignoring local entities. The use of this switch may accelerate
12827 @code{gnatfind} and @code{gnatxref}.
12828
12829 @item -IDIR
12830 Equivalent to @samp{-aODIR -aIDIR}.
12831
12832 @item -pFILE
12833 Specify a project file to use @xref{Project Files}.
12834 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12835 project file in the current directory.
12836
12837 If a project file is either specified or found by the tools, then the content
12838 of the source directory and object directory lines are added as if they
12839 had been specified respectively by @samp{-aI}
12840 and @samp{-aO}.
12841 @item -u
12842 Output only unused symbols. This may be really useful if you give your
12843 main compilation unit on the command line, as @code{gnatxref} will then
12844 display every unused entity and 'with'ed package.
12845
12846 @item -v
12847 Instead of producing the default output, @code{gnatxref} will generate a
12848 @file{tags} file that can be used by vi. For examples how to use this
12849 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
12850 to the standard output, thus you will have to redirect it to a file.
12851
12852 @end table
12853
12854 All these switches may be in any order on the command line, and may even
12855 appear after the file names. They need not be separated by spaces, thus
12856 you can say @samp{gnatxref -ag} instead of
12857 @samp{gnatxref -a -g}.
12858
12859 @node gnatfind Switches
12860 @section @code{gnatfind} Switches
12861
12862 @noindent
12863 The command line for @code{gnatfind} is:
12864
12865 @smallexample
12866 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
12867       [file1 file2 ...]
12868 @end smallexample
12869
12870 @noindent
12871 where
12872
12873 @table @code
12874 @item pattern
12875 An entity will be output only if it matches the regular expression found
12876 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
12877
12878 Omitting the pattern is equivalent to specifying @samp{*}, which
12879 will match any entity. Note that if you do not provide a pattern, you
12880 have to provide both a sourcefile and a line.
12881
12882 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12883 for matching purposes. At the current time there is no support for
12884 8-bit codes other than Latin-1, or for wide characters in identifiers.
12885
12886 @item sourcefile
12887 @code{gnatfind} will look for references, bodies or declarations
12888 of symbols referenced in @file{sourcefile}, at line @samp{line}
12889 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
12890 for syntax examples.
12891
12892 @item line
12893 is a decimal integer identifying the line number containing
12894 the reference to the entity (or entities) to be located.
12895
12896 @item column
12897 is a decimal integer identifying the exact location on the
12898 line of the first character of the identifier for the
12899 entity reference. Columns are numbered from 1.
12900
12901 @item file1 file2 ...
12902 The search will be restricted to these files. If none are given, then
12903 the search will be done for every library file in the search path.
12904 These file must appear only after the pattern or sourcefile.
12905
12906 These file names are considered to be regular expressions, so for instance
12907 specifying 'source*.adb' is the same as giving every file in the current
12908 directory whose name starts with 'source' and whose extension is 'adb'.
12909
12910 Not that if you specify at least one file in this part, @code{gnatfind} may
12911 sometimes not be able to find the body of the subprograms...
12912
12913 @end table
12914
12915 At least one of 'sourcefile' or 'pattern' has to be present on
12916 the command line.
12917
12918 The following switches are available:
12919 @table @code
12920
12921 @item -a
12922 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12923 the read-only files found in the library search path. Otherwise, these files
12924 will be ignored. This option can be used to protect Gnat sources or your own
12925 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12926 much faster, and their output much smaller.
12927
12928 @item -aIDIR
12929 When looking for source files also look in directory DIR. The order in which
12930 source file search is undertaken is the same as for @file{gnatmake}.
12931
12932 @item -aODIR
12933 When searching for library and object files, look in directory
12934 DIR. The order in which library files are searched is the same as for
12935 @file{gnatmake}.
12936
12937 @item -nostdinc
12938 Do not look for sources in the system default directory.
12939
12940 @item -nostdlib
12941 Do not look for library files in the system default directory.
12942
12943 @item --RTS=@var{rts-path}
12944 @cindex @code{--RTS} (@code{gnatfind})
12945 Specifies the default location of the runtime library. Same meaning as the
12946 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
12947
12948 @item -d
12949 If this switch is set, then @code{gnatfind} will output the parent type
12950 reference for each matching derived types.
12951
12952 @item -e
12953 By default, @code{gnatfind} accept the simple regular expression set for
12954 @samp{pattern}. If this switch is set, then the pattern will be
12955 considered as full Unix-style regular expression.
12956
12957 @item -f
12958 If this switch is set, the output file names will be preceded by their
12959 directory (if the file was found in the search path). If this switch is
12960 not set, the directory will not be printed.
12961
12962 @item -g
12963 If this switch is set, information is output only for library-level
12964 entities, ignoring local entities. The use of this switch may accelerate
12965 @code{gnatfind} and @code{gnatxref}.
12966
12967 @item -IDIR
12968 Equivalent to @samp{-aODIR -aIDIR}.
12969
12970 @item -pFILE
12971 Specify a project file (@pxref{Project Files}) to use.
12972 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12973 project file in the current directory.
12974
12975 If a project file is either specified or found by the tools, then the content
12976 of the source directory and object directory lines are added as if they
12977 had been specified respectively by @samp{-aI} and
12978 @samp{-aO}.
12979
12980 @item -r
12981 By default, @code{gnatfind} will output only the information about the
12982 declaration, body or type completion of the entities. If this switch is
12983 set, the @code{gnatfind} will locate every reference to the entities in
12984 the files specified on the command line (or in every file in the search
12985 path if no file is given on the command line).
12986
12987 @item -s
12988 If this switch is set, then @code{gnatfind} will output the content
12989 of the Ada source file lines were the entity was found.
12990
12991 @item -t
12992 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12993 the specified type. It act like -d option but recursively from parent
12994 type to parent type. When this switch is set it is not possible to
12995 specify more than one file.
12996
12997 @end table
12998
12999 All these switches may be in any order on the command line, and may even
13000 appear after the file names. They need not be separated by spaces, thus
13001 you can say @samp{gnatxref -ag} instead of
13002 @samp{gnatxref -a -g}.
13003
13004 As stated previously, gnatfind will search in every directory in the
13005 search path. You can force it to look only in the current directory if
13006 you specify @code{*} at the end of the command line.
13007
13008
13009 @node Project Files for gnatxref and gnatfind
13010 @section Project Files for @command{gnatxref} and @command{gnatfind}
13011
13012 @noindent
13013 Project files allow a programmer to specify how to compile its
13014 application, where to find sources,... These files are used primarily by
13015 the Glide Ada mode, but they can also be used by the two tools
13016 @code{gnatxref} and @code{gnatfind}.
13017
13018 A project file name must end with @file{.adp}. If a single one is
13019 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13020 extract the information from it. If multiple project files are found, none of
13021 them is read, and you have to use the @samp{-p} switch to specify the one
13022 you want to use.
13023
13024 The following lines can be included, even though most of them have default
13025 values which can be used in most cases.
13026 The lines can be entered in any order in the file.
13027 Except for @samp{src_dir} and @samp{obj_dir}, you can only have one instance of
13028 each line. If you have multiple instances, only the last one is taken into
13029 account.
13030
13031 @table @code
13032 @item src_dir=DIR         [default: "./"]
13033 specifies a directory where to look for source files. Multiple src_dir lines
13034 can be specified and they will be searched in the order they
13035 are specified.
13036
13037 @item obj_dir=DIR         [default: "./"]
13038 specifies a directory where to look for object and library files. Multiple
13039 obj_dir lines can be specified and they will be searched in the order they
13040 are specified
13041
13042 @item comp_opt=SWITCHES   [default: ""]
13043 creates a variable which can be referred to subsequently by using
13044 the @samp{$@{comp_opt@}} notation. This is intended to store the default
13045 switches given to @file{gnatmake} and @file{gcc}.
13046
13047 @item bind_opt=SWITCHES   [default: ""]
13048 creates a variable which can be referred to subsequently by using
13049 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13050 switches given to @file{gnatbind}.
13051
13052 @item link_opt=SWITCHES   [default: ""]
13053 creates a variable which can be referred to subsequently by using
13054 the @samp{$@{link_opt@}} notation. This is intended to store the default
13055 switches given to @file{gnatlink}.
13056
13057 @item main=EXECUTABLE     [default: ""]
13058 specifies the name of the executable for the application. This variable can
13059 be referred to in the following lines by using the @samp{$@{main@}} notation.
13060
13061 @item comp_cmd=COMMAND    [default: "gcc -c -I$@{src_dir@} -g -gnatq"]
13062 specifies the command used to compile a single file in the application.
13063
13064 @item make_cmd=COMMAND    [default: "gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"]
13065 specifies the command used to recompile the whole application.
13066
13067 @item run_cmd=COMMAND     [default: "$@{main@}"]
13068 specifies the command used to run the application.
13069
13070 @item debug_cmd=COMMAND   [default: "gdb $@{main@}"]
13071 specifies the command used to debug the application
13072
13073 @end table
13074
13075 @code{gnatxref} and @code{gnatfind} only take into account the @samp{src_dir}
13076 and @samp{obj_dir} lines, and ignore the others.
13077
13078 @node Regular Expressions in gnatfind and gnatxref
13079 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
13080
13081 @noindent
13082 As specified in the section about @code{gnatfind}, the pattern can be a
13083 regular expression. Actually, there are to set of regular expressions
13084 which are recognized by the program :
13085
13086 @table @code
13087 @item globbing patterns
13088 These are the most usual regular expression. They are the same that you
13089 generally used in a Unix shell command line, or in a DOS session.
13090
13091 Here is a more formal grammar :
13092 @smallexample
13093 @group
13094 @iftex
13095 @leftskip=.5cm
13096 @end iftex
13097 regexp ::= term
13098 term   ::= elmt            -- matches elmt
13099 term   ::= elmt elmt       -- concatenation (elmt then elmt)
13100 term   ::= *               -- any string of 0 or more characters
13101 term   ::= ?               -- matches any character
13102 term   ::= [char @{char@}] -- matches any character listed
13103 term   ::= [char - char]   -- matches any character in range
13104 @end group
13105 @end smallexample
13106
13107 @item full regular expression
13108 The second set of regular expressions is much more powerful. This is the
13109 type of regular expressions recognized by utilities such a @file{grep}.
13110
13111 The following is the form of a regular expression, expressed in Ada
13112 reference manual style BNF is as follows
13113
13114 @smallexample
13115 @iftex
13116 @leftskip=.5cm
13117 @end iftex
13118 @group
13119 regexp ::= term @{| term@} -- alternation (term or term ...)
13120
13121 term ::= item @{item@}     -- concatenation (item then item)
13122
13123 item ::= elmt              -- match elmt
13124 item ::= elmt *            -- zero or more elmt's
13125 item ::= elmt +            -- one or more elmt's
13126 item ::= elmt ?            -- matches elmt or nothing
13127 @end group
13128 @group
13129 elmt ::= nschar            -- matches given character
13130 elmt ::= [nschar @{nschar@}]   -- matches any character listed
13131 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
13132 elmt ::= [char - char]     -- matches chars in given range
13133 elmt ::= \ char            -- matches given character
13134 elmt ::= .                 -- matches any single character
13135 elmt ::= ( regexp )        -- parens used for grouping
13136
13137 char ::= any character, including special characters
13138 nschar ::= any character except ()[].*+?^
13139 @end group
13140 @end smallexample
13141
13142 Following are a few examples :
13143
13144 @table @samp
13145 @item abcde|fghi
13146 will match any of the two strings 'abcde' and 'fghi'.
13147
13148 @item abc*d
13149 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
13150
13151 @item [a-z]+
13152 will match any string which has only lowercase characters in it (and at
13153 least one character
13154
13155 @end table
13156 @end table
13157
13158 @node Examples of gnatxref Usage
13159 @section Examples of @code{gnatxref} Usage
13160
13161 @subsection General Usage
13162
13163 @noindent
13164 For the following examples, we will consider the following units :
13165
13166 @smallexample
13167 @group
13168 @cartouche
13169 main.ads:
13170 1: @b{with} Bar;
13171 2: @b{package} Main @b{is}
13172 3:     @b{procedure} Foo (B : @b{in} Integer);
13173 4:     C : Integer;
13174 5: @b{private}
13175 6:     D : Integer;
13176 7: @b{end} Main;
13177
13178 main.adb:
13179 1: @b{package body} Main @b{is}
13180 2:     @b{procedure} Foo (B : @b{in} Integer) @b{is}
13181 3:     @b{begin}
13182 4:        C := B;
13183 5:        D := B;
13184 6:        Bar.Print (B);
13185 7:        Bar.Print (C);
13186 8:     @b{end} Foo;
13187 9: @b{end} Main;
13188
13189 bar.ads:
13190 1: @b{package} Bar @b{is}
13191 2:     @b{procedure} Print (B : Integer);
13192 3: @b{end} bar;
13193 @end cartouche
13194 @end group
13195 @end smallexample
13196
13197 @table @code
13198
13199 @noindent
13200 The first thing to do is to recompile your application (for instance, in
13201 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13202 the cross-referencing information.
13203 You can then issue any of the following commands:
13204
13205 @item gnatxref main.adb
13206 @code{gnatxref} generates cross-reference information for main.adb
13207 and every unit 'with'ed by main.adb.
13208
13209 The output would be:
13210 @smallexample
13211 @iftex
13212 @leftskip=0cm
13213 @end iftex
13214 B                                                      Type: Integer
13215   Decl: bar.ads           2:22
13216 B                                                      Type: Integer
13217   Decl: main.ads          3:20
13218   Body: main.adb          2:20
13219   Ref:  main.adb          4:13     5:13     6:19
13220 Bar                                                    Type: Unit
13221   Decl: bar.ads           1:9
13222   Ref:  main.adb          6:8      7:8
13223        main.ads           1:6
13224 C                                                      Type: Integer
13225   Decl: main.ads          4:5
13226   Modi: main.adb          4:8
13227   Ref:  main.adb          7:19
13228 D                                                      Type: Integer
13229   Decl: main.ads          6:5
13230   Modi: main.adb          5:8
13231 Foo                                                    Type: Unit
13232   Decl: main.ads          3:15
13233   Body: main.adb          2:15
13234 Main                                                    Type: Unit
13235   Decl: main.ads          2:9
13236   Body: main.adb          1:14
13237 Print                                                   Type: Unit
13238   Decl: bar.ads           2:15
13239   Ref:  main.adb          6:12     7:12
13240 @end smallexample
13241
13242 @noindent
13243 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13244 its body is in main.adb, line 1, column 14 and is not referenced any where.
13245
13246 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13247 it referenced in main.adb, line 6 column 12 and line 7 column 12.
13248
13249 @item gnatxref package1.adb package2.ads
13250 @code{gnatxref} will generates cross-reference information for
13251 package1.adb, package2.ads and any other package 'with'ed by any
13252 of these.
13253
13254 @end table
13255
13256 @subsection Using gnatxref with vi
13257
13258 @code{gnatxref} can generate a tags file output, which can be used
13259 directly from @file{vi}. Note that the standard version of @file{vi}
13260 will not work properly with overloaded symbols. Consider using another
13261 free implementation of @file{vi}, such as @file{vim}.
13262
13263 @smallexample
13264 $ gnatxref -v gnatfind.adb > tags
13265 @end smallexample
13266
13267 @noindent
13268 will generate the tags file for @code{gnatfind} itself (if the sources
13269 are in the search path!).
13270
13271 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
13272 (replacing @i{entity} by whatever you are looking for), and vi will
13273 display a new file with the corresponding declaration of entity.
13274
13275 @node Examples of gnatfind Usage
13276 @section Examples of @code{gnatfind} Usage
13277
13278 @table @code
13279
13280 @item gnatfind -f xyz:main.adb
13281 Find declarations for all entities xyz referenced at least once in
13282 main.adb. The references are search in every library file in the search
13283 path.
13284
13285 The directories will be printed as well (as the @samp{-f}
13286 switch is set)
13287
13288 The output will look like:
13289 @smallexample
13290 directory/main.ads:106:14: xyz <= declaration
13291 directory/main.adb:24:10: xyz <= body
13292 directory/foo.ads:45:23: xyz <= declaration
13293 @end smallexample
13294
13295 @noindent
13296 that is to say, one of the entities xyz found in main.adb is declared at
13297 line 12 of main.ads (and its body is in main.adb), and another one is
13298 declared at line 45 of foo.ads
13299
13300 @item gnatfind -fs xyz:main.adb
13301 This is the same command as the previous one, instead @code{gnatfind} will
13302 display the content of the Ada source file lines.
13303
13304 The output will look like:
13305
13306 @smallexample
13307 directory/main.ads:106:14: xyz <= declaration
13308    procedure xyz;
13309 directory/main.adb:24:10: xyz <= body
13310    procedure xyz is
13311 directory/foo.ads:45:23: xyz <= declaration
13312    xyz : Integer;
13313 @end smallexample
13314
13315 @noindent
13316 This can make it easier to find exactly the location your are looking
13317 for.
13318
13319 @item gnatfind -r "*x*":main.ads:123 foo.adb
13320 Find references to all entities containing an x that are
13321 referenced on line 123 of main.ads.
13322 The references will be searched only in main.adb and foo.adb.
13323
13324 @item gnatfind main.ads:123
13325 Find declarations and bodies for all entities that are referenced on
13326 line 123 of main.ads.
13327
13328 This is the same as @code{gnatfind "*":main.adb:123}.
13329
13330 @item gnatfind mydir/main.adb:123:45
13331 Find the declaration for the entity referenced at column 45 in
13332 line 123 of file main.adb in directory mydir. Note that it
13333 is usual to omit the identifier name when the column is given,
13334 since the column position identifies a unique reference.
13335
13336 The column has to be the beginning of the identifier, and should not
13337 point to any character in the middle of the identifier.
13338
13339 @end table
13340
13341 @node File Name Krunching Using gnatkr
13342 @chapter File Name Krunching Using @code{gnatkr}
13343 @findex gnatkr
13344
13345 @noindent
13346 This chapter discusses the method used by the compiler to shorten
13347 the default file names chosen for Ada units so that they do not
13348 exceed the maximum length permitted. It also describes the
13349 @code{gnatkr} utility that can be used to determine the result of
13350 applying this shortening.
13351 @menu
13352 * About gnatkr::
13353 * Using gnatkr::
13354 * Krunching Method::
13355 * Examples of gnatkr Usage::
13356 @end menu
13357
13358 @node About gnatkr
13359 @section About @code{gnatkr}
13360
13361 @noindent
13362 The default file naming rule in GNAT
13363 is that the file name must be derived from
13364 the unit name. The exact default rule is as follows:
13365 @itemize @bullet
13366 @item
13367 Take the unit name and replace all dots by hyphens.
13368 @item
13369 If such a replacement occurs in the
13370 second character position of a name, and the first character is
13371 a, g, s, or i then replace the dot by the character
13372 ~ (tilde)
13373 instead of a minus.
13374 @end itemize
13375 The reason for this exception is to avoid clashes
13376 with the standard names for children of System, Ada, Interfaces,
13377 and GNAT, which use the prefixes s- a- i- and g-
13378 respectively.
13379
13380 The @code{-gnatk@var{nn}}
13381 switch of the compiler activates a "krunching"
13382 circuit that limits file names to nn characters (where nn is a decimal
13383 integer). For example, using OpenVMS,
13384 where the maximum file name length is
13385 39, the value of nn is usually set to 39, but if you want to generate
13386 a set of files that would be usable if ported to a system with some
13387 different maximum file length, then a different value can be specified.
13388 The default value of 39 for OpenVMS need not be specified.
13389
13390 The @code{gnatkr} utility can be used to determine the krunched name for
13391 a given file, when krunched to a specified maximum length.
13392
13393 @node Using gnatkr
13394 @section Using @code{gnatkr}
13395
13396 @noindent
13397 The @code{gnatkr} command has the form
13398
13399 @smallexample
13400 $ gnatkr @var{name} [@var{length}]
13401 @end smallexample
13402
13403
13404 @noindent
13405 @var{name} can be an Ada name with dots or the GNAT name of the unit,
13406 where the dots representing child units or subunit are replaced by
13407 hyphens. The only confusion arises if a name ends in @code{.ads} or
13408 @code{.adb}. @code{gnatkr} takes this to be an extension if there are
13409 no other dots in the name and the whole name is in lowercase.
13410
13411 @var{length} represents the length of the krunched name. The default
13412 when no argument is given is 8 characters. A length of zero stands for
13413 unlimited, in other words do not chop except for system files which are
13414 always 8.
13415
13416 @noindent
13417 The output is the krunched name. The output has an extension only if the
13418 original argument was a file name with an extension.
13419
13420 @node Krunching Method
13421 @section Krunching Method
13422
13423 @noindent
13424 The initial file name is determined by the name of the unit that the file
13425 contains. The name is formed by taking the full expanded name of the
13426 unit and replacing the separating dots with hyphens and
13427 using lowercase
13428 for all letters, except that a hyphen in the second character position is
13429 replaced by a tilde if the first character is
13430 a, i, g, or s.
13431 The extension is @code{.ads} for a
13432 specification and @code{.adb} for a body.
13433 Krunching does not affect the extension, but the file name is shortened to
13434 the specified length by following these rules:
13435
13436 @itemize @bullet
13437 @item
13438 The name is divided into segments separated by hyphens, tildes or
13439 underscores and all hyphens, tildes, and underscores are
13440 eliminated. If this leaves the name short enough, we are done.
13441
13442 @item
13443 If the name is too long, the longest segment is located (left-most if there are two
13444 of equal length), and shortened by dropping its last character. This is
13445 repeated until the name is short enough.
13446
13447 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
13448 to fit the name into 8 characters as required by some operating systems.
13449
13450 @smallexample
13451 our-strings-wide_fixed 22
13452 our strings wide fixed 19
13453 our string  wide fixed 18
13454 our strin   wide fixed 17
13455 our stri    wide fixed 16
13456 our stri    wide fixe  15
13457 our str     wide fixe  14
13458 our str     wid  fixe  13
13459 our str     wid  fix   12
13460 ou  str     wid  fix   11
13461 ou  st      wid  fix   10
13462 ou  st      wi   fix   9
13463 ou  st      wi   fi    8
13464 Final file name: oustwifi.adb
13465 @end smallexample
13466
13467 @item
13468 The file names for all predefined units are always krunched to eight
13469 characters. The krunching of these predefined units uses the following
13470 special prefix replacements:
13471
13472 @table @file
13473 @item ada-
13474 replaced by @file{a-}
13475
13476 @item gnat-
13477 replaced by @file{g-}
13478
13479 @item interfaces-
13480 replaced by @file{i-}
13481
13482 @item system-
13483 replaced by @file{s-}
13484 @end table
13485
13486 These system files have a hyphen in the second character position. That
13487 is why normal user files replace such a character with a
13488 tilde, to
13489 avoid confusion with system file names.
13490
13491 As an example of this special rule, consider
13492 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
13493
13494 @smallexample
13495 ada-strings-wide_fixed 22
13496 a-  strings wide fixed 18
13497 a-  string  wide fixed 17
13498 a-  strin   wide fixed 16
13499 a-  stri    wide fixed 15
13500 a-  stri    wide fixe  14
13501 a-  str     wide fixe  13
13502 a-  str     wid  fixe  12
13503 a-  str     wid  fix   11
13504 a-  st      wid  fix   10
13505 a-  st      wi   fix   9
13506 a-  st      wi   fi    8
13507 Final file name: a-stwifi.adb
13508 @end smallexample
13509 @end itemize
13510
13511 Of course no file shortening algorithm can guarantee uniqueness over all
13512 possible unit names, and if file name krunching is used then it is your
13513 responsibility to ensure that no name clashes occur. The utility
13514 program @code{gnatkr} is supplied for conveniently determining the
13515 krunched name of a file.
13516
13517 @node Examples of gnatkr Usage
13518 @section Examples of @code{gnatkr} Usage
13519
13520 @smallexample
13521 @iftex
13522 @leftskip=0cm
13523 @end iftex
13524 $ gnatkr very_long_unit_name.ads      --> velounna.ads
13525 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
13526 $ gnatkr Grandparent.Parent.Child     --> grparchi
13527 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
13528 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
13529 @end smallexample
13530
13531 @node Preprocessing Using gnatprep
13532 @chapter Preprocessing Using @code{gnatprep}
13533 @findex gnatprep
13534
13535 @noindent
13536 The @code{gnatprep} utility provides
13537 a simple preprocessing capability for Ada programs.
13538 It is designed for use with GNAT, but is not dependent on any special
13539 features of GNAT.
13540
13541 @menu
13542 * Using gnatprep::
13543 * Switches for gnatprep::
13544 * Form of Definitions File::
13545 * Form of Input Text for gnatprep::
13546 @end menu
13547
13548 @node Using gnatprep
13549 @section Using @code{gnatprep}
13550
13551 @noindent
13552 To call @code{gnatprep} use
13553
13554 @smallexample
13555 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
13556 @end smallexample
13557
13558 @noindent
13559 where
13560 @table @code
13561 @item infile
13562 is the full name of the input file, which is an Ada source
13563 file containing preprocessor directives.
13564
13565 @item outfile
13566 is the full name of the output file, which is an Ada source
13567 in standard Ada form. When used with GNAT, this file name will
13568 normally have an ads or adb suffix.
13569
13570 @item deffile
13571 is the full name of a text file containing definitions of
13572 symbols to be referenced by the preprocessor. This argument is
13573 optional, and can be replaced by the use of the @code{-D} switch.
13574
13575 @item switches
13576 is an optional sequence of switches as described in the next section.
13577 @end table
13578
13579 @node Switches for gnatprep
13580 @section Switches for @code{gnatprep}
13581
13582 @table @code
13583
13584 @item -b
13585 Causes both preprocessor lines and the lines deleted by
13586 preprocessing to be replaced by blank lines in the output source file,
13587 preserving line numbers in the output file.
13588
13589 @item -c
13590 Causes both preprocessor lines and the lines deleted
13591 by preprocessing to be retained in the output source as comments marked
13592 with the special string "--! ". This option will result in line numbers
13593 being preserved in the output file.
13594
13595 @item -Dsymbol=value
13596 Defines a new symbol, associated with value. If no value is given on the
13597 command line, then symbol is considered to be @code{True}. This switch
13598 can be used in place of a definition file.
13599
13600
13601 @item -r
13602 Causes a @code{Source_Reference} pragma to be generated that
13603 references the original input file, so that error messages will use
13604 the file name of this original file. The use of this switch implies
13605 that preprocessor lines are not to be removed from the file, so its
13606 use will force @code{-b} mode if
13607 @code{-c}
13608 has not been specified explicitly.
13609
13610 Note that if the file to be preprocessed contains multiple units, then
13611 it will be necessary to @code{gnatchop} the output file from
13612 @code{gnatprep}. If a @code{Source_Reference} pragma is present
13613 in the preprocessed file, it will be respected by
13614 @code{gnatchop -r}
13615 so that the final chopped files will correctly refer to the original
13616 input source file for @code{gnatprep}.
13617
13618 @item -s
13619 Causes a sorted list of symbol names and values to be
13620 listed on the standard output file.
13621
13622 @item -u
13623 Causes undefined symbols to be treated as having the value FALSE in the context
13624 of a preprocessor test. In the absence of this option, an undefined symbol in
13625 a @code{#if} or @code{#elsif} test will be treated as an error.
13626
13627 @end table
13628
13629 @noindent
13630 Note: if neither @code{-b} nor @code{-c} is present,
13631 then preprocessor lines and
13632 deleted lines are completely removed from the output, unless -r is
13633 specified, in which case -b is assumed.
13634
13635 @node Form of Definitions File
13636 @section Form of Definitions File
13637
13638 @noindent
13639 The definitions file contains lines of the form
13640
13641 @smallexample
13642 symbol := value
13643 @end smallexample
13644
13645 @noindent
13646 where symbol is an identifier, following normal Ada (case-insensitive)
13647 rules for its syntax, and value is one of the following:
13648
13649 @itemize @bullet
13650 @item
13651 Empty, corresponding to a null substitution
13652 @item
13653 A string literal using normal Ada syntax
13654 @item
13655 Any sequence of characters from the set
13656 (letters, digits, period, underline).
13657 @end itemize
13658
13659 @noindent
13660 Comment lines may also appear in the definitions file, starting with
13661 the usual @code{--},
13662 and comments may be added to the definitions lines.
13663
13664 @node Form of Input Text for gnatprep
13665 @section Form of Input Text for @code{gnatprep}
13666
13667 @noindent
13668 The input text may contain preprocessor conditional inclusion lines,
13669 as well as general symbol substitution sequences.
13670
13671 The preprocessor conditional inclusion commands have the form
13672
13673 @smallexample
13674 @group
13675 @cartouche
13676 #if @i{expression} [then]
13677    lines
13678 #elsif @i{expression} [then]
13679    lines
13680 #elsif @i{expression} [then]
13681    lines
13682 ...
13683 #else
13684    lines
13685 #end if;
13686 @end cartouche
13687 @end group
13688 @end smallexample
13689
13690 @noindent
13691 In this example, @i{expression} is defined by the following grammar:
13692 @smallexample
13693 @i{expression} ::=  <symbol>
13694 @i{expression} ::=  <symbol> = "<value>"
13695 @i{expression} ::=  <symbol> = <symbol>
13696 @i{expression} ::=  <symbol> 'Defined
13697 @i{expression} ::=  not @i{expression}
13698 @i{expression} ::=  @i{expression} and @i{expression}
13699 @i{expression} ::=  @i{expression} or @i{expression}
13700 @i{expression} ::=  @i{expression} and then @i{expression}
13701 @i{expression} ::=  @i{expression} or else @i{expression}
13702 @i{expression} ::=  ( @i{expression} )
13703 @end smallexample
13704
13705 @noindent
13706 For the first test (@i{expression} ::= <symbol>) the symbol must have
13707 either the value true or false, that is to say the right-hand of the
13708 symbol definition must be one of the (case-insensitive) literals
13709 @code{True} or @code{False}. If the value is true, then the
13710 corresponding lines are included, and if the value is false, they are
13711 excluded.
13712
13713 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
13714 the symbol has been defined in the definition file or by a @code{-D}
13715 switch on the command line. Otherwise, the test is false.
13716
13717 The equality tests are case insensitive, as are all the preprocessor lines.
13718
13719 If the symbol referenced is not defined in the symbol definitions file,
13720 then the effect depends on whether or not switch @code{-u}
13721 is specified. If so, then the symbol is treated as if it had the value
13722 false and the test fails. If this switch is not specified, then
13723 it is an error to reference an undefined symbol. It is also an error to
13724 reference a symbol that is defined with a value other than @code{True}
13725 or @code{False}.
13726
13727 The use of the @code{not} operator inverts the sense of this logical test, so
13728 that the lines are included only if the symbol is not defined.
13729 The @code{then} keyword is optional as shown
13730
13731 The @code{#} must be the first non-blank character on a line, but
13732 otherwise the format is free form. Spaces or tabs may appear between
13733 the @code{#} and the keyword. The keywords and the symbols are case
13734 insensitive as in normal Ada code. Comments may be used on a
13735 preprocessor line, but other than that, no other tokens may appear on a
13736 preprocessor line. Any number of @code{elsif} clauses can be present,
13737 including none at all. The @code{else} is optional, as in Ada.
13738
13739 The @code{#} marking the start of a preprocessor line must be the first
13740 non-blank character on the line, i.e. it must be preceded only by
13741 spaces or horizontal tabs.
13742
13743 Symbol substitution outside of preprocessor lines is obtained by using
13744 the sequence
13745
13746 @smallexample
13747 $symbol
13748 @end smallexample
13749
13750 @noindent
13751 anywhere within a source line, except in a comment or within a
13752 string literal. The identifier
13753 following the @code{$} must match one of the symbols defined in the symbol
13754 definition file, and the result is to substitute the value of the
13755 symbol in place of @code{$symbol} in the output file.
13756
13757 Note that although the substitution of strings within a string literal
13758 is not possible, it is possible to have a symbol whose defined value is
13759 a string literal. So instead of setting XYZ to @code{hello} and writing:
13760
13761 @smallexample
13762 Header : String := "$XYZ";
13763 @end smallexample
13764
13765 @noindent
13766 you should set XYZ to @code{"hello"} and write:
13767
13768 @smallexample
13769 Header : String := $XYZ;
13770 @end smallexample
13771
13772 @noindent
13773 and then the substitution will occur as desired.
13774
13775
13776 @node The GNAT Library Browser gnatls
13777 @chapter The GNAT Library Browser @code{gnatls}
13778 @findex gnatls
13779 @cindex Library browser
13780
13781 @noindent
13782 @code{gnatls} is a tool that outputs information about compiled
13783 units. It gives the relationship between objects, unit names and source
13784 files. It can also be used to check the source dependencies of a unit
13785 as well as various characteristics.
13786
13787 @menu
13788 * Running gnatls::
13789 * Switches for gnatls::
13790 * Examples of gnatls Usage::
13791 @end menu
13792
13793 @node Running gnatls
13794 @section Running @code{gnatls}
13795
13796 @noindent
13797 The @code{gnatls} command has the form
13798
13799 @smallexample
13800 $ gnatls switches @var{object_or_ali_file}
13801 @end smallexample
13802
13803 @noindent
13804 The main argument is the list of object or @file{ali} files
13805 (@pxref{The Ada Library Information Files})
13806 for which information is requested.
13807
13808 In normal mode, without additional option, @code{gnatls} produces a
13809 four-column listing. Each line represents information for a specific
13810 object. The first column gives the full path of the object, the second
13811 column gives the name of the principal unit in this object, the third
13812 column gives the status of the source and the fourth column gives the
13813 full path of the source representing this unit.
13814 Here is a simple example of use:
13815
13816 @smallexample
13817 $ gnatls *.o
13818 ./demo1.o            demo1            DIF demo1.adb
13819 ./demo2.o            demo2             OK demo2.adb
13820 ./hello.o            h1                OK hello.adb
13821 ./instr-child.o      instr.child      MOK instr-child.adb
13822 ./instr.o            instr             OK instr.adb
13823 ./tef.o              tef              DIF tef.adb
13824 ./text_io_example.o  text_io_example   OK text_io_example.adb
13825 ./tgef.o             tgef             DIF tgef.adb
13826 @end smallexample
13827
13828 @noindent
13829 The first line can be interpreted as follows: the main unit which is
13830 contained in
13831 object file @file{demo1.o} is demo1, whose main source is in
13832 @file{demo1.adb}. Furthermore, the version of the source used for the
13833 compilation of demo1 has been modified (DIF). Each source file has a status
13834 qualifier which can be:
13835
13836 @table @code
13837 @item OK (unchanged)
13838 The version of the source file used for the compilation of the
13839 specified unit corresponds exactly to the actual source file.
13840
13841 @item MOK (slightly modified)
13842 The version of the source file used for the compilation of the
13843 specified unit differs from the actual source file but not enough to
13844 require recompilation. If you use gnatmake with the qualifier
13845 @code{-m (minimal recompilation)}, a file marked
13846 MOK will not be recompiled.
13847
13848 @item DIF (modified)
13849 No version of the source found on the path corresponds to the source
13850 used to build this object.
13851
13852 @item ??? (file not found)
13853 No source file was found for this unit.
13854
13855 @item HID (hidden,  unchanged version not first on PATH)
13856 The version of the source that corresponds exactly to the source used
13857 for compilation has been found on the path but it is hidden by another
13858 version of the same source that has been modified.
13859
13860 @end table
13861
13862 @node Switches for gnatls
13863 @section Switches for @code{gnatls}
13864
13865 @noindent
13866 @code{gnatls} recognizes the following switches:
13867
13868 @table @code
13869 @item -a
13870 @cindex @code{-a} (@code{gnatls})
13871 Consider all units, including those of the predefined Ada library.
13872 Especially useful with @code{-d}.
13873
13874 @item -d
13875 @cindex @code{-d} (@code{gnatls})
13876 List sources from which specified units depend on.
13877
13878 @item -h
13879 @cindex @code{-h} (@code{gnatls})
13880 Output the list of options.
13881
13882 @item -o
13883 @cindex @code{-o} (@code{gnatls})
13884 Only output information about object files.
13885
13886 @item -s
13887 @cindex @code{-s} (@code{gnatls})
13888 Only output information about source files.
13889
13890 @item -u
13891 @cindex @code{-u} (@code{gnatls})
13892 Only output information about compilation units.
13893
13894 @item -aO@var{dir}
13895 @itemx -aI@var{dir}
13896 @itemx -I@var{dir}
13897 @itemx  -I-
13898 @itemx -nostdinc
13899 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
13900 (see @ref{Switches for gnatmake}).
13901
13902 @item --RTS=@var{rts-path}
13903 @cindex @code{--RTS} (@code{gnatls})
13904 Specifies the default location of the runtime library. Same meaning as the
13905 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13906
13907 @item -v
13908 @cindex @code{-s} (@code{gnatls})
13909 Verbose mode. Output the complete source and object paths. Do not use
13910 the default column layout but instead use long format giving as much as
13911 information possible on each requested units, including special
13912 characteristics such as:
13913
13914 @table @code
13915 @item  Preelaborable
13916 The unit is preelaborable in the Ada 95 sense.
13917
13918 @item No_Elab_Code
13919 No elaboration code has been produced by the compiler for this unit.
13920
13921 @item Pure
13922 The unit is pure in the Ada 95 sense.
13923
13924 @item Elaborate_Body
13925 The unit contains a pragma Elaborate_Body.
13926
13927 @item Remote_Types
13928 The unit contains a pragma Remote_Types.
13929
13930 @item Shared_Passive
13931 The unit contains a pragma Shared_Passive.
13932
13933 @item Predefined
13934 This unit is part of the predefined environment and cannot be modified
13935 by the user.
13936
13937 @item Remote_Call_Interface
13938 The unit contains a pragma Remote_Call_Interface.
13939
13940 @end table
13941
13942 @end table
13943
13944 @node Examples of gnatls Usage
13945 @section Example of @code{gnatls} Usage
13946
13947 @noindent
13948 Example of using the verbose switch. Note how the source and
13949 object paths are affected by the -I switch.
13950
13951 @smallexample
13952 $ gnatls -v -I.. demo1.o
13953
13954 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
13955
13956 Source Search Path:
13957    <Current_Directory>
13958    ../
13959    /home/comar/local/adainclude/
13960
13961 Object Search Path:
13962    <Current_Directory>
13963    ../
13964    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
13965
13966 ./demo1.o
13967    Unit =>
13968      Name   => demo1
13969      Kind   => subprogram body
13970      Flags  => No_Elab_Code
13971      Source => demo1.adb    modified
13972 @end smallexample
13973
13974 @noindent
13975 The following is an example of use of the dependency list.
13976 Note the use of the -s switch
13977 which gives a straight list of source files. This can be useful for
13978 building specialized scripts.
13979
13980 @smallexample
13981 $ gnatls -d demo2.o
13982 ./demo2.o   demo2        OK demo2.adb
13983                          OK gen_list.ads
13984                          OK gen_list.adb
13985                          OK instr.ads
13986                          OK instr-child.ads
13987
13988 $ gnatls -d -s -a demo1.o
13989 demo1.adb
13990 /home/comar/local/adainclude/ada.ads
13991 /home/comar/local/adainclude/a-finali.ads
13992 /home/comar/local/adainclude/a-filico.ads
13993 /home/comar/local/adainclude/a-stream.ads
13994 /home/comar/local/adainclude/a-tags.ads
13995 gen_list.ads
13996 gen_list.adb
13997 /home/comar/local/adainclude/gnat.ads
13998 /home/comar/local/adainclude/g-io.ads
13999 instr.ads
14000 /home/comar/local/adainclude/system.ads
14001 /home/comar/local/adainclude/s-exctab.ads
14002 /home/comar/local/adainclude/s-finimp.ads
14003 /home/comar/local/adainclude/s-finroo.ads
14004 /home/comar/local/adainclude/s-secsta.ads
14005 /home/comar/local/adainclude/s-stalib.ads
14006 /home/comar/local/adainclude/s-stoele.ads
14007 /home/comar/local/adainclude/s-stratt.ads
14008 /home/comar/local/adainclude/s-tasoli.ads
14009 /home/comar/local/adainclude/s-unstyp.ads
14010 /home/comar/local/adainclude/unchconv.ads
14011 @end smallexample
14012
14013
14014 @node GNAT and Libraries
14015 @chapter GNAT and Libraries
14016 @cindex Library, building, installing
14017
14018 @noindent
14019 This chapter addresses some of the issues related to building and using
14020 a library with GNAT. It also shows how the GNAT run-time library can be
14021 recompiled.
14022
14023 @menu
14024 * Creating an Ada Library::
14025 * Installing an Ada Library::
14026 * Using an Ada Library::
14027 * Creating an Ada Library to be Used in a Non-Ada Context::
14028 * Rebuilding the GNAT Run-Time Library::
14029 @end menu
14030
14031 @node Creating an Ada Library
14032 @section Creating an Ada Library
14033
14034 @noindent
14035 In the GNAT environment, a library has two components:
14036 @itemize @bullet
14037 @item
14038 Source files.
14039 @item
14040 Compiled code and Ali files. See @ref{The Ada Library Information Files}.
14041 @end itemize
14042
14043 @noindent
14044 In order to use other packages @ref{The GNAT Compilation Model}
14045 requires a certain number of sources to be available to the compiler.
14046 The minimal set of
14047 sources required includes the specs of all the packages that make up the
14048 visible part of the library as well as all the sources upon which they
14049 depend. The bodies of all visible generic units must also be provided.
14050 @noindent
14051 Although it is not strictly mandatory, it is recommended that all sources
14052 needed to recompile the library be provided, so that the user can make
14053 full use of inter-unit inlining and source-level debugging. This can also
14054 make the situation easier for users that need to upgrade their compilation
14055 toolchain and thus need to recompile the library from sources.
14056
14057 @noindent
14058 The compiled code can be provided in different ways. The simplest way is
14059 to provide directly the set of objects produced by the compiler during
14060 the compilation of the library. It is also possible to group the objects
14061 into an archive using whatever commands are provided by the operating
14062 system. Finally, it is also possible to create a shared library (see
14063 option -shared in the GCC manual).
14064
14065 @noindent
14066 There are various possibilities for compiling the units that make up the
14067 library: for example with a Makefile @ref{Using the GNU make Utility},
14068 or with a conventional script.
14069 For simple libraries, it is also possible to create a
14070 dummy main program which depends upon all the packages that comprise the
14071 interface of the library. This dummy main program can then be given to
14072 gnatmake, in order to build all the necessary objects. Here is an example
14073 of such a dummy program and the generic commands used to build an
14074 archive or a shared library.
14075
14076 @smallexample
14077 @iftex
14078 @leftskip=.7cm
14079 @end iftex
14080 @b{with} My_Lib.Service1;
14081 @b{with} My_Lib.Service2;
14082 @b{with} My_Lib.Service3;
14083 @b{procedure} My_Lib_Dummy @b{is}
14084 @b{begin}
14085    @b{null};
14086 @b{end};
14087
14088 # compiling the library
14089 $ gnatmake -c my_lib_dummy.adb
14090
14091 # we don't need the dummy object itself
14092 $ rm my_lib_dummy.o my_lib_dummy.ali
14093
14094 # create an archive with the remaining objects
14095 $ ar rc libmy_lib.a *.o
14096 # some systems may require "ranlib" to be run as well
14097
14098 # or create a shared library
14099 $ gcc -shared -o libmy_lib.so *.o
14100 # some systems may require the code to have been compiled with -fPIC
14101 @end smallexample
14102
14103 @noindent
14104 When the objects are grouped in an archive or a shared library, the user
14105 needs to specify the desired library at link time, unless a pragma
14106 linker_options has been used in one of the sources:
14107 @smallexample
14108 @b{pragma} Linker_Options ("-lmy_lib");
14109 @end smallexample
14110
14111 @node Installing an Ada Library
14112 @section Installing an Ada Library
14113
14114 @noindent
14115 In the GNAT model, installing a library consists in copying into a specific
14116 location the files that make up this library. It is possible to install
14117 the sources in a different directory from the other files (ALI, objects,
14118 archives) since the source path and the object path can easily be
14119 specified separately.
14120
14121 @noindent
14122 For general purpose libraries, it is possible for the system
14123 administrator to put those libraries in the default compiler paths. To
14124 achieve this, he must specify their location in the configuration files
14125 "ada_source_path" and "ada_object_path" that must be located in the GNAT
14126 installation tree at the same place as the gcc spec file. The location of
14127 the gcc spec file can be determined as follows:
14128 @smallexample
14129 $ gcc -v
14130 @end smallexample
14131
14132 @noindent
14133 The configuration files mentioned above have simple format: each line in them
14134 must contain one unique
14135 directory name. Those names are added to the corresponding path
14136 in their order of appearance in the file. The names can be either absolute
14137 or relative, in the latter case, they are relative to where theses files
14138 are located.
14139
14140 @noindent
14141 "ada_source_path" and "ada_object_path" might actually not be present in a
14142 GNAT installation, in which case, GNAT will look for its run-time library in
14143 the directories "adainclude" for the sources and "adalib" for the
14144 objects and ALI files. When the files exist, the compiler does not
14145 look in "adainclude" and "adalib" at all, and thus the "ada_source_path" file
14146 must contain the location for the GNAT run-time sources (which can simply
14147 be "adainclude"). In the same way, the "ada_object_path" file must contain
14148 the location for the GNAT run-time objects (which can simply
14149 be "adalib").
14150
14151 @noindent
14152 You can also specify a new default path to the runtime library at compilation
14153 time with the switch "--RTS=@var{rts-path}". You can easily choose and change
14154 the runtime you want your program to be compiled with. This switch is
14155 recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref.
14156
14157 @noindent
14158 It is possible to install a library before or after the standard GNAT
14159 library, by reordering the lines in the configuration files. In general, a
14160 library must be installed before the GNAT library if it redefines any part of it.
14161
14162 @node Using an Ada Library
14163 @section Using an Ada Library
14164
14165 @noindent
14166 In order to use a Ada library, you need to make sure that this
14167 library is on both your source and object path
14168 @ref{Search Paths and the Run-Time Library (RTL)}
14169 and @ref{Search Paths for gnatbind}. For
14170 instance, you can use the library "mylib" installed in "/dir/my_lib_src"
14171 and "/dir/my_lib_obj" with the following commands:
14172
14173 @smallexample
14174 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
14175   -largs -lmy_lib
14176 @end smallexample
14177
14178 @noindent
14179 This can be simplified down to the following:
14180 @smallexample
14181 $ gnatmake my_appl
14182 @end smallexample
14183 when the following conditions are met:
14184 @itemize @bullet
14185 @item
14186 "/dir/my_lib_src" has been added by the user to the environment
14187 variable "ADA_INCLUDE_PATH", or by the administrator to the file
14188 "ada_source_path"
14189 @item
14190 "/dir/my_lib_obj" has been added by the user to the environment
14191 variable "ADA_OBJECTS_PATH", or by the administrator to the file
14192 "ada_object_path"
14193 @item
14194 a pragma linker_options, as mentioned in @ref{Creating an Ada Library}
14195 as been added to the sources.
14196 @end itemize
14197 @noindent
14198
14199 @node Creating an Ada Library to be Used in a Non-Ada Context
14200 @section Creating an Ada Library to be Used in a Non-Ada Context
14201
14202 @noindent
14203 The previous sections detailed how to create and install a library that
14204 was usable from an Ada main program. Using this library in a non-Ada
14205 context is not possible, because the elaboration of the library is
14206 automatically done as part of the main program elaboration.
14207
14208 GNAT also provides the ability to build libraries that can be used both
14209 in an Ada and non-Ada context.  This section describes how to build such
14210 a library, and then how to use it from a C program. The method for
14211 interfacing with the library from other languages such as Fortran for
14212 instance remains the same.
14213
14214 @subsection Creating the Library
14215
14216 @itemize @bullet
14217 @item Identify the units representing the interface of the library.
14218
14219 Here is an example of simple library interface:
14220
14221 @smallexample
14222 package Interface is
14223
14224    procedure Do_Something;
14225
14226    procedure Do_Something_Else;
14227
14228 end Interface;
14229 @end smallexample
14230
14231 @item Use @code{pragma Export} or @code{pragma Convention} for the
14232 exported entities.
14233
14234 Our package @code{Interface} is then updated as follow:
14235 @smallexample
14236 package Interface is
14237
14238    procedure Do_Something;
14239    pragma Export (C, Do_Something, "do_something");
14240
14241    procedure Do_Something_Else;
14242    pragma Export (C, Do_Something_Else, "do_something_else");
14243
14244 end Interface;
14245 @end smallexample
14246
14247 @item Compile all the units composing the library.
14248
14249 @item Bind the library objects.
14250
14251 This step is performed by invoking gnatbind with the @code{-L<prefix>}
14252 switch. @code{gnatbind} will then generate the library elaboration
14253 procedure (named @code{<prefix>init}) and the run-time finalization
14254 procedure (named @code{<prefix>final}).
14255
14256 @smallexample
14257 # generate the binder file in Ada
14258 $ gnatbind -Lmylib interface
14259
14260 # generate the binder file in C
14261 $ gnatbind -C -Lmylib interface
14262 @end smallexample
14263
14264 @item Compile the files generated by the binder
14265
14266 @smallexample
14267 $ gcc -c b~interface.adb
14268 @end smallexample
14269
14270 @item Create the library;
14271
14272 The procedure is identical to the procedure explained in
14273 @ref{Creating an Ada Library},
14274 except that @file{b~interface.o} needs to be added to
14275 the list of objects.
14276
14277 @smallexample
14278 # create an archive file
14279 $ ar cr libmylib.a b~interface.o <other object files>
14280
14281 # create a shared library
14282 $ gcc -shared -o libmylib.so b~interface.o <other object files>
14283 @end smallexample
14284
14285 @item Provide a "foreign" view of the library interface;
14286
14287 The example below shows the content of @code{mylib_interface.h} (note
14288 that there is no rule for the naming of this file, any name can be used)
14289 @smallexample
14290 /* the library elaboration procedure */
14291 extern void mylibinit (void);
14292
14293 /* the library finalization procedure */
14294 extern void mylibfinal (void);
14295
14296 /* the interface exported by the library */
14297 extern void do_something (void);
14298 extern void do_something_else (void);
14299 @end smallexample
14300 @end itemize
14301
14302 @subsection Using the Library
14303
14304 @noindent
14305 Libraries built as explained above can be used from any program, provided
14306 that the elaboration procedures (named @code{mylibinit} in the previous
14307 example) are called before the library services are used. Any number of
14308 libraries can be used simultaneously, as long as the elaboration
14309 procedure of each library is called.
14310
14311 Below is an example of C program that uses our @code{mylib} library.
14312
14313 @smallexample
14314 #include "mylib_interface.h"
14315
14316 int
14317 main (void)
14318 @{
14319    /* First, elaborate the library before using it */
14320    mylibinit ();
14321
14322    /* Main program, using the library exported entities */
14323    do_something ();
14324    do_something_else ();
14325
14326    /* Library finalization at the end of the program */
14327    mylibfinal ();
14328    return 0;
14329 @}
14330 @end smallexample
14331
14332 @noindent
14333 Note that this same library can be used from an equivalent Ada main
14334 program. In addition, if the libraries are installed as detailed in
14335 @ref{Installing an Ada Library}, it is not necessary to invoke the
14336 library elaboration and finalization routines. The binder will ensure
14337 that this is done as part of the main program elaboration and
14338 finalization phases.
14339
14340 @subsection The Finalization Phase
14341
14342 @noindent
14343 Invoking any library finalization procedure generated by @code{gnatbind}
14344 shuts down the Ada run time permanently. Consequently, the finalization
14345 of all Ada libraries must be performed at the end of the program. No
14346 call to these libraries nor the Ada run time should be made past the
14347 finalization phase.
14348
14349 @subsection Restrictions in Libraries
14350
14351 @noindent
14352 The pragmas listed below should be used with caution inside libraries,
14353 as they can create incompatibilities with other Ada libraries:
14354 @itemize @bullet
14355 @item pragma @code{Locking_Policy}
14356 @item pragma @code{Queuing_Policy}
14357 @item pragma @code{Task_Dispatching_Policy}
14358 @item pragma @code{Unreserve_All_Interrupts}
14359 @end itemize
14360 When using a library that contains such pragmas, the user must make sure
14361 that all libraries use the same pragmas with the same values. Otherwise,
14362 a @code{Program_Error} will
14363 be raised during the elaboration of the conflicting
14364 libraries. The usage of these pragmas and its consequences for the user
14365 should therefore be well documented.
14366
14367 Similarly, the traceback in exception occurrences mechanism should be
14368 enabled or disabled in a consistent manner across all libraries.
14369 Otherwise, a Program_Error will be raised during the elaboration of the
14370 conflicting libraries.
14371
14372 If the @code{'Version} and @code{'Body_Version}
14373 attributes are used inside a library, then it is necessary to
14374 perform a @code{gnatbind} step that mentions all ali files in all
14375 libraries, so that version identifiers can be properly computed.
14376 In practice these attributes are rarely used, so this is unlikely
14377 to be a consideration.
14378
14379 @node  Rebuilding the GNAT Run-Time Library
14380 @section Rebuilding the GNAT Run-Time Library
14381
14382 @noindent
14383 It may be useful to recompile the GNAT library in various contexts, the
14384 most important one being the use of partition-wide configuration pragmas
14385 such as Normalize_Scalar. A special Makefile called
14386 @code{Makefile.adalib} is provided to that effect and can be found in
14387 the directory containing the GNAT library. The location of this
14388 directory depends on the way the GNAT environment has been installed and can
14389 be determined by means of the command:
14390
14391 @smallexample
14392 $ gnatls -v
14393 @end smallexample
14394
14395 @noindent
14396 The last entry in the object search path usually contains the
14397 gnat library. This Makefile contains its own documentation and in
14398 particular the set of instructions needed to rebuild a new library and
14399 to use it.
14400
14401 @node Using the GNU make Utility
14402 @chapter Using the GNU @code{make} Utility
14403 @findex make
14404
14405 @noindent
14406 This chapter offers some examples of makefiles that solve specific
14407 problems. It does not explain how to write a makefile (see the GNU make
14408 documentation), nor does it try to replace the @code{gnatmake} utility
14409 (@pxref{The GNAT Make Program gnatmake}).
14410
14411 All the examples in this section are specific to the GNU version of
14412 make. Although @code{make} is a standard utility, and the basic language
14413 is the same, these examples use some advanced features found only in
14414 @code{GNU make}.
14415
14416 @menu
14417 * Using gnatmake in a Makefile::
14418 * Automatically Creating a List of Directories::
14419 * Generating the Command Line Switches::
14420 * Overcoming Command Line Length Limits::
14421 @end menu
14422
14423 @node Using gnatmake in a Makefile
14424 @section Using gnatmake in a Makefile
14425 @findex makefile
14426 @cindex GNU make
14427
14428 @noindent
14429 Complex project organizations can be handled in a very powerful way by
14430 using GNU make combined with gnatmake. For instance, here is a Makefile
14431 which allows you to build each subsystem of a big project into a separate
14432 shared library. Such a makefile allows you to significantly reduce the link
14433 time of very big applications while maintaining full coherence at
14434 each step of the build process.
14435
14436 The list of dependencies are handled automatically by
14437 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
14438 the appropriate directories.
14439
14440 Note that you should also read the example on how to automatically
14441 create the list of directories (@pxref{Automatically Creating a List of Directories})
14442 which might help you in case your project has a lot of
14443 subdirectories.
14444
14445 @smallexample
14446 @iftex
14447 @leftskip=0cm
14448 @font@heightrm=cmr8
14449 @heightrm
14450 @end iftex
14451 ## This Makefile is intended to be used with the following directory
14452 ## configuration:
14453 ##  - The sources are split into a series of csc (computer software components)
14454 ##    Each of these csc is put in its own directory.
14455 ##    Their name are referenced by the directory names.
14456 ##    They will be compiled into shared library (although this would also work
14457 ##    with static libraries
14458 ##  - The main program (and possibly other packages that do not belong to any
14459 ##    csc is put in the top level directory (where the Makefile is).
14460 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
14461 ##                    \_ second_csc (sources) __ lib (will contain the library)
14462 ##                    \_ ...
14463 ## Although this Makefile is build for shared library, it is easy to modify
14464 ## to build partial link objects instead (modify the lines with -shared and
14465 ## gnatlink below)
14466 ##
14467 ## With this makefile, you can change any file in the system or add any new
14468 ## file, and everything will be recompiled correctly (only the relevant shared
14469 ## objects will be recompiled, and the main program will be re-linked).
14470
14471 # The list of computer software component for your project. This might be
14472 # generated automatically.
14473 CSC_LIST=aa bb cc
14474
14475 # Name of the main program (no extension)
14476 MAIN=main
14477
14478 # If we need to build objects with -fPIC, uncomment the following line
14479 #NEED_FPIC=-fPIC
14480
14481 # The following variable should give the directory containing libgnat.so
14482 # You can get this directory through 'gnatls -v'. This is usually the last
14483 # directory in the Object_Path.
14484 GLIB=...
14485
14486 # The directories for the libraries
14487 # (This macro expands the list of CSC to the list of shared libraries, you
14488 # could simply use the expanded form :
14489 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
14490 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
14491
14492 $@{MAIN@}: objects $@{LIB_DIR@}
14493     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
14494     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
14495
14496 objects::
14497     # recompile the sources
14498     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
14499
14500 # Note: In a future version of GNAT, the following commands will be simplified
14501 # by a new tool, gnatmlib
14502 $@{LIB_DIR@}:
14503     mkdir -p $@{dir $@@ @}
14504     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
14505     cd $@{dir $@@ @}; cp -f ../*.ali .
14506
14507 # The dependencies for the modules
14508 # Note that we have to force the expansion of *.o, since in some cases make won't
14509 # be able to do it itself.
14510 aa/lib/libaa.so: $@{wildcard aa/*.o@}
14511 bb/lib/libbb.so: $@{wildcard bb/*.o@}
14512 cc/lib/libcc.so: $@{wildcard cc/*.o@}
14513
14514 # Make sure all of the shared libraries are in the path before starting the
14515 # program
14516 run::
14517     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
14518
14519 clean::
14520     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
14521     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
14522     $@{RM@} $@{CSC_LIST:%=%/*.o@}
14523     $@{RM@} *.o *.ali $@{MAIN@}
14524 @end smallexample
14525
14526 @node Automatically Creating a List of Directories
14527 @section Automatically Creating a List of Directories
14528
14529 @noindent
14530 In most makefiles, you will have to specify a list of directories, and
14531 store it in a variable. For small projects, it is often easier to
14532 specify each of them by hand, since you then have full control over what
14533 is the proper order for these directories, which ones should be
14534 included...
14535
14536 However, in larger projects, which might involve hundreds of
14537 subdirectories, it might be more convenient to generate this list
14538 automatically.
14539
14540 The example below presents two methods. The first one, although less
14541 general, gives you more control over the list. It involves wildcard
14542 characters, that are automatically expanded by @code{make}. Its
14543 shortcoming is that you need to explicitly specify some of the
14544 organization of your project, such as for instance the directory tree
14545 depth, whether some directories are found in a separate tree,...
14546
14547 The second method is the most general one. It requires an external
14548 program, called @code{find}, which is standard on all Unix systems. All
14549 the directories found under a given root directory will be added to the
14550 list.
14551
14552 @smallexample
14553 @iftex
14554 @leftskip=0cm
14555 @font@heightrm=cmr8
14556 @heightrm
14557 @end iftex
14558 # The examples below are based on the following directory hierarchy:
14559 # All the directories can contain any number of files
14560 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
14561 #                       ->  ab
14562 #                       ->  ac
14563 #                ->  b  ->  ba  ->  baa
14564 #                       ->  bb
14565 #                       ->  bc
14566 # This Makefile creates a variable called DIRS, that can be reused any time
14567 # you need this list (see the other examples in this section)
14568
14569 # The root of your project's directory hierarchy
14570 ROOT_DIRECTORY=.
14571
14572 ####
14573 # First method: specify explicitly the list of directories
14574 # This allows you to specify any subset of all the directories you need.
14575 ####
14576
14577 DIRS := a/aa/ a/ab/ b/ba/
14578
14579 ####
14580 # Second method: use wildcards
14581 # Note that the argument(s) to wildcard below should end with a '/'.
14582 # Since wildcards also return file names, we have to filter them out
14583 # to avoid duplicate directory names.
14584 # We thus use make's @code{dir} and @code{sort} functions.
14585 # It sets DIRs to the following value (note that the directories aaa and baa
14586 # are not given, unless you change the arguments to wildcard).
14587 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
14588 ####
14589
14590 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ $@{ROOT_DIRECTORY@}/*/*/@}@}@}
14591
14592 ####
14593 # Third method: use an external program
14594 # This command is much faster if run on local disks, avoiding NFS slowdowns.
14595 # This is the most complete command: it sets DIRs to the following value:
14596 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
14597 ####
14598
14599 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
14600
14601 @end smallexample
14602
14603 @node Generating the Command Line Switches
14604 @section Generating the Command Line Switches
14605
14606 @noindent
14607 Once you have created the list of directories as explained in the
14608 previous section (@pxref{Automatically Creating a List of Directories}),
14609 you can easily generate the command line arguments to pass to gnatmake.
14610
14611 For the sake of completeness, this example assumes that the source path
14612 is not the same as the object path, and that you have two separate lists
14613 of directories.
14614
14615 @smallexample
14616 # see "Automatically creating a list of directories" to create
14617 # these variables
14618 SOURCE_DIRS=
14619 OBJECT_DIRS=
14620
14621 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
14622 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
14623
14624 all:
14625         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
14626 @end smallexample
14627
14628 @node Overcoming Command Line Length Limits
14629 @section Overcoming Command Line Length Limits
14630
14631 @noindent
14632 One problem that might be encountered on big projects is that many
14633 operating systems limit the length of the command line. It is thus hard to give
14634 gnatmake the list of source and object directories.
14635
14636 This example shows how you can set up environment variables, which will
14637 make @code{gnatmake} behave exactly as if the directories had been
14638 specified on the command line, but have a much higher length limit (or
14639 even none on most systems).
14640
14641 It assumes that you have created a list of directories in your Makefile,
14642 using one of the methods presented in
14643 @ref{Automatically Creating a List of Directories}.
14644 For the sake of completeness, we assume that the object
14645 path (where the ALI files are found) is different from the sources patch.
14646
14647 Note a small trick in the Makefile below: for efficiency reasons, we
14648 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
14649 expanded immediately by @code{make}. This way we overcome the standard
14650 make behavior which is to expand the variables only when they are
14651 actually used.
14652
14653 @smallexample
14654 @iftex
14655 @leftskip=0cm
14656 @font@heightrm=cmr8
14657 @heightrm
14658 @end iftex
14659 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
14660 # This is the same thing as putting the -I arguments on the command line.
14661 # (the equivalent of using -aI on the command line would be to define
14662 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
14663 # You can of course have different values for these variables.
14664 #
14665 # Note also that we need to keep the previous values of these variables, since
14666 # they might have been set before running 'make' to specify where the GNAT
14667 # library is installed.
14668
14669 # see "Automatically creating a list of directories" to create these
14670 # variables
14671 SOURCE_DIRS=
14672 OBJECT_DIRS=
14673
14674 empty:=
14675 space:=$@{empty@} $@{empty@}
14676 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
14677 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
14678 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
14679 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
14680 export ADA_INCLUDE_PATH
14681 export ADA_OBJECT_PATH
14682
14683 all:
14684         gnatmake main_unit
14685 @end smallexample
14686
14687
14688 @node Finding Memory Problems with GNAT Debug Pool
14689 @chapter Finding Memory Problems with GNAT Debug Pool
14690 @findex Debug Pool
14691 @cindex storage, pool, memory corruption
14692
14693 @noindent
14694 The use of unchecked deallocation and unchecked conversion can easily
14695 lead to incorrect memory references. The problems generated by such
14696 references are usually difficult to tackle because the symptoms can be
14697 very remote from the origin of the problem. In such cases, it is
14698 very helpful to detect the problem as early as possible. This is the
14699 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
14700
14701 @noindent
14702 In order to use the GNAT specific debugging pool, the user must
14703 associate a debug pool object with each of the access types that may be
14704 related to suspected memory problems. See Ada Reference Manual
14705 13.11.
14706 @smallexample
14707 @b{type} Ptr @b{is} @b{access} Some_Type;
14708 Pool : GNAT.Debug_Pools.Debug_Pool;
14709 @b{for} Ptr'Storage_Pool @b{use} Pool;
14710 @end smallexample
14711
14712 @code{GNAT.Debug_Pools} is derived from of a GNAT-specific kind of
14713 pool: the Checked_Pool. Such pools, like standard Ada storage pools,
14714 allow the user to redefine allocation and deallocation strategies. They
14715 also provide a checkpoint for each dereference, through the use of
14716 the primitive operation @code{Dereference} which is implicitly called at
14717 each dereference of an access value.
14718
14719 Once an access type has been associated with a debug pool, operations on
14720 values of the type may raise four distinct exceptions,
14721 which correspond to four potential kinds of memory corruption:
14722 @itemize @bullet
14723 @item
14724 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
14725 @item
14726 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
14727 @item
14728 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
14729 @item
14730 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
14731 @end itemize
14732
14733 @noindent
14734 For types associated with a Debug_Pool, dynamic allocation is performed using
14735 the standard
14736 GNAT allocation routine. References to all allocated chunks of memory
14737 are kept in an internal dictionary. The deallocation strategy consists
14738 in not releasing the memory to the underlying system but rather to fill
14739 it with a memory pattern easily recognizable during debugging sessions:
14740 The memory pattern is the old IBM hexadecimal convention: 16#DEADBEEF#.
14741 Upon each dereference, a check is made that the access value denotes a properly
14742 allocated memory location. Here is a complete example of use of
14743 @code{Debug_Pools}, that includes typical instances of  memory corruption:
14744 @smallexample
14745 @iftex
14746 @leftskip=0cm
14747 @end iftex
14748 @b{with} Gnat.Io; @b{use} Gnat.Io;
14749 @b{with} Unchecked_Deallocation;
14750 @b{with} Unchecked_Conversion;
14751 @b{with} GNAT.Debug_Pools;
14752 @b{with} System.Storage_Elements;
14753 @b{with} Ada.Exceptions; @b{use} Ada.Exceptions;
14754 @b{procedure} Debug_Pool_Test @b{is}
14755
14756    @b{type} T @b{is} @b{access} Integer;
14757    @b{type} U @b{is} @b{access} @b{all} T;
14758
14759    P : GNAT.Debug_Pools.Debug_Pool;
14760    @b{for} T'Storage_Pool @b{use} P;
14761
14762    @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T);
14763    @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T);
14764    A, B : @b{aliased} T;
14765
14766    @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line);
14767
14768 @b{begin}
14769    Info (P);
14770    A := @b{new} Integer;
14771    B := @b{new} Integer;
14772    B := A;
14773    Info (P);
14774    Free (A);
14775    @b{begin}
14776       Put_Line (Integer'Image(B.@b{all}));
14777    @b{exception}
14778       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
14779    @b{end};
14780    @b{begin}
14781       Free (B);
14782    @b{exception}
14783       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
14784    @b{end};
14785    B := UC(A'Access);
14786    @b{begin}
14787       Put_Line (Integer'Image(B.@b{all}));
14788    @b{exception}
14789       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
14790    @b{end};
14791    @b{begin}
14792       Free (B);
14793    @b{exception}
14794       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
14795    @b{end};
14796    Info (P);
14797 @b{end} Debug_Pool_Test;
14798 @end smallexample
14799 @noindent
14800 The debug pool mechanism provides the following precise diagnostics on the
14801 execution of this erroneous program:
14802 @smallexample
14803 Debug Pool info:
14804   Total allocated bytes :  0
14805   Total deallocated bytes :  0
14806   Current Water Mark:  0
14807   High Water Mark:  0
14808
14809 Debug Pool info:
14810   Total allocated bytes :  8
14811   Total deallocated bytes :  0
14812   Current Water Mark:  8
14813   High Water Mark:  8
14814
14815 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
14816 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
14817 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
14818 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
14819 Debug Pool info:
14820   Total allocated bytes :  8
14821   Total deallocated bytes :  4
14822   Current Water Mark:  4
14823   High Water Mark:  8
14824
14825 @end smallexample
14826
14827 @node Creating Sample Bodies Using gnatstub
14828 @chapter Creating Sample Bodies Using @code{gnatstub}
14829 @findex gnatstub
14830
14831 @noindent
14832 @code{gnatstub} creates body stubs, that is, empty but compilable bodies
14833 for library unit declarations.
14834
14835 To create a body stub, @code{gnatstub} has to compile the library
14836 unit declaration. Therefore, bodies can be created only for legal
14837 library units. Moreover, if a library unit depends semantically upon
14838 units located outside the current directory, you have to provide
14839 the source search path when calling @code{gnatstub}, see the description
14840 of @code{gnatstub} switches below.
14841
14842 @menu
14843 * Running gnatstub::
14844 * Switches for gnatstub::
14845 @end menu
14846
14847 @node Running gnatstub
14848 @section Running @code{gnatstub}
14849
14850 @noindent
14851 @code{gnatstub} has the command-line interface of the form
14852
14853 @smallexample
14854 $ gnatstub [switches] filename [directory]
14855 @end smallexample
14856
14857 @noindent
14858 where
14859 @table @code
14860 @item filename
14861 is the name of the source file that contains a library unit declaration
14862 for which a body must be created. This name should follow the GNAT file name
14863 conventions. No crunching is allowed for this file name. The file
14864 name may contain the path information.
14865
14866 @item directory
14867 indicates the directory to place a body stub (default is the
14868 current directory)
14869
14870 @item switches
14871 is an optional sequence of switches as described in the next section
14872 @end table
14873
14874 @node Switches for gnatstub
14875 @section Switches for @code{gnatstub}
14876
14877 @table @code
14878
14879 @item -f
14880 If the destination directory already contains a file with a name of the body file
14881 for the argument spec file, replace it with the generated body stub.
14882
14883 @item -hs
14884 Put the comment header (i.e. all the comments preceding the
14885 compilation unit) from the source of the library unit declaration
14886 into the body stub.
14887
14888 @item -hg
14889 Put a sample comment header into the body stub.
14890
14891 @item -IDIR
14892 @itemx -I-
14893 These switches have the same meaning as in calls to gcc.
14894 They define the source search path in the call to gcc issued
14895 by @code{gnatstub} to compile an argument source file.
14896
14897 @item -i@var{n}
14898 (@var{n} is a decimal natural number). Set the indentation level in the
14899 generated body sample to n, '-i0' means "no indentation",
14900 the default indentation is 3.
14901
14902 @item -k
14903 Do not remove the tree file (i.e. the snapshot of the compiler internal
14904 structures used by @code{gnatstub}) after creating the body stub.
14905
14906 @item -l@var{n}
14907 (@var{n} is a decimal positive number) Set the maximum line length in the
14908 body stub to n, the default is 78.
14909
14910 @item -q
14911 Quiet mode: do not generate a confirmation when a body is
14912 successfully created or a message when a body is not required for an
14913 argument unit.
14914
14915 @item -r
14916 Reuse the tree file (if it exists) instead of creating it: instead of
14917 creating the tree file for the library unit declaration, gnatstub
14918 tries to find it in the current directory and use it for creating
14919 a body. If the tree file is not found, no body is created. @code{-r}
14920 also implies @code{-k}, whether or not
14921 @code{-k} is set explicitly.
14922
14923 @item -t
14924 Overwrite the existing tree file: if the current directory already
14925 contains the file which, according to the GNAT file name rules should
14926 be considered as a tree file for the argument source file, gnatstub
14927 will refuse to create the tree file needed to create a body sampler,
14928 unless @code{-t} option is set
14929
14930 @item -v
14931 Verbose mode: generate version information.
14932
14933 @end table
14934
14935 @node Reducing the Size of Ada Executables with gnatelim
14936 @chapter Reducing the Size of Ada Executables with @code{gnatelim}
14937 @findex gnatelim
14938
14939 @menu
14940 * About gnatelim::
14941 * Eliminate Pragma::
14942 * Tree Files::
14943 * Preparing Tree and Bind Files for gnatelim::
14944 * Running gnatelim::
14945 * Correcting the List of Eliminate Pragmas::
14946 * Making Your Executables Smaller::
14947 * Summary of the gnatelim Usage Cycle::
14948 @end menu
14949
14950 @node About gnatelim
14951 @section About @code{gnatelim}
14952
14953 @noindent
14954 When a program shares a set of Ada
14955 packages with other programs, it may happen that this program uses
14956 only a fraction of the subprograms defined in these packages. The code
14957 created for these unused subprograms increases the size of the executable.
14958
14959 @code{gnatelim} tracks unused subprograms in an Ada program and
14960 outputs a list of GNAT-specific @code{Eliminate} pragmas (see next
14961 section) marking all the subprograms that are declared but never called.
14962 By placing the list of @code{Eliminate} pragmas in the GNAT configuration
14963 file @file{gnat.adc} and recompiling your program, you may decrease the
14964 size of its executable, because the compiler will not generate the code
14965 for 'eliminated' subprograms.
14966
14967 @code{gnatelim} needs as its input data a set of tree files
14968 (see @ref{Tree Files}) representing all the components of a program to
14969 process and a bind file for a main subprogram (see
14970 @ref{Preparing Tree and Bind Files for gnatelim}).
14971
14972 @node Eliminate Pragma
14973 @section @code{Eliminate} Pragma
14974 @findex Eliminate
14975
14976 @noindent
14977 The simplified syntax of the Eliminate pragma used by @code{gnatelim} is:
14978
14979 @smallexample
14980 @cartouche
14981 @b{pragma} Eliminate (Library_Unit_Name, Subprogram_Name);
14982 @end cartouche
14983 @end smallexample
14984
14985 @noindent
14986 where
14987 @table @code
14988 @item Library_Unit_Name
14989 full expanded Ada name of a library unit
14990
14991 @item Subprogram_Name
14992 a simple or expanded name of a subprogram declared within this
14993 compilation unit
14994
14995 @end table
14996
14997 @noindent
14998 The effect of an @code{Eliminate} pragma placed in the GNAT configuration
14999 file @file{gnat.adc} is:
15000
15001 @itemize @bullet
15002
15003 @item
15004 If the subprogram @code{Subprogram_Name} is declared within
15005 the library unit @code{Library_Unit_Name}, the compiler will not generate
15006 code for this subprogram. This applies to all overloaded subprograms denoted
15007 by @code{Subprogram_Name}.
15008
15009 @item
15010 If a subprogram marked by the pragma @code{Eliminate} is used (called)
15011 in a program, the compiler will produce an error message in the place where
15012 it is called.
15013 @end itemize
15014
15015 @node Tree Files
15016 @section Tree Files
15017 @cindex Tree file
15018
15019 @noindent
15020 A tree file stores a snapshot of the compiler internal data
15021 structures at the very end of a successful compilation. It contains all the
15022 syntactic and semantic information for the compiled unit and all the
15023 units upon which it depends semantically.
15024 To use tools that make use of tree files, you
15025 need to first produce the right set of tree files.
15026
15027 GNAT produces correct tree files when -gnatt -gnatc options are set
15028 in a gcc call. The tree files have an .adt extension.
15029 Therefore, to produce a tree file for the compilation unit contained in a file
15030 named @file{foo.adb}, you must use the command
15031
15032 @smallexample
15033 $ gcc -c -gnatc -gnatt foo.adb
15034 @end smallexample
15035
15036 @noindent
15037 and you will get the tree file @file{foo.adt}.
15038 compilation.
15039
15040 @node Preparing Tree and Bind Files for gnatelim
15041 @section Preparing Tree and Bind Files for @code{gnatelim}
15042
15043 @noindent
15044 A set of tree files covering the program to be analyzed with
15045 @code{gnatelim} and
15046 the bind file for the main subprogram does not have to
15047 be in the current directory.
15048 '-T' gnatelim option may be used to provide
15049 the search path for tree files, and '-b'
15050 option may be used to point to the bind
15051 file to process (see @ref{Running gnatelim})
15052
15053 If you do not have the appropriate set of tree
15054 files and the right bind file, you
15055 may create them in the current directory using the following procedure.
15056
15057 Let @code{Main_Prog} be the name of a main subprogram, and suppose
15058 this subprogram is in a file named @file{main_prog.adb}.
15059
15060 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
15061 the main subprogram. @code{gnatelim} can work with both Ada and C
15062 bind files; when both are present, it uses the Ada bind file.
15063 The following commands will build the program and create the bind file:
15064
15065 @smallexample
15066 $ gnatmake -c Main_Prog
15067 $ gnatbind main_prog
15068 @end smallexample
15069
15070 @noindent
15071 To create a minimal set of tree files covering the whole program, call
15072 @code{gnatmake} for this program as follows:
15073
15074 @smallexample
15075 $ gnatmake -f -c -gnatc -gnatt Main_Prog
15076 @end smallexample
15077
15078 @noindent
15079 The @code{-c} gnatmake option turns off the bind and link
15080 steps, that are useless anyway because the sources are compiled with
15081 @option{-gnatc} option which turns off code generation.
15082
15083 The @code{-f} gnatmake option forces
15084 recompilation of all the needed sources.
15085
15086 This sequence of actions will create all the data needed by @code{gnatelim}
15087 from scratch and therefore guarantee its consistency. If you would like to
15088 use some existing set of files as @code{gnatelim} output, you must make
15089 sure that the set of files is complete and consistent. You can use the
15090 @code{-m} switch to check if there are missed tree files
15091
15092 Note, that @code{gnatelim} needs neither object nor ALI files.
15093
15094 @node Running gnatelim
15095 @section Running @code{gnatelim}
15096
15097 @noindent
15098 @code{gnatelim} has the following command-line interface:
15099
15100 @smallexample
15101 $ gnatelim [options] name
15102 @end smallexample
15103
15104 @noindent
15105 @code{name} should be a full expanded Ada name of a main subprogram
15106 of a program (partition).
15107
15108 @code{gnatelim} options:
15109
15110 @table @code
15111 @item -q
15112 Quiet mode: by default @code{gnatelim} generates to the standard error
15113 stream a trace of the source file names of the compilation units being
15114 processed. This option turns this trace off.
15115
15116 @item -v
15117 Verbose mode: @code{gnatelim} version information is printed as Ada
15118 comments to the standard output stream.
15119
15120 @item -a
15121 Also look for subprograms from the GNAT run time that can be eliminated.
15122
15123 @item -m
15124 Check if any tree files are missing for an accurate result.
15125
15126 @item -T@var{dir}
15127 When looking for tree files also look in directory @var{dir}
15128
15129 @item -b@var{bind_file}
15130 Specifies @var{bind_file} as the bind file to process. If not set, the name
15131 of the bind file is computed from the full expanded Ada name of a main subprogram.
15132
15133 @item -d@var{x}
15134 Activate internal debugging switches. @var{x} is a letter or digit, or
15135 string of letters or digits, which specifies the type of debugging
15136 mode desired.  Normally these are used only for internal development
15137 or system debugging purposes. You can find full documentation for these
15138 switches in the body of the @code{Gnatelim.Options} unit in the compiler
15139 source file @file{gnatelim-options.adb}.
15140 @end table
15141
15142 @noindent
15143 @code{gnatelim} sends its output to the standard output stream, and all the
15144 tracing and debug information is sent to the standard error stream.
15145 In order to produce a proper GNAT configuration file
15146 @file{gnat.adc}, redirection must be used:
15147
15148 @smallexample
15149 $ gnatelim Main_Prog > gnat.adc
15150 @end smallexample
15151
15152 @noindent
15153 or
15154
15155 @smallexample
15156 $ gnatelim Main_Prog >> gnat.adc
15157 @end smallexample
15158
15159 @noindent
15160 In order to append the @code{gnatelim} output to the existing contents of
15161 @file{gnat.adc}.
15162
15163 @node Correcting the List of Eliminate Pragmas
15164 @section Correcting the List of Eliminate Pragmas
15165
15166 @noindent
15167 In some rare cases it may happen that @code{gnatelim} will try to eliminate
15168 subprograms which are actually called in the program. In this case, the
15169 compiler will generate an error message of the form:
15170
15171 @smallexample
15172 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
15173 @end smallexample
15174
15175 @noindent
15176 You will need to manually remove the wrong @code{Eliminate} pragmas from
15177 the @file{gnat.adc} file. It is advised that you recompile your program
15178 from scratch after that because you need a consistent @file{gnat.adc} file
15179 during the entire compilation.
15180
15181 @node Making Your Executables Smaller
15182 @section Making Your Executables Smaller
15183
15184 @noindent
15185 In order to get a smaller executable for your program you now have to
15186 recompile the program completely with the new @file{gnat.adc} file
15187 created by @code{gnatelim} in your current directory:
15188
15189 @smallexample
15190 $ gnatmake -f Main_Prog
15191 @end smallexample
15192
15193 @noindent
15194 (you will need @code{-f} option for gnatmake to
15195 recompile everything
15196 with the set of pragmas @code{Eliminate} you have obtained with
15197 @code{gnatelim}).
15198
15199 Be aware that the set of @code{Eliminate} pragmas is specific to each
15200 program. It is not recommended to merge sets of @code{Eliminate}
15201 pragmas created for different programs in one @file{gnat.adc} file.
15202
15203 @node Summary of the gnatelim Usage Cycle
15204 @section Summary of the gnatelim Usage Cycle
15205
15206 @noindent
15207 Here is a quick summary of the steps to be taken in order to reduce
15208 the size of your executables with @code{gnatelim}. You may use
15209 other GNAT options to control the optimization level,
15210 to produce the debugging information, to set search path, etc.
15211
15212 @enumerate
15213 @item
15214 Produce a bind file and a set of tree files
15215
15216 @smallexample
15217 $ gnatmake -c Main_Prog
15218 $ gnatbind main_prog
15219 $ gnatmake -f -c -gnatc -gnatt Main_Prog
15220 @end smallexample
15221
15222 @item
15223 Generate a list of @code{Eliminate} pragmas
15224 @smallexample
15225 $ gnatelim Main_Prog >[>] gnat.adc
15226 @end smallexample
15227
15228 @item
15229 Recompile the application
15230
15231 @smallexample
15232 $ gnatmake -f Main_Prog
15233 @end smallexample
15234
15235 @end enumerate
15236
15237 @node Other Utility Programs
15238 @chapter Other Utility Programs
15239
15240 @noindent
15241 This chapter discusses some other utility programs available in the Ada
15242 environment.
15243
15244 @menu
15245 * Using Other Utility Programs with GNAT::
15246 * The gnatpsta Utility Program::
15247 * The External Symbol Naming Scheme of GNAT::
15248 * Ada Mode for Glide::
15249 * Converting Ada Files to html with gnathtml::
15250 * Installing gnathtml::
15251 @end menu
15252
15253 @node Using Other Utility Programs with GNAT
15254 @section Using Other Utility Programs with GNAT
15255
15256 @noindent
15257 The object files generated by GNAT are in standard system format and in
15258 particular the debugging information uses this format. This means
15259 programs generated by GNAT can be used with existing utilities that
15260 depend on these formats.
15261
15262 In general, any utility program that works with C will also often work with
15263 Ada programs generated by GNAT. This includes software utilities such as
15264 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
15265 as Purify.
15266
15267 @node The gnatpsta Utility Program
15268 @section The @code{gnatpsta} Utility Program
15269
15270 @noindent
15271 Many of the definitions in package Standard are implementation-dependent.
15272 However, the source of this package does not exist as an Ada source
15273 file, so these values cannot be determined by inspecting the source.
15274 They can be determined by examining in detail the coding of
15275 @file{cstand.adb} which creates the image of Standard in the compiler,
15276 but this is awkward and requires a great deal of internal knowledge
15277 about the system.
15278
15279 The @code{gnatpsta} utility is designed to deal with this situation.
15280 It is an Ada program that dynamically determines the
15281 values of all the relevant parameters in Standard, and prints them
15282 out in the form of an Ada source listing for Standard, displaying all
15283 the values of interest. This output is generated to
15284 @file{stdout}.
15285
15286 To determine the value of any parameter in package Standard, simply
15287 run @code{gnatpsta} with no qualifiers or arguments, and examine
15288 the output. This is preferable to consulting documentation, because
15289 you know that the values you are getting are the actual ones provided
15290 by the executing system.
15291
15292 @node The External Symbol Naming Scheme of GNAT
15293 @section The External Symbol Naming Scheme of GNAT
15294
15295 @noindent
15296 In order to interpret the output from GNAT, when using tools that are
15297 originally intended for use with other languages, it is useful to
15298 understand the conventions used to generate link names from the Ada
15299 entity names.
15300
15301 All link names are in all lowercase letters. With the exception of library
15302 procedure names, the mechanism used is simply to use the full expanded
15303 Ada name with dots replaced by double underscores. For example, suppose
15304 we have the following package spec:
15305
15306 @smallexample
15307 @group
15308 @cartouche
15309 @b{package} QRS @b{is}
15310    MN : Integer;
15311 @b{end} QRS;
15312 @end cartouche
15313 @end group
15314 @end smallexample
15315
15316 @noindent
15317 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
15318 the corresponding link name is @code{qrs__mn}.
15319 @findex Export
15320 Of course if a @code{pragma Export} is used this may be overridden:
15321
15322 @smallexample
15323 @group
15324 @cartouche
15325 @b{package} Exports @b{is}
15326    Var1 : Integer;
15327    @b{pragma} Export (Var1, C, External_Name => "var1_name");
15328    Var2 : Integer;
15329    @b{pragma} Export (Var2, C, Link_Name => "var2_link_name");
15330 @b{end} Exports;
15331 @end cartouche
15332 @end group
15333 @end smallexample
15334
15335 @noindent
15336 In this case, the link name for @var{Var1} is whatever link name the
15337 C compiler would assign for the C function @var{var1_name}. This typically
15338 would be either @var{var1_name} or @var{_var1_name}, depending on operating
15339 system conventions, but other possibilities exist. The link name for
15340 @var{Var2} is @var{var2_link_name}, and this is not operating system
15341 dependent.
15342
15343 @findex _main
15344 One exception occurs for library level procedures. A potential ambiguity
15345 arises between the required name @code{_main} for the C main program,
15346 and the name we would otherwise assign to an Ada library level procedure
15347 called @code{Main} (which might well not be the main program).
15348
15349 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
15350 names. So if we have a library level procedure such as
15351
15352 @smallexample
15353 @group
15354 @cartouche
15355 @b{procedure} Hello (S : String);
15356 @end cartouche
15357 @end group
15358 @end smallexample
15359
15360 @noindent
15361 the external name of this procedure will be @var{_ada_hello}.
15362
15363 @node Ada Mode for Glide
15364 @section Ada Mode for @code{Glide}
15365
15366 @noindent
15367 The Glide mode for programming in Ada (both, Ada83 and Ada95) helps the
15368 user in understanding existing code and facilitates writing new code. It
15369 furthermore provides some utility functions for easier integration of
15370 standard Emacs features when programming in Ada.
15371
15372 @subsection General Features:
15373
15374 @itemize @bullet
15375 @item
15376 Full Integrated Development Environment :
15377
15378 @itemize @bullet
15379 @item
15380 support of 'project files' for the configuration (directories,
15381 compilation options,...)
15382
15383 @item
15384 compiling and stepping through error messages.
15385
15386 @item
15387 running and debugging your applications within Glide.
15388 @end itemize
15389
15390 @item
15391 easy to use for beginners by pull-down menus,
15392
15393 @item
15394 user configurable by many user-option variables.
15395 @end itemize
15396
15397 @subsection Ada Mode Features That Help Understanding Code:
15398
15399 @itemize @bullet
15400 @item
15401 functions for easy and quick stepping through Ada code,
15402
15403 @item
15404 getting cross reference information for identifiers (e.g. find the
15405 defining place by a keystroke),
15406
15407 @item
15408 displaying an index menu of types and subprograms and move point to
15409 the chosen one,
15410
15411 @item
15412 automatic color highlighting of the various entities in Ada code.
15413 @end itemize
15414
15415 @subsection Glide Support for Writing Ada Code:
15416
15417 @itemize @bullet
15418 @item
15419 switching between spec and body files with possible
15420 autogeneration of body files,
15421
15422 @item
15423 automatic formating of subprograms parameter lists.
15424
15425 @item
15426 automatic smart indentation according to Ada syntax,
15427
15428 @item
15429 automatic completion of identifiers,
15430
15431 @item
15432 automatic casing of identifiers, keywords, and attributes,
15433
15434 @item
15435 insertion of statement templates,
15436
15437 @item
15438 filling comment paragraphs like filling normal text,
15439 @end itemize
15440
15441 For more information, please refer to the online Glide documentation
15442 available in the Glide --> Help Menu.
15443
15444 @node Converting Ada Files to html with gnathtml
15445 @section Converting Ada Files to html with @code{gnathtml}
15446
15447 @noindent
15448 This @code{Perl} script allows Ada source files to be browsed using
15449 standard Web browsers. For installation procedure, see the section
15450 @xref{Installing gnathtml}.
15451
15452 Ada reserved keywords are highlighted in a bold font and Ada comments in
15453 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
15454 switch to suppress the generation of cross-referencing information, user
15455 defined variables and types will appear in a different color; you will
15456 be able to click on any identifier and go to its declaration.
15457
15458 The command line is as follow:
15459 @smallexample
15460 $ perl gnathtml.pl [switches] ada-files
15461 @end smallexample
15462
15463 You can pass it as many Ada files as you want. @code{gnathtml} will generate
15464 an html file for every ada file, and a global file called @file{index.htm}.
15465 This file is an index of every identifier defined in the files.
15466
15467 The available switches are the following ones :
15468
15469 @table @code
15470 @item -83
15471 @cindex @code{-83} (@code{gnathtml})
15472 Only the subset on the Ada 83 keywords will be highlighted, not the full
15473 Ada 95 keywords set.
15474
15475 @item -cc @var{color}
15476 This option allows you to change the color used for comments. The default
15477 value is green. The color argument can be any name accepted by html.
15478
15479 @item -d
15480 @cindex @code{-d} (@code{gnathtml})
15481 If the ada files depend on some other files (using for instance the
15482 @code{with} command, the latter will also be converted to html.
15483 Only the files in the user project will be converted to html, not the files
15484 in the run-time library itself.
15485
15486 @item -D
15487 This command is the same as -d above, but @code{gnathtml} will also look
15488 for files in the run-time library, and generate html files for them.
15489
15490 @item -f
15491 @cindex @code{-f} (@code{gnathtml})
15492 By default, gnathtml will generate html links only for global entities
15493 ('with'ed units, global variables and types,...). If you specify the
15494 @code{-f} on the command line, then links will be generated for local
15495 entities too.
15496
15497 @item -l @var{number}
15498 @cindex @code{-l} (@code{gnathtml})
15499 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
15500 will number the html files every @var{number} line.
15501
15502 @item -I @var{dir}
15503 @cindex @code{-I} (@code{gnathtml})
15504 Specify a directory to search for library files (@file{.ali} files) and
15505 source files. You can provide several -I switches on the command line,
15506 and the directories will be parsed in the order of the command line.
15507
15508 @item -o @var{dir}
15509 @cindex @code{-o} (@code{gnathtml})
15510 Specify the output directory for html files. By default, gnathtml will
15511 saved the generated html files in a subdirectory named @file{html/}.
15512
15513 @item -p @var{file}
15514 @cindex @code{-p} (@code{gnathtml})
15515 If you are using Emacs and the most recent Emacs Ada mode, which provides
15516 a full Integrated Development Environment for compiling, checking,
15517 running and debugging applications, you may be using @file{.adp} files
15518 to give the directories where Emacs can find sources and object files.
15519
15520 Using this switch, you can tell gnathtml to use these files. This allows
15521 you to get an html version of your application, even if it is spread
15522 over multiple directories.
15523
15524 @item -sc @var{color}
15525 @cindex @code{-sc} (@code{gnathtml})
15526 This option allows you to change the color used for symbol definitions.
15527 The default value is red. The color argument can be any name accepted by html.
15528
15529 @item -t @var{file}
15530 @cindex @code{-t} (@code{gnathtml})
15531 This switch provides the name of a file. This file contains a list of
15532 file names to be converted, and the effect is exactly as though they had
15533 appeared explicitly on the command line. This
15534 is the recommended way to work around the command line length limit on some
15535 systems.
15536
15537 @end table
15538
15539 @node Installing gnathtml
15540 @section Installing @code{gnathtml}
15541
15542 @noindent
15543 @code{Perl} needs to be installed on your machine to run this script.
15544 @code{Perl} is freely available for almost every architecture and
15545 Operating System via the Internet.
15546
15547 On Unix systems, you  may want to modify  the  first line of  the script
15548 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
15549 is. The syntax of this line is :
15550 @smallexample
15551 #!full_path_name_to_perl
15552 @end smallexample
15553
15554 @noindent
15555 Alternatively, you may run the script using the following command line:
15556
15557 @smallexample
15558 $ perl gnathtml.pl [switches] files
15559 @end smallexample
15560
15561
15562 @node Running and Debugging Ada Programs
15563 @chapter Running and Debugging Ada Programs
15564 @cindex Debugging
15565
15566 @noindent
15567 This chapter discusses how to debug Ada programs. An incorrect Ada program
15568 may be handled in three ways by the GNAT compiler:
15569
15570 @enumerate
15571 @item
15572 The illegality may be a violation of the static semantics of Ada. In
15573 that case GNAT diagnoses the constructs in the program that are illegal.
15574 It is then a straightforward matter for the user to modify those parts of
15575 the program.
15576
15577 @item
15578 The illegality may be a violation of the dynamic semantics of Ada. In
15579 that case the program compiles and executes, but may generate incorrect
15580 results, or may terminate abnormally with some exception.
15581
15582 @item
15583 When presented with a program that contains convoluted errors, GNAT
15584 itself may terminate abnormally without providing full diagnostics on
15585 the incorrect user program.
15586 @end enumerate
15587
15588 @menu
15589 * The GNAT Debugger GDB::
15590 * Running GDB::
15591 * Introduction to GDB Commands::
15592 * Using Ada Expressions::
15593 * Calling User-Defined Subprograms::
15594 * Using the Next Command in a Function::
15595 * Ada Exceptions::
15596 * Ada Tasks::
15597 * Debugging Generic Units::
15598 * GNAT Abnormal Termination or Failure to Terminate::
15599 * Naming Conventions for GNAT Source Files::
15600 * Getting Internal Debugging Information::
15601 * Stack Traceback::
15602 @end menu
15603
15604 @cindex Debugger
15605 @findex gdb
15606
15607 @node The GNAT Debugger GDB
15608 @section The GNAT Debugger GDB
15609
15610 @noindent
15611 @code{GDB} is a general purpose, platform-independent debugger that
15612 can be used to debug mixed-language programs compiled with @code{GCC},
15613 and in particular is capable of debugging Ada programs compiled with
15614 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
15615 complex Ada data structures.
15616
15617 The manual @cite{Debugging with GDB}
15618 contains full details on the usage of @code{GDB}, including a section on
15619 its usage on programs. This manual should be consulted for full
15620 details. The section that follows is a brief introduction to the
15621 philosophy and use of @code{GDB}.
15622
15623 When GNAT programs are compiled, the compiler optionally writes debugging
15624 information into the generated object file, including information on
15625 line numbers, and on declared types and variables. This information is
15626 separate from the generated code. It makes the object files considerably
15627 larger, but it does not add to the size of the actual executable that
15628 will be loaded into memory, and has no impact on run-time performance. The
15629 generation of debug information is triggered by the use of the
15630 -g switch in the gcc or gnatmake command used to carry out
15631 the compilations. It is important to emphasize that the use of these
15632 options does not change the generated code.
15633
15634 The debugging information is written in standard system formats that
15635 are used by many tools, including debuggers and profilers. The format
15636 of the information is typically designed to describe C types and
15637 semantics, but GNAT implements a translation scheme which allows full
15638 details about Ada types and variables to be encoded into these
15639 standard C formats. Details of this encoding scheme may be found in
15640 the file exp_dbug.ads in the GNAT source distribution. However, the
15641 details of this encoding are, in general, of no interest to a user,
15642 since @code{GDB} automatically performs the necessary decoding.
15643
15644 When a program is bound and linked, the debugging information is
15645 collected from the object files, and stored in the executable image of
15646 the program. Again, this process significantly increases the size of
15647 the generated executable file, but it does not increase the size of
15648 the executable program itself. Furthermore, if this program is run in
15649 the normal manner, it runs exactly as if the debug information were
15650 not present, and takes no more actual memory.
15651
15652 However, if the program is run under control of @code{GDB}, the
15653 debugger is activated.  The image of the program is loaded, at which
15654 point it is ready to run.  If a run command is given, then the program
15655 will run exactly as it would have if @code{GDB} were not present. This
15656 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
15657 entirely non-intrusive until a breakpoint is encountered.  If no
15658 breakpoint is ever hit, the program will run exactly as it would if no
15659 debugger were present. When a breakpoint is hit, @code{GDB} accesses
15660 the debugging information and can respond to user commands to inspect
15661 variables, and more generally to report on the state of execution.
15662
15663 @node Running GDB
15664 @section Running GDB
15665
15666
15667 Please refer to the debugging section of the chapter specific to your
15668 cross environment at the end of this manual.
15669
15670 @node Introduction to GDB Commands
15671 @section Introduction to GDB Commands
15672
15673 @noindent
15674 @code{GDB} contains a large repertoire of commands. The manual
15675 @cite{Debugging with GDB}
15676 includes extensive documentation on the use
15677 of these commands, together with examples of their use. Furthermore,
15678 the command @var{help} invoked from within @code{GDB} activates a simple help
15679 facility which summarizes the available commands and their options.
15680 In this section we summarize a few of the most commonly
15681 used commands to give an idea of what @code{GDB} is about. You should create
15682 a simple program with debugging information and experiment with the use of
15683 these @code{GDB} commands on the program as you read through the
15684 following section.
15685
15686 @table @code
15687 @item set args @var{arguments}
15688 The @var{arguments} list above is a list of arguments to be passed to
15689 the program on a subsequent run command, just as though the arguments
15690 had been entered on a normal invocation of the program. The @code{set args}
15691 command is not needed if the program does not require arguments.
15692
15693 @item run
15694 The @code{run} command causes execution of the program to start from
15695 the beginning. If the program is already running, that is to say if
15696 you are currently positioned at a breakpoint, then a prompt will ask
15697 for confirmation that you want to abandon the current execution and
15698 restart.
15699
15700 @item breakpoint @var{location}
15701 The breakpoint command sets a breakpoint, that is to say a point at which
15702 execution will halt and @code{GDB} will await further
15703 commands. @var{location} is
15704 either a line number within a file, given in the format @code{file:linenumber},
15705 or it is the name of a subprogram. If you request that a breakpoint be set on
15706 a subprogram that is overloaded, a prompt will ask you to specify on which of
15707 those subprograms you want to breakpoint. You can also
15708 specify that all of them should be breakpointed. If the program is run
15709 and execution encounters the breakpoint, then the program
15710 stops and @code{GDB} signals that the breakpoint was encountered by
15711 printing the line of code before which the program is halted.
15712
15713 @item breakpoint exception @var{name}
15714 A special form of the breakpoint command which breakpoints whenever
15715 exception @var{name} is raised.
15716 If @var{name} is omitted,
15717 then a breakpoint will occur when any exception is raised.
15718
15719 @item print @var{expression}
15720 This will print the value of the given expression. Most simple
15721 Ada expression formats are properly handled by @code{GDB}, so the expression
15722 can contain function calls, variables, operators, and attribute references.
15723
15724 @item continue
15725 Continues execution following a breakpoint, until the next breakpoint or the
15726 termination of the program.
15727
15728 @item step
15729 Executes a single line after a breakpoint. If the next statement is a subprogram
15730 call, execution continues into (the first statement of) the
15731 called subprogram.
15732
15733 @item next
15734 Executes a single line. If this line is a subprogram call, executes and
15735 returns from the call.
15736
15737 @item list
15738 Lists a few lines around the current source location. In practice, it
15739 is usually more convenient to have a separate edit window open with the
15740 relevant source file displayed. Successive applications of this command
15741 print subsequent lines. The command can be given an argument which is a
15742 line number, in which case it displays a few lines around the specified one.
15743
15744 @item backtrace
15745 Displays a backtrace of the call chain. This command is typically
15746 used after a breakpoint has occurred, to examine the sequence of calls that
15747 leads to the current breakpoint. The display includes one line for each
15748 activation record (frame) corresponding to an active subprogram.
15749
15750 @item up
15751 At a breakpoint, @code{GDB} can display the values of variables local
15752 to the current frame. The command @code{up} can be used to
15753 examine the contents of other active frames, by moving the focus up
15754 the stack, that is to say from callee to caller, one frame at a time.
15755
15756 @item down
15757 Moves the focus of @code{GDB} down from the frame currently being
15758 examined to the frame of its callee (the reverse of the previous command),
15759
15760 @item frame @var{n}
15761 Inspect the frame with the given number. The value 0 denotes the frame
15762 of the current breakpoint, that is to say the top of the call stack.
15763
15764 @end table
15765
15766 The above list is a very short introduction to the commands that
15767 @code{GDB} provides. Important additional capabilities, including conditional
15768 breakpoints, the ability to execute command sequences on a breakpoint,
15769 the ability to debug at the machine instruction level and many other
15770 features are described in detail in @cite{Debugging with GDB}.
15771 Note that most commands can be abbreviated
15772 (for example, c for continue, bt for backtrace).
15773
15774 @node Using Ada Expressions
15775 @section Using Ada Expressions
15776 @cindex Ada expressions
15777
15778 @noindent
15779 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
15780 extensions. The philosophy behind the design of this subset is
15781
15782 @itemize @bullet
15783 @item
15784 That @code{GDB} should provide basic literals and access to operations for
15785 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
15786 leaving more sophisticated computations to subprograms written into the
15787 program (which therefore may be called from @code{GDB}).
15788
15789 @item
15790 That type safety and strict adherence to Ada language restrictions
15791 are not particularly important to the @code{GDB} user.
15792
15793 @item
15794 That brevity is important to the @code{GDB} user.
15795 @end itemize
15796
15797 Thus, for brevity, the debugger acts as if there were
15798 implicit @code{with} and @code{use} clauses in effect for all user-written
15799 packages, thus making it unnecessary to fully qualify most names with
15800 their packages, regardless of context. Where this causes ambiguity,
15801 @code{GDB} asks the user's intent.
15802
15803 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
15804
15805 @node Calling User-Defined Subprograms
15806 @section Calling User-Defined Subprograms
15807
15808 @noindent
15809 An important capability of @code{GDB} is the ability to call user-defined
15810 subprograms while debugging. This is achieved simply by entering
15811 a subprogram call statement in the form:
15812
15813 @smallexample
15814 call subprogram-name (parameters)
15815 @end smallexample
15816
15817 @noindent
15818 The keyword @code{call} can be omitted in the normal case where the
15819 @code{subprogram-name} does not coincide with any of the predefined
15820 @code{GDB} commands.
15821
15822 The effect is to invoke the given subprogram, passing it the
15823 list of parameters that is supplied. The parameters can be expressions and
15824 can include variables from the program being debugged. The
15825 subprogram must be defined
15826 at the library level within your program, and @code{GDB} will call the
15827 subprogram within the environment of your program execution (which
15828 means that the subprogram is free to access or even modify variables
15829 within your program).
15830
15831 The most important use of this facility is in allowing the inclusion of
15832 debugging routines that are tailored to particular data structures
15833 in your program. Such debugging routines can be written to provide a suitably
15834 high-level description of an abstract type, rather than a low-level dump
15835 of its physical layout. After all, the standard
15836 @code{GDB print} command only knows the physical layout of your
15837 types, not their abstract meaning. Debugging routines can provide information
15838 at the desired semantic level and are thus enormously useful.
15839
15840 For example, when debugging GNAT itself, it is crucial to have access to
15841 the contents of the tree nodes used to represent the program internally.
15842 But tree nodes are represented simply by an integer value (which in turn
15843 is an index into a table of nodes).
15844 Using the @code{print} command on a tree node would simply print this integer
15845 value, which is not very useful. But the PN routine (defined in file
15846 treepr.adb in the GNAT sources) takes a tree node as input, and displays
15847 a useful high level representation of the tree node, which includes the
15848 syntactic category of the node, its position in the source, the integers
15849 that denote descendant nodes and parent node, as well as varied
15850 semantic information. To study this example in more detail, you might want to
15851 look at the body of the PN procedure in the stated file.
15852
15853 @node Using the Next Command in a Function
15854 @section Using the Next Command in a Function
15855
15856 @noindent
15857 When you use the @code{next} command in a function, the current source
15858 location will advance to the next statement as usual. A special case
15859 arises in the case of a @code{return} statement.
15860
15861 Part of the code for a return statement is the "epilog" of the function.
15862 This is the code that returns to the caller. There is only one copy of
15863 this epilog code, and it is typically associated with the last return
15864 statement in the function if there is more than one return. In some
15865 implementations, this epilog is associated with the first statement
15866 of the function.
15867
15868 The result is that if you use the @code{next} command from a return
15869 statement that is not the last return statement of the function you
15870 may see a strange apparent jump to the last return statement or to
15871 the start of the function. You should simply ignore this odd jump.
15872 The value returned is always that from the first return statement
15873 that was stepped through.
15874
15875 @node Ada Exceptions
15876 @section Breaking on Ada Exceptions
15877 @cindex Exceptions
15878
15879 @noindent
15880 You can set breakpoints that trip when your program raises
15881 selected exceptions.
15882
15883 @table @code
15884 @item break exception
15885 Set a breakpoint that trips whenever (any task in the) program raises
15886 any exception.
15887
15888 @item break exception @var{name}
15889 Set a breakpoint that trips whenever (any task in the) program raises
15890 the exception @var{name}.
15891
15892 @item break exception unhandled
15893 Set a breakpoint that trips whenever (any task in the) program raises an
15894 exception for which there is no handler.
15895
15896 @item info exceptions
15897 @itemx info exceptions @var{regexp}
15898 The @code{info exceptions} command permits the user to examine all defined
15899 exceptions within Ada programs. With a regular expression, @var{regexp}, as
15900 argument, prints out only those exceptions whose name matches @var{regexp}.
15901 @end table
15902
15903 @node Ada Tasks
15904 @section Ada Tasks
15905 @cindex Tasks
15906
15907 @noindent
15908 @code{GDB} allows the following task-related commands:
15909
15910 @table @code
15911 @item info tasks
15912 This command shows a list of current Ada tasks, as in the following example:
15913
15914 @smallexample
15915 @iftex
15916 @leftskip=0cm
15917 @end iftex
15918 (gdb) info tasks
15919   ID       TID P-ID   Thread Pri State                 Name
15920    1   8088000   0   807e000  15 Child Activation Wait main_task
15921    2   80a4000   1   80ae000  15 Accept/Select Wait    b
15922    3   809a800   1   80a4800  15 Child Activation Wait a
15923 *  4   80ae800   3   80b8000  15 Running               c
15924 @end smallexample
15925
15926 @noindent
15927 In this listing, the asterisk before the first task indicates it to be the
15928 currently running task. The first column lists the task ID that is used
15929 to refer to tasks in the following commands.
15930
15931 @item break @var{linespec} task @var{taskid}
15932 @itemx break @var{linespec} task @var{taskid} if @dots{}
15933 @cindex Breakpoints and tasks
15934 These commands are like the @code{break @dots{} thread @dots{}}.
15935 @var{linespec} specifies source lines.
15936
15937 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
15938 to specify that you only want @code{GDB} to stop the program when a
15939 particular Ada task reaches this breakpoint. @var{taskid} is one of the
15940 numeric task identifiers assigned by @code{GDB}, shown in the first
15941 column of the @samp{info tasks} display.
15942
15943 If you do not specify @samp{task @var{taskid}} when you set a
15944 breakpoint, the breakpoint applies to @emph{all} tasks of your
15945 program.
15946
15947 You can use the @code{task} qualifier on conditional breakpoints as
15948 well; in this case, place @samp{task @var{taskid}} before the
15949 breakpoint condition (before the @code{if}).
15950
15951 @item task @var{taskno}
15952 @cindex Task switching
15953
15954 This command allows to switch to the task referred by @var{taskno}. In
15955 particular, This allows to browse the backtrace of the specified
15956 task. It is advised to switch back to the original task before
15957 continuing execution otherwise the scheduling of the program may be
15958 perturbated.
15959 @end table
15960
15961 @noindent
15962 For more detailed information on the tasking support, see @cite{Debugging with GDB}.
15963
15964 @node Debugging Generic Units
15965 @section Debugging Generic Units
15966 @cindex Debugging Generic Units
15967 @cindex Generics
15968
15969 @noindent
15970 GNAT always uses code expansion for generic instantiation. This means that
15971 each time an instantiation occurs, a complete copy of the original code is
15972 made, with appropriate substitutions of formals by actuals.
15973
15974 It is not possible to refer to the original generic entities in
15975 @code{GDB}, but it is always possible to debug a particular instance of
15976 a generic, by using the appropriate expanded names. For example, if we have
15977
15978 @smallexample
15979 @group
15980 @cartouche
15981 @b{procedure} g @b{is}
15982
15983    @b{generic package} k @b{is}
15984       @b{procedure} kp (v1 : @b{in out} integer);
15985    @b{end} k;
15986
15987    @b{package body} k @b{is}
15988       @b{procedure} kp (v1 : @b{in out} integer) @b{is}
15989       @b{begin}
15990          v1 := v1 + 1;
15991       @b{end} kp;
15992    @b{end} k;
15993
15994    @b{package} k1 @b{is new} k;
15995    @b{package} k2 @b{is new} k;
15996
15997    var : integer := 1;
15998
15999 @b{begin}
16000    k1.kp (var);
16001    k2.kp (var);
16002    k1.kp (var);
16003    k2.kp (var);
16004 @b{end};
16005 @end cartouche
16006 @end group
16007 @end smallexample
16008
16009 @noindent
16010 Then to break on a call to procedure kp in the k2 instance, simply
16011 use the command:
16012
16013 @smallexample
16014 (gdb) break g.k2.kp
16015 @end smallexample
16016
16017 @noindent
16018 When the breakpoint occurs, you can step through the code of the
16019 instance in the normal manner and examine the values of local variables, as for
16020 other units.
16021
16022 @node GNAT Abnormal Termination or Failure to Terminate
16023 @section GNAT Abnormal Termination or Failure to Terminate
16024 @cindex GNAT Abnormal Termination or Failure to Terminate
16025
16026 @noindent
16027 When presented with programs that contain serious errors in syntax
16028 or semantics,
16029 GNAT may on rare occasions  experience problems in operation, such
16030 as aborting with a
16031 segmentation fault or illegal memory access, raising an internal
16032 exception, terminating abnormally, or failing to terminate at all.
16033 In such cases, you can activate
16034 various features of GNAT that can help you pinpoint the construct in your
16035 program that is the likely source of the problem.
16036
16037 The following strategies are presented in increasing order of
16038 difficulty, corresponding to your experience in using GNAT and your
16039 familiarity with compiler internals.
16040
16041 @enumerate
16042 @item
16043 Run @code{gcc} with the @option{-gnatf}. This first
16044 switch causes all errors on a given line to be reported. In its absence,
16045 only the first error on a line is displayed.
16046
16047 The @option{-gnatdO} switch causes errors to be displayed as soon as they
16048 are encountered, rather than after compilation is terminated. If GNAT
16049 terminates prematurely or goes into an infinite loop, the last error
16050 message displayed may help to pinpoint the culprit.
16051
16052 @item
16053 Run @code{gcc} with the @code{-v (verbose)} switch. In this mode,
16054 @code{gcc} produces ongoing information about the progress of the
16055 compilation and provides the name of each procedure as code is
16056 generated. This switch allows you to find which Ada procedure was being
16057 compiled when it encountered a code generation problem.
16058
16059 @item
16060 @cindex @option{-gnatdc} switch
16061 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
16062 switch that does for the front-end what @code{-v} does for the back end.
16063 The system prints the name of each unit, either a compilation unit or
16064 nested unit, as it is being analyzed.
16065 @item
16066 Finally, you can start
16067 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
16068 front-end of GNAT, and can be run independently (normally it is just
16069 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
16070 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
16071 @code{where} command is the first line of attack; the variable
16072 @code{lineno} (seen by @code{print lineno}), used by the second phase of
16073 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
16074 which the execution stopped, and @code{input_file name} indicates the name of
16075 the source file.
16076 @end enumerate
16077
16078 @node Naming Conventions for GNAT Source Files
16079 @section Naming Conventions for GNAT Source Files
16080
16081 @noindent
16082 In order to examine the workings of the GNAT system, the following
16083 brief description of its organization may be helpful:
16084
16085 @itemize @bullet
16086 @item
16087 Files with prefix @file{sc} contain the lexical scanner.
16088
16089 @item
16090 All files prefixed with @file{par} are components of the parser. The
16091 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
16092 parsing of select statements can be found in @file{par-ch9.adb}.
16093
16094 @item
16095 All files prefixed with @file{sem} perform semantic analysis. The
16096 numbers correspond to chapters of the Ada standard. For example, all
16097 issues involving context clauses can be found in @file{sem_ch10.adb}. In
16098 addition, some features of the language require sufficient special processing
16099 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
16100 dynamic dispatching, etc.
16101
16102 @item
16103 All files prefixed with @file{exp} perform normalization and
16104 expansion of the intermediate representation (abstract syntax tree, or AST).
16105 these files use the same numbering scheme as the parser and semantics files.
16106 For example, the construction of record initialization procedures is done in
16107 @file{exp_ch3.adb}.
16108
16109 @item
16110 The files prefixed with @file{bind} implement the binder, which
16111 verifies the consistency of the compilation, determines an order of
16112 elaboration, and generates the bind file.
16113
16114 @item
16115 The files @file{atree.ads} and @file{atree.adb} detail the low-level
16116 data structures used by the front-end.
16117
16118 @item
16119 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
16120 the abstract syntax tree as produced by the parser.
16121
16122 @item
16123 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
16124 all entities, computed during semantic analysis.
16125
16126 @item
16127 Library management issues are dealt with in files with prefix
16128 @file{lib}.
16129
16130 @item
16131 @findex Ada
16132 @cindex Annex A
16133 Ada files with the prefix @file{a-} are children of @code{Ada}, as
16134 defined in Annex A.
16135
16136 @item
16137 @findex Interfaces
16138 @cindex Annex B
16139 Files with prefix @file{i-} are children of @code{Interfaces}, as
16140 defined in Annex B.
16141
16142 @item
16143 @findex System
16144 Files with prefix @file{s-} are children of @code{System}. This includes
16145 both language-defined children and GNAT run-time routines.
16146
16147 @item
16148 @findex GNAT
16149 Files with prefix @file{g-} are children of @code{GNAT}. These are useful
16150 general-purpose packages, fully documented in their specifications. All
16151 the other @file{.c} files are modifications of common @code{gcc} files.
16152 @end itemize
16153
16154 @node Getting Internal Debugging Information
16155 @section Getting Internal Debugging Information
16156
16157 @noindent
16158 Most compilers have internal debugging switches and modes. GNAT
16159 does also, except GNAT internal debugging switches and modes are not
16160 secret. A summary and full description of all the compiler and binder
16161 debug flags are in the file @file{debug.adb}. You must obtain the
16162 sources of the compiler to see the full detailed effects of these flags.
16163
16164 The switches that print the source of the program (reconstructed from
16165 the internal tree) are of general interest for user programs, as are the
16166 options to print
16167 the full internal tree, and the entity table (the symbol table
16168 information). The reconstructed source provides a readable version of the
16169 program after the front-end has completed analysis and  expansion, and is useful
16170 when studying the performance of specific constructs. For example, constraint
16171 checks are indicated, complex aggregates are replaced with loops and
16172 assignments, and tasking primitives are replaced with run-time calls.
16173
16174 @node Stack Traceback
16175 @section Stack Traceback
16176 @cindex traceback
16177 @cindex stack traceback
16178 @cindex stack unwinding
16179
16180 @noindent
16181 Traceback is a mechanism to display the sequence of subprogram calls that
16182 leads to a specified execution point in a program. Often (but not always)
16183 the execution point is an instruction at which an exception has been raised.
16184 This mechanism is also known as @i{stack unwinding} because it obtains
16185 its information by scanning the run-time stack and recovering the activation
16186 records of all active subprograms. Stack unwinding is one of the most
16187 important tools for program debugging.
16188
16189 @noindent
16190 The first entry stored in traceback corresponds to the deepest calling level,
16191 that is to say the subprogram currently executing the instruction
16192 from which we want to obtain the traceback.
16193
16194 @noindent
16195 Note that there is no runtime performance penalty when stack traceback
16196 is enabled and no exception are raised during program execution.
16197
16198 @menu
16199 * Non-Symbolic Traceback::
16200 * Symbolic Traceback::
16201 @end menu
16202
16203 @node Non-Symbolic Traceback
16204 @subsection Non-Symbolic Traceback
16205 @cindex traceback, non-symbolic
16206
16207 @noindent
16208 Note: this feature is not supported on all platforms. See
16209 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
16210 platforms.
16211
16212 @menu
16213 * Tracebacks From an Unhandled Exception::
16214 * Tracebacks From Exception Occurrences (non-symbolic)::
16215 * Tracebacks From Anywhere in a Program (non-symbolic)::
16216 @end menu
16217
16218 @node Tracebacks From an Unhandled Exception
16219 @subsubsection Tracebacks From an Unhandled Exception
16220
16221 @noindent
16222 A runtime non-symbolic traceback is a list of addresses of call instructions.
16223 To enable this feature you must use the @code{-E}
16224 @code{gnatbind}'s option. With this option a stack traceback is stored as part
16225 of exception information. It is possible to retrieve this information using the
16226 standard @code{Ada.Exception.Exception_Information} routine.
16227
16228 @noindent
16229 Let's have a look at a simple example:
16230
16231 @smallexample
16232 @cartouche
16233 @group
16234 procedure STB is
16235
16236    procedure P1 is
16237    begin
16238       raise Constraint_Error;
16239    end P1;
16240
16241    procedure P2 is
16242    begin
16243       P1;
16244    end P2;
16245
16246 begin
16247    P2;
16248 end STB;
16249 @end group
16250 @end cartouche
16251 @end smallexample
16252
16253 @smallexample
16254 $ gnatmake stb -bargs -E
16255 $ stb
16256
16257 Execution terminated by unhandled exception
16258 Exception name: CONSTRAINT_ERROR
16259 Message: stb.adb:5
16260 Call stack traceback locations:
16261 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
16262 @end smallexample
16263
16264 @noindent
16265 As we see the traceback lists a sequence of addresses for the unhandled
16266 exception @code{CONSTAINT_ERROR} raised in procedure P1. It is easy to
16267 guess that this exception come from procedure P1. To translate these
16268 addresses into the source lines where the calls appear, the
16269 @code{addr2line} tool, described below, is invaluable. The use of this tool
16270 requires the program to be compiled with debug information.
16271
16272 @smallexample
16273 $ gnatmake -g stb -bargs -E
16274 $ stb
16275
16276 Execution terminated by unhandled exception
16277 Exception name: CONSTRAINT_ERROR
16278 Message: stb.adb:5
16279 Call stack traceback locations:
16280 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
16281
16282 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
16283    0x4011f1 0x77e892a4
16284
16285 00401373 at d:/stb/stb.adb:5
16286 0040138B at d:/stb/stb.adb:10
16287 0040139C at d:/stb/stb.adb:14
16288 00401335 at d:/stb/b~stb.adb:104
16289 004011C4 at /build/.../crt1.c:200
16290 004011F1 at /build/.../crt1.c:222
16291 77E892A4 in ?? at ??:0
16292 @end smallexample
16293
16294 @noindent
16295 @code{addr2line} has a number of other useful options:
16296
16297 @table @code
16298 @item --functions
16299 to get the function name corresponding to any location
16300
16301 @item --demangle=gnat
16302 to use the @b{gnat} decoding mode for the function names. Note that
16303 for binutils version 2.9.x the option is simply @code{--demangle}.
16304 @end table
16305
16306 @smallexample
16307 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
16308    0x40139c 0x401335 0x4011c4 0x4011f1
16309
16310 00401373 in stb.p1 at d:/stb/stb.adb:5
16311 0040138B in stb.p2 at d:/stb/stb.adb:10
16312 0040139C in stb at d:/stb/stb.adb:14
16313 00401335 in main at d:/stb/b~stb.adb:104
16314 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
16315 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
16316 @end smallexample
16317
16318 @noindent
16319 From this traceback we can see that the exception was raised in
16320 @file{stb.adb} at line 5, which was reached from a procedure call in
16321 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
16322 which contains the call to the main program.
16323 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
16324 and the output will vary from platform to platform.
16325
16326 @noindent
16327 It is also possible to use @code{GDB} with these traceback addresses to debug
16328 the program. For example, we can break at a given code location, as reported
16329 in the stack traceback:
16330
16331 @smallexample
16332 $ gdb -nw stb
16333
16334 (gdb) break *0x401373
16335 Breakpoint 1 at 0x401373: file stb.adb, line 5.
16336 @end smallexample
16337
16338 @noindent
16339 It is important to note that the stack traceback addresses
16340 do not change when debug information is included. This is particularly useful
16341 because it makes it possible to release software without debug information (to
16342 minimize object size), get a field report that includes a stack traceback
16343 whenever an internal bug occurs, and then be able to retrieve the sequence
16344 of calls with the same program compiled with debug information.
16345
16346 @node Tracebacks From Exception Occurrences (non-symbolic)
16347 @subsubsection Tracebacks From Exception Occurrences
16348
16349 @noindent
16350 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
16351 The stack traceback is attached to the exception information string, and can
16352 be retrieved in an exception handler within the Ada program, by means of the
16353 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
16354
16355 @smallexample
16356 @cartouche
16357 @group
16358 with Ada.Text_IO;
16359 with Ada.Exceptions;
16360
16361 procedure STB is
16362
16363    use Ada;
16364    use Ada.Exceptions;
16365
16366    procedure P1 is
16367       K : Positive := 1;
16368    begin
16369       K := K - 1;
16370    exception
16371       when E : others =>
16372          Text_IO.Put_Line (Exception_Information (E));
16373    end P1;
16374
16375    procedure P2 is
16376    begin
16377       P1;
16378    end P2;
16379
16380 begin
16381    P2;
16382 end STB;
16383 @end group
16384 @end cartouche
16385 @end smallexample
16386
16387 @noindent
16388 This program will output:
16389
16390 @smallexample
16391 $ stb
16392
16393 Exception name: CONSTRAINT_ERROR
16394 Message: stb.adb:12
16395 Call stack traceback locations:
16396 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
16397 @end smallexample
16398
16399 @node Tracebacks From Anywhere in a Program (non-symbolic)
16400 @subsubsection Tracebacks From Anywhere in a Program
16401
16402 @noindent
16403 It is also possible to retrieve a stack traceback from anywhere in a
16404 program. For this you need to
16405 use the @code{GNAT.Traceback} API. This package includes a procedure called
16406 @code{Call_Chain} that computes a complete stack traceback, as well as useful
16407 display procedures described below. It is not necessary to use the
16408 @code{-E gnatbind} option in this case, because the stack traceback mechanism
16409 is invoked explicitly.
16410
16411 @noindent
16412 In the following example we compute a traceback at a specific location in
16413 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
16414 convert addresses to strings:
16415
16416 @smallexample
16417 @cartouche
16418 @group
16419 with Ada.Text_IO;
16420 with GNAT.Traceback;
16421 with GNAT.Debug_Utilities;
16422
16423 procedure STB is
16424
16425    use Ada;
16426    use GNAT;
16427    use GNAT.Traceback;
16428
16429    procedure P1 is
16430       TB  : Tracebacks_Array (1 .. 10);
16431       --  We are asking for a maximum of 10 stack frames.
16432       Len : Natural;
16433       --  Len will receive the actual number of stack frames returned.
16434    begin
16435       Call_Chain (TB, Len);
16436
16437       Text_IO.Put ("In STB.P1 : ");
16438
16439       for K in 1 .. Len loop
16440          Text_IO.Put (Debug_Utilities.Image (TB (K)));
16441          Text_IO.Put (' ');
16442       end loop;
16443
16444       Text_IO.New_Line;
16445    end P1;
16446
16447    procedure P2 is
16448    begin
16449       P1;
16450    end P2;
16451
16452 begin
16453    P2;
16454 end STB;
16455 @end group
16456 @end cartouche
16457 @end smallexample
16458
16459 @smallexample
16460 $ gnatmake stb
16461 $ stb
16462
16463 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
16464 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
16465 @end smallexample
16466
16467 @node Symbolic Traceback
16468 @subsection Symbolic Traceback
16469 @cindex traceback, symbolic
16470
16471 @noindent
16472 A symbolic traceback is a stack traceback in which procedure names are
16473 associated with each code location.
16474
16475 @noindent
16476 Note that this feature is not supported on all platforms. See
16477 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
16478 list of currently supported platforms.
16479
16480 @noindent
16481 Note that the symbolic traceback requires that the program be compiled
16482 with debug information. If it is not compiled with debug information
16483 only the non-symbolic information will be valid.
16484
16485 @menu
16486 * Tracebacks From Exception Occurrences (symbolic)::
16487 * Tracebacks From Anywhere in a Program (symbolic)::
16488 @end menu
16489
16490 @node Tracebacks From Exception Occurrences (symbolic)
16491 @subsubsection Tracebacks From Exception Occurrences
16492
16493 @smallexample
16494 @cartouche
16495 @group
16496 with Ada.Text_IO;
16497 with GNAT.Traceback.Symbolic;
16498
16499 procedure STB is
16500
16501    procedure P1 is
16502    begin
16503       raise Constraint_Error;
16504    end P1;
16505
16506    procedure P2 is
16507    begin
16508       P1;
16509    end P2;
16510
16511    procedure P3 is
16512    begin
16513       P2;
16514    end P3;
16515
16516 begin
16517    P3;
16518 exception
16519    when E : others =>
16520       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
16521 end STB;
16522 @end group
16523 @end cartouche
16524 @end smallexample
16525
16526 @smallexample
16527 $ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl
16528 $ stb
16529
16530 0040149F in stb.p1 at stb.adb:8
16531 004014B7 in stb.p2 at stb.adb:13
16532 004014CF in stb.p3 at stb.adb:18
16533 004015DD in ada.stb at stb.adb:22
16534 00401461 in main at b~stb.adb:168
16535 004011C4 in __mingw_CRTStartup at crt1.c:200
16536 004011F1 in mainCRTStartup at crt1.c:222
16537 77E892A4 in ?? at ??:0
16538 @end smallexample
16539
16540 @noindent
16541 The exact sequence of linker options may vary from platform to platform.
16542 The above @code{-largs} section is for Windows platforms. By contrast,
16543 under Unix there is no need for the @code{-largs} section.
16544 Differences across platforms are due to details of linker implementation.
16545
16546 @node Tracebacks From Anywhere in a Program (symbolic)
16547 @subsubsection Tracebacks From Anywhere in a Program
16548
16549 @noindent
16550 It is possible to get a symbolic stack traceback
16551 from anywhere in a program, just as for non-symbolic tracebacks.
16552 The first step is to obtain a non-symbolic
16553 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
16554 information. Here is an example:
16555
16556 @smallexample
16557 @cartouche
16558 @group
16559 with Ada.Text_IO;
16560 with GNAT.Traceback;
16561 with GNAT.Traceback.Symbolic;
16562
16563 procedure STB is
16564
16565    use Ada;
16566    use GNAT.Traceback;
16567    use GNAT.Traceback.Symbolic;
16568
16569    procedure P1 is
16570       TB  : Tracebacks_Array (1 .. 10);
16571       --  We are asking for a maximum of 10 stack frames.
16572       Len : Natural;
16573       --  Len will receive the actual number of stack frames returned.
16574    begin
16575       Call_Chain (TB, Len);
16576       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
16577    end P1;
16578
16579    procedure P2 is
16580    begin
16581       P1;
16582    end P2;
16583
16584 begin
16585    P2;
16586 end STB;
16587 @end group
16588 @end cartouche
16589 @end smallexample
16590
16591
16592 @node Inline Assembler
16593 @chapter Inline Assembler
16594
16595 @noindent
16596 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:
16597
16598 @itemize @bullet
16599 @item No need to use non-Ada tools
16600 @item Consistent interface over different targets
16601 @item Automatic usage of the proper calling conventions
16602 @item Access to Ada constants and variables
16603 @item Definition of intrinsic routines
16604 @item Possibility of inlining a subprogram comprising assembler code
16605 @item Code optimizer can take Inline Assembler code into account
16606 @end itemize
16607
16608 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.
16609
16610 @menu
16611 * Basic Assembler Syntax::
16612 * A Simple Example of Inline Assembler::
16613 * Output Variables in Inline Assembler::
16614 * Input Variables in Inline Assembler::
16615 * Inlining Inline Assembler Code::
16616 * Other Asm Functionality::
16617 * A Complete Example::
16618 @end menu
16619
16620 @c ---------------------------------------------------------------------------
16621 @node Basic Assembler Syntax
16622 @section Basic Assembler Syntax
16623
16624 @noindent
16625 The assembler used by GNAT and gcc is based not on the Intel assembly language, but rather on a
16626 language that descends from the AT&T Unix assembler @emph{as} (and which is often
16627 referred to as ``AT&T syntax'').
16628 The following table summarizes the main features of @emph{as} syntax and points out the differences from the Intel conventions.
16629 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
16630 pre-processor) documentation for further information.
16631
16632 @table @asis
16633 @item Register names
16634 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
16635 @*
16636 Intel: No extra punctuation; for example @code{eax}
16637
16638 @item Immediate operand
16639 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
16640 @*
16641 Intel: No extra punctuation; for example @code{4}
16642
16643 @item Address
16644 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
16645 @*
16646 Intel: No extra punctuation; for example @code{loc}
16647
16648 @item Memory contents
16649 gcc / @emph{as}: No extra punctuation; for example @code{loc}
16650 @*
16651 Intel: Square brackets; for example @code{[loc]}
16652
16653 @item Register contents
16654 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
16655 @*
16656 Intel: Square brackets; for example @code{[eax]}
16657
16658 @item Hexadecimal numbers
16659 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
16660 @*
16661 Intel: Trailing ``h''; for example @code{A0h}
16662
16663 @item Operand size
16664 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move a 16-bit word
16665 @*
16666 Intel: Implicit, deduced by assembler; for example @code{mov}
16667
16668 @item Instruction repetition
16669 gcc / @emph{as}: Split into two lines; for example
16670 @*
16671 @code{rep}
16672 @*
16673 @code{stosl}
16674 @*
16675 Intel: Keep on one line; for example @code{rep stosl}
16676
16677 @item Order of operands
16678 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
16679 @*
16680 Intel: Destination first; for example @code{mov eax, 4}
16681 @end table
16682
16683 @c ---------------------------------------------------------------------------
16684 @node A Simple Example of Inline Assembler
16685 @section A Simple Example of Inline Assembler
16686
16687 @noindent
16688 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.
16689
16690 @smallexample
16691 @group
16692 with System.Machine_Code; use System.Machine_Code;
16693 procedure Nothing is
16694 begin
16695    Asm ("nop");
16696 end Nothing;
16697 @end group
16698 @end smallexample
16699
16700 @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.
16701 @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.
16702
16703 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}.
16704
16705 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:
16706 @smallexample
16707 gnatmake nothing
16708 @end smallexample
16709 However, the interesting aspect of this example is not its run-time behavior but rather the
16710 generated assembly code.  To see this output, invoke the compiler as follows:
16711 @smallexample
16712    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
16713 @end smallexample
16714 where the options are:
16715
16716 @table @code
16717 @item -c
16718 compile only (no bind or link)
16719 @item -S
16720 generate assembler listing
16721 @item -fomit-frame-pointer
16722 do not set up separate stack frames
16723 @item -gnatp
16724 do not add runtime checks
16725 @end table
16726
16727 This gives a human-readable assembler version of the code. The resulting
16728 file will have the same name as the Ada source file, but with a @code{.s} extension.
16729 In our example, the file @file{nothing.s} has the following contents:
16730
16731 @smallexample
16732 @group
16733 .file "nothing.adb"
16734 gcc2_compiled.:
16735 ___gnu_compiled_ada:
16736 .text
16737    .align 4
16738 .globl __ada_nothing
16739 __ada_nothing:
16740 #APP
16741    nop
16742 #NO_APP
16743    jmp L1
16744    .align 2,0x90
16745 L1:
16746    ret
16747 @end group
16748 @end smallexample
16749
16750 The assembly code you included is clearly indicated by
16751 the compiler, between the @code{#APP} and @code{#NO_APP}
16752 delimiters. The character before the 'APP' and 'NOAPP'
16753 can differ on different targets. For example, Linux uses '#APP' while
16754 on NT you will see '/APP'.
16755
16756 If you make a mistake in your assembler code (such as using the
16757 wrong size modifier, or using a wrong operand for the instruction) GNAT
16758 will report this error in a temporary file, which will be deleted when
16759 the compilation is finished.  Generating an assembler file will help
16760 in such cases, since you can assemble this file separately using the
16761 @emph{as} assembler that comes with gcc.
16762
16763 Assembling the file using the command
16764
16765 @smallexample
16766 as @file{nothing.s}
16767 @end smallexample
16768 @noindent
16769 will give you error messages whose lines correspond to the assembler
16770 input file, so you can easily find and correct any mistakes you made.
16771 If there are no errors, @emph{as} will generate an object file @file{nothing.out}.
16772
16773 @c ---------------------------------------------------------------------------
16774 @node Output Variables in Inline Assembler
16775 @section Output Variables in Inline Assembler
16776
16777 @noindent
16778 The examples in this section, showing how to access the processor flags, illustrate how to specify the destination operands for assembly language statements.
16779
16780 @smallexample
16781 @group
16782 with Interfaces; use Interfaces;
16783 with Ada.Text_IO; use Ada.Text_IO;
16784 with System.Machine_Code; use System.Machine_Code;
16785 procedure Get_Flags is
16786    Flags : Unsigned_32;
16787    use ASCII;
16788 begin
16789    Asm ("pushfl"          & LF & HT & -- push flags on stack
16790         "popl %%eax"      & LF & HT & -- load eax with flags
16791         "movl %%eax, %0",             -- store flags in variable
16792         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
16793    Put_Line ("Flags register:" & Flags'Img);
16794 end Get_Flags;
16795 @end group
16796 @end smallexample
16797
16798 In order to have a nicely aligned assembly listing, we have separated
16799 multiple assembler statements in the Asm template string with linefeed (ASCII.LF)
16800 and horizontal tab (ASCII.HT) characters.  The resulting section of the
16801 assembly output file is:
16802
16803 @smallexample
16804 @group
16805 #APP
16806    pushfl
16807    popl %eax
16808    movl %eax, -40(%ebp)
16809 #NO_APP
16810 @end group
16811 @end smallexample
16812
16813 It would have been legal to write the Asm invocation as:
16814
16815 @smallexample
16816 Asm ("pushfl popl %%eax movl %%eax, %0")
16817 @end smallexample
16818
16819 but in the generated assembler file, this would come out as:
16820
16821 @smallexample
16822 #APP
16823    pushfl popl %eax movl %eax, -40(%ebp)
16824 #NO_APP
16825 @end smallexample
16826
16827 which is not so convenient for the human reader.
16828
16829 We use Ada comments
16830 at the end of each line to explain what the assembler instructions
16831 actually do.  This is a useful convention.
16832
16833 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.
16834
16835 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}.
16836 An output variable is illustrated in
16837 the third statement in the Asm template string:
16838 @smallexample
16839 movl %%eax, %0
16840 @end smallexample
16841 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.
16842
16843 Information about the output variable is supplied in the @code{Outputs} parameter to @code{Asm}:
16844 @smallexample
16845 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
16846 @end smallexample
16847
16848 The output is defined by the @code{Asm_Output} attribute of the target type; the general format is
16849 @smallexample
16850 Type'Asm_Output (constraint_string, variable_name)
16851 @end smallexample
16852
16853 The constraint string directs the compiler how
16854 to store/access the associated variable.  In the example
16855 @smallexample
16856 Unsigned_32'Asm_Output ("=m", Flags);
16857 @end smallexample
16858 the @code{"m"} (memory) constraint tells the compiler that the variable
16859 @code{Flags} should be stored in a memory variable, thus preventing
16860 the optimizer from keeping it in a register.  In contrast,
16861 @smallexample
16862 Unsigned_32'Asm_Output ("=r", Flags);
16863 @end smallexample
16864 uses the @code{"r"} (register) constraint, telling the compiler to
16865 store the variable in a register.
16866
16867 If the constraint is preceded by the equal character (@strong{=}), it tells the
16868 compiler that the variable will be used to store data into it.
16869
16870 In the @code{Get_Flags} example, we used the "g" (global) constraint, allowing the optimizer
16871 to choose whatever it deems best.
16872
16873 There are a fairly large number of constraints, but the ones that are most useful (for the Intel x86 processor) are the following:
16874
16875 @table @code
16876 @item =
16877 output constraint
16878 @item g
16879 global (i.e. can be stored anywhere)
16880 @item m
16881 in memory
16882 @item I
16883 a constant
16884 @item a
16885 use eax
16886 @item b
16887 use ebx
16888 @item c
16889 use ecx
16890 @item d
16891 use edx
16892 @item S
16893 use esi
16894 @item D
16895 use edi
16896 @item r
16897 use one of eax, ebx, ecx or edx
16898 @item q
16899 use one of eax, ebx, ecx, edx, esi or edi
16900 @end table
16901
16902 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.
16903
16904 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
16905 @smallexample
16906 @group
16907 Asm ("pushfl"          & LF & HT & -- push flags on stack
16908      "popl %%eax"      & LF & HT & -- load eax with flags
16909      "movl %%eax, %0",             -- store flags in variable
16910      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
16911 @end group
16912 @end smallexample
16913 @noindent
16914 @code{%0} will be replaced in the expanded code by the appropriate operand,
16915 whatever
16916 the compiler decided for the @code{Flags} variable.
16917
16918 In general, you may have any number of output variables:
16919 @itemize @bullet
16920 @item
16921 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
16922 @item
16923 Specify the @code{Outputs} parameter as a parenthesized comma-separated list of @code{Asm_Output} attributes
16924 @end itemize
16925
16926 For example:
16927 @smallexample
16928 @group
16929 Asm ("movl %%eax, %0" & LF & HT &
16930      "movl %%ebx, %1" & LF & HT &
16931      "movl %%ecx, %2",
16932      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
16933                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
16934                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
16935 @end group
16936 @end smallexample
16937 @noindent
16938 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables in the Ada program.
16939
16940 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:
16941
16942 @smallexample
16943 @group
16944 with Interfaces; use Interfaces;
16945 with Ada.Text_IO; use Ada.Text_IO;
16946 with System.Machine_Code; use System.Machine_Code;
16947 procedure Get_Flags_2 is
16948    Flags : Unsigned_32;
16949    use ASCII;
16950 begin
16951    Asm ("pushfl"      & LF & HT & -- push flags on stack
16952         "popl %%eax",             -- save flags in eax
16953         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
16954    Put_Line ("Flags register:" & Flags'Img);
16955 end Get_Flags_2;
16956 @end group
16957 @end smallexample
16958
16959 @noindent
16960 The @code{"a"} constraint tells the compiler that the @code{Flags}
16961 variable will come from the eax register. Here is the resulting code:
16962
16963 @smallexample
16964 @group
16965 #APP
16966    pushfl
16967    popl %eax
16968 #NO_APP
16969    movl %eax,-40(%ebp)
16970 @end group
16971 @end smallexample
16972
16973 @noindent
16974 The compiler generated the store of eax into Flags after
16975 expanding the assembler code.
16976
16977 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:
16978
16979 @smallexample
16980 @group
16981 with Interfaces; use Interfaces;
16982 with Ada.Text_IO; use Ada.Text_IO;
16983 with System.Machine_Code; use System.Machine_Code;
16984 procedure Get_Flags_3 is
16985    Flags : Unsigned_32;
16986    use ASCII;
16987 begin
16988    Asm ("pushfl"  & LF & HT & -- push flags on stack
16989         "pop %0",             -- save flags in Flags
16990         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
16991    Put_Line ("Flags register:" & Flags'Img);
16992 end Get_Flags_3;
16993 @end group
16994 @end smallexample
16995
16996 @c ---------------------------------------------------------------------------
16997 @node Input Variables in Inline Assembler
16998 @section Input Variables in Inline Assembler
16999
17000 @noindent
17001 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:
17002
17003 @smallexample
17004 @group
17005 with Interfaces; use Interfaces;
17006 with Ada.Text_IO; use Ada.Text_IO;
17007 with System.Machine_Code; use System.Machine_Code;
17008 procedure Increment is
17009
17010    function Incr (Value : Unsigned_32) return Unsigned_32 is
17011       Result : Unsigned_32;
17012    begin
17013       Asm ("incl %0",
17014            Inputs  => Unsigned_32'Asm_Input ("a", Value),
17015            Outputs => Unsigned_32'Asm_Output ("=a", Result));
17016       return Result;
17017    end Incr;
17018
17019    Value : Unsigned_32;
17020
17021 begin
17022    Value := 5;
17023    Put_Line ("Value before is" & Value'Img);
17024    Value := Incr (Value);
17025    Put_Line ("Value after is" & Value'Img);
17026 end Increment;
17027 @end group
17028 @end smallexample
17029
17030 The @code{Outputs} parameter to @code{Asm} specifies
17031 that the result will be in the eax register and that it is to be stored in the @code{Result}
17032 variable.
17033
17034 The @code{Inputs} parameter looks much like the @code{Outputs} parameter, but with an
17035 @code{Asm_Input} attribute. The
17036 @code{"="} constraint, indicating an output value, is not present.
17037
17038 You can have multiple input variables, in the same way that you can have more
17039 than one output variable.
17040
17041 The parameter count (%0, %1) etc, now starts at the first input
17042 statement, and continues with the output statements.
17043 When both parameters use the same variable, the
17044 compiler will treat them as the same %n operand, which is the case here.
17045
17046 Just as the @code{Outputs} parameter causes the register to be stored into the
17047 target variable after execution of the assembler statements, so does the
17048 @code{Inputs} parameter cause its variable to be loaded into the register before execution
17049 of the
17050 assembler statements.
17051
17052 Thus the effect of the @code{Asm} invocation is:
17053 @enumerate
17054 @item load the 32-bit value of @code{Value} into eax
17055 @item execute the @code{incl %eax} instruction
17056 @item store the contents of eax into the @code{Result} variable
17057 @end enumerate
17058
17059 The resulting assembler file (with @code{-O2} optimization) contains:
17060 @smallexample
17061 @group
17062 _increment__incr.1:
17063    subl $4,%esp
17064    movl 8(%esp),%eax
17065 #APP
17066    incl %eax
17067 #NO_APP
17068    movl %eax,%edx
17069    movl %ecx,(%esp)
17070    addl $4,%esp
17071    ret
17072 @end group
17073 @end smallexample
17074
17075 @c ---------------------------------------------------------------------------
17076 @node Inlining Inline Assembler Code
17077 @section Inlining Inline Assembler Code
17078
17079 @noindent
17080 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)
17081 can be significant, compared to the amount of code in the subprogram body.
17082 A solution is to apply Ada's @code{Inline} pragma to the subprogram,
17083 which directs the compiler to expand invocations of the subprogram at the point(s)
17084 of call, instead of setting up a stack frame for out-of-line calls.
17085 Here is the resulting program:
17086
17087 @smallexample
17088 @group
17089 with Interfaces; use Interfaces;
17090 with Ada.Text_IO; use Ada.Text_IO;
17091 with System.Machine_Code; use System.Machine_Code;
17092 procedure Increment_2 is
17093
17094    function Incr (Value : Unsigned_32) return Unsigned_32 is
17095       Result : Unsigned_32;
17096    begin
17097       Asm ("incl %0",
17098            Inputs  => Unsigned_32'Asm_Input ("a", Value),
17099            Outputs => Unsigned_32'Asm_Output ("=a", Result));
17100       return Result;
17101    end Incr;
17102    pragma Inline (Increment);
17103
17104    Value : Unsigned_32;
17105
17106 begin
17107    Value := 5;
17108    Put_Line ("Value before is" & Value'Img);
17109    Value := Increment (Value);
17110    Put_Line ("Value after is" & Value'Img);
17111 end Increment_2;
17112 @end group
17113 @end smallexample
17114
17115 Compile the program with both optimization (@code{-O2}) and inlining
17116 enabled (@option{-gnatpn} instead of @option{-gnatp}).
17117
17118 The @code{Incr} function is still compiled as usual, but at the
17119 point in @code{Increment} where our function used to be called:
17120
17121 @smallexample
17122 @group
17123 pushl %edi
17124 call _increment__incr.1
17125 @end group
17126 @end smallexample
17127
17128 @noindent
17129 the code for the function body directly appears:
17130
17131 @smallexample
17132 @group
17133 movl %esi,%eax
17134 #APP
17135    incl %eax
17136 #NO_APP
17137    movl %eax,%edx
17138 @end group
17139 @end smallexample
17140
17141 @noindent
17142 thus saving the overhead of stack frame setup and an out-of-line call.
17143
17144 @c ---------------------------------------------------------------------------
17145 @node Other Asm Functionality
17146 @section Other @code{Asm} Functionality
17147
17148 @noindent
17149 This section describes two important parameters to the @code{Asm} procedure: @code{Clobber}, which identifies register usage; and @code{Volatile}, which inhibits unwanted optimizations.
17150
17151 @menu
17152 * The Clobber Parameter::
17153 * The Volatile Parameter::
17154 @end menu
17155
17156 @c ---------------------------------------------------------------------------
17157 @node The Clobber Parameter
17158 @subsection The @code{Clobber} Parameter
17159
17160 @noindent
17161 One of the dangers of intermixing assembly language and a compiled language such as Ada is
17162 that the compiler needs to be aware of which registers are being used by the assembly code.
17163 In some cases, such as the earlier examples, the constraint string is sufficient to
17164 indicate register usage (e.g. "a" for the eax register).  But more generally, the
17165 compiler needs an explicit identification of the registers that are used by the Inline
17166 Assembly statements.
17167
17168 Using a register that the compiler doesn't know about
17169 could be a side effect of an instruction (like @code{mull}
17170 storing its result in both eax and edx).
17171 It can also arise from explicit register usage in your
17172 assembly code; for example:
17173 @smallexample
17174 @group
17175 Asm ("movl %0, %%ebx" & LF & HT &
17176      "movl %%ebx, %1",
17177      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
17178      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
17179 @end group
17180 @end smallexample
17181 @noindent
17182 where the compiler (since it does not analyze the @code{Asm} template string)
17183 does not know you are using the ebx register.
17184
17185 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
17186 to identify the registers that will be used by your assembly code:
17187
17188 @smallexample
17189 @group
17190 Asm ("movl %0, %%ebx" & LF & HT &
17191      "movl %%ebx, %1",
17192      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
17193      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
17194      Clobber => "ebx");
17195 @end group
17196 @end smallexample
17197
17198 The Clobber parameter is a static string expression specifying the
17199 register(s) you are using.  Note that register names are @emph{not} prefixed by a percent sign.
17200 Also, if more than one register is used then their names are separated by commas; e.g., @code{"eax, ebx"}
17201
17202 The @code{Clobber} parameter has several additional uses:
17203 @enumerate
17204 @item Use the "register" name @code{cc} to indicate that flags might have changed
17205 @item Use the "register" name @code{memory} if you changed a memory location
17206 @end enumerate
17207
17208 @c ---------------------------------------------------------------------------
17209 @node The Volatile Parameter
17210 @subsection The @code{Volatile} Parameter
17211 @cindex Volatile parameter
17212
17213 @noindent
17214 Compiler optimizations in the presence of Inline Assembler may sometimes have unwanted effects.
17215 For example, when
17216 an @code{Asm} invocation with an input variable is inside a loop, the compiler might move
17217 the loading of the input variable outside the loop, regarding it as a
17218 one-time initialization.
17219
17220 If this effect is not desired, you can disable such optimizations by setting the
17221 @code{Volatile} parameter to @code{True}; for example:
17222
17223 @smallexample
17224 @group
17225 Asm ("movl %0, %%ebx" & LF & HT &
17226      "movl %%ebx, %1",
17227      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
17228      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
17229      Clobber  => "ebx",
17230      Volatile => True);
17231 @end group
17232 @end smallexample
17233
17234 By default, @code{Volatile} is set to @code{False} unless there is no @code{Outputs}
17235 parameter.
17236
17237 Although setting @code{Volatile} to @code{True} prevents unwanted optimizations,
17238 it will also disable other optimizations that might be important for efficiency.
17239 In general, you should set @code{Volatile} to @code{True} only if the compiler's
17240 optimizations have created problems.
17241
17242 @c ---------------------------------------------------------------------------
17243 @node A Complete Example
17244 @section A Complete Example
17245
17246 @noindent
17247 This section contains a complete program illustrating a realistic usage of GNAT's Inline Assembler
17248 capabilities.  It comprises a main procedure @code{Check_CPU} and a package @code{Intel_CPU}.
17249 The package declares a collection of functions that detect the properties of the 32-bit
17250 x86 processor that is running the program.  The main procedure invokes these functions
17251 and displays the information.
17252
17253 The Intel_CPU package could be enhanced by adding functions to
17254 detect the type of x386 co-processor, the processor caching options and
17255 special operations such as the SIMD extensions.
17256
17257 Although the Intel_CPU package has been written for 32-bit Intel
17258 compatible CPUs, it is OS neutral. It has been tested on DOS,
17259 Windows/NT and Linux.
17260
17261 @menu
17262 * Check_CPU Procedure::
17263 * Intel_CPU Package Specification::
17264 * Intel_CPU Package Body::
17265 @end menu
17266
17267 @c ---------------------------------------------------------------------------
17268 @node Check_CPU Procedure
17269 @subsection @code{Check_CPU} Procedure
17270 @cindex Check_CPU procedure
17271
17272 @smallexample
17273 ---------------------------------------------------------------------
17274 --                                                                 --
17275 --  Uses the Intel_CPU package to identify the CPU the program is  --
17276 --  running on, and some of the features it supports.              --
17277 --                                                                 --
17278 ---------------------------------------------------------------------
17279
17280 with Intel_CPU;                     --  Intel CPU detection functions
17281 with Ada.Text_IO;                   --  Standard text I/O
17282 with Ada.Command_Line;              --  To set the exit status
17283
17284 procedure Check_CPU is
17285
17286    Type_Found : Boolean := False;
17287    --  Flag to indicate that processor was identified
17288
17289    Features   : Intel_CPU.Processor_Features;
17290    --  The processor features
17291
17292    Signature  : Intel_CPU.Processor_Signature;
17293    --  The processor type signature
17294
17295 begin
17296
17297    -----------------------------------
17298    --  Display the program banner.  --
17299    -----------------------------------
17300
17301    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
17302                          ": check Intel CPU version and features, v1.0");
17303    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
17304    Ada.Text_IO.New_Line;
17305
17306    -----------------------------------------------------------------------
17307    --  We can safely start with the assumption that we are on at least  --
17308    --  a x386 processor. If the CPUID instruction is present, then we   --
17309    --  have a later processor type.                                     --
17310    -----------------------------------------------------------------------
17311
17312    if Intel_CPU.Has_CPUID = False then
17313
17314       --  No CPUID instruction, so we assume this is indeed a x386
17315       --  processor. We can still check if it has a FP co-processor.
17316       if Intel_CPU.Has_FPU then
17317          Ada.Text_IO.Put_Line
17318            ("x386-type processor with a FP co-processor");
17319       else
17320          Ada.Text_IO.Put_Line
17321            ("x386-type processor without a FP co-processor");
17322       end if;  --  check for FPU
17323
17324       --  Program done
17325       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17326       return;
17327
17328    end if;  --  check for CPUID
17329
17330    -----------------------------------------------------------------------
17331    --  If CPUID is supported, check if this is a true Intel processor,  --
17332    --  if it is not, display a warning.                                 --
17333    -----------------------------------------------------------------------
17334
17335    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
17336       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
17337       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
17338    end if;  --  check if Intel
17339
17340    ----------------------------------------------------------------------
17341    --  With the CPUID instruction present, we can assume at least a    --
17342    --  x486 processor. If the CPUID support level is < 1 then we have  --
17343    --  to leave it at that.                                            --
17344    ----------------------------------------------------------------------
17345
17346    if Intel_CPU.CPUID_Level < 1 then
17347
17348       --  Ok, this is a x486 processor. we still can get the Vendor ID
17349       Ada.Text_IO.Put_Line ("x486-type processor");
17350       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
17351
17352       --  We can also check if there is a FPU present
17353       if Intel_CPU.Has_FPU then
17354          Ada.Text_IO.Put_Line ("Floating-Point support");
17355       else
17356          Ada.Text_IO.Put_Line ("No Floating-Point support");
17357       end if;  --  check for FPU
17358
17359       --  Program done
17360       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17361       return;
17362
17363    end if;  --  check CPUID level
17364
17365    ---------------------------------------------------------------------
17366    --  With a CPUID level of 1 we can use the processor signature to  --
17367    --  determine it's exact type.                                     --
17368    ---------------------------------------------------------------------
17369
17370    Signature := Intel_CPU.Signature;
17371
17372    ----------------------------------------------------------------------
17373    --  Ok, now we go into a lot of messy comparisons to get the        --
17374    --  processor type. For clarity, no attememt to try to optimize the --
17375    --  comparisons has been made. Note that since Intel_CPU does not   --
17376    --  support getting cache info, we cannot distinguish between P5    --
17377    --  and Celeron types yet.                                          --
17378    ----------------------------------------------------------------------
17379
17380    --  x486SL
17381    if Signature.Processor_Type = 2#00#   and
17382      Signature.Family          = 2#0100# and
17383      Signature.Model           = 2#0100# then
17384       Type_Found := True;
17385       Ada.Text_IO.Put_Line ("x486SL processor");
17386    end if;
17387
17388    --  x486DX2 Write-Back
17389    if Signature.Processor_Type = 2#00#   and
17390      Signature.Family          = 2#0100# and
17391      Signature.Model           = 2#0111# then
17392       Type_Found := True;
17393       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
17394    end if;
17395
17396    --  x486DX4
17397    if Signature.Processor_Type = 2#00#   and
17398      Signature.Family          = 2#0100# and
17399      Signature.Model           = 2#1000# then
17400       Type_Found := True;
17401       Ada.Text_IO.Put_Line ("x486DX4 processor");
17402    end if;
17403
17404    --  x486DX4 Overdrive
17405    if Signature.Processor_Type = 2#01#   and
17406      Signature.Family          = 2#0100# and
17407      Signature.Model           = 2#1000# then
17408       Type_Found := True;
17409       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
17410    end if;
17411
17412    --  Pentium (60, 66)
17413    if Signature.Processor_Type = 2#00#   and
17414      Signature.Family          = 2#0101# and
17415      Signature.Model           = 2#0001# then
17416       Type_Found := True;
17417       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
17418    end if;
17419
17420    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
17421    if Signature.Processor_Type = 2#00#   and
17422      Signature.Family          = 2#0101# and
17423      Signature.Model           = 2#0010# then
17424       Type_Found := True;
17425       Ada.Text_IO.Put_Line
17426         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
17427    end if;
17428
17429    --  Pentium OverDrive (60, 66)
17430    if Signature.Processor_Type = 2#01#   and
17431      Signature.Family          = 2#0101# and
17432      Signature.Model           = 2#0001# then
17433       Type_Found := True;
17434       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
17435    end if;
17436
17437    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
17438    if Signature.Processor_Type = 2#01#   and
17439      Signature.Family          = 2#0101# and
17440      Signature.Model           = 2#0010# then
17441       Type_Found := True;
17442       Ada.Text_IO.Put_Line
17443         ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
17444    end if;
17445
17446    --  Pentium OverDrive processor for x486 processor-based systems
17447    if Signature.Processor_Type = 2#01#   and
17448      Signature.Family          = 2#0101# and
17449      Signature.Model           = 2#0011# then
17450       Type_Found := True;
17451       Ada.Text_IO.Put_Line
17452         ("Pentium OverDrive processor for x486 processor-based systems");
17453    end if;
17454
17455    --  Pentium processor with MMX technology (166, 200)
17456    if Signature.Processor_Type = 2#00#   and
17457      Signature.Family          = 2#0101# and
17458      Signature.Model           = 2#0100# then
17459       Type_Found := True;
17460       Ada.Text_IO.Put_Line
17461         ("Pentium processor with MMX technology (166, 200)");
17462    end if;
17463
17464    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
17465    if Signature.Processor_Type = 2#01#   and
17466      Signature.Family          = 2#0101# and
17467      Signature.Model           = 2#0100# then
17468       Type_Found := True;
17469       Ada.Text_IO.Put_Line
17470         ("Pentium OverDrive processor with MMX " &
17471          "technology for Pentium processor (75, 90, 100, 120, 133)");
17472    end if;
17473
17474    --  Pentium Pro processor
17475    if Signature.Processor_Type = 2#00#   and
17476      Signature.Family          = 2#0110# and
17477      Signature.Model           = 2#0001# then
17478       Type_Found := True;
17479       Ada.Text_IO.Put_Line ("Pentium Pro processor");
17480    end if;
17481
17482    --  Pentium II processor, model 3
17483    if Signature.Processor_Type = 2#00#   and
17484      Signature.Family          = 2#0110# and
17485      Signature.Model           = 2#0011# then
17486       Type_Found := True;
17487       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
17488    end if;
17489
17490    --  Pentium II processor, model 5 or Celeron processor
17491    if Signature.Processor_Type = 2#00#   and
17492      Signature.Family          = 2#0110# and
17493      Signature.Model           = 2#0101# then
17494       Type_Found := True;
17495       Ada.Text_IO.Put_Line
17496         ("Pentium II processor, model 5 or Celeron processor");
17497    end if;
17498
17499    --  Pentium Pro OverDrive processor
17500    if Signature.Processor_Type = 2#01#   and
17501      Signature.Family          = 2#0110# and
17502      Signature.Model           = 2#0011# then
17503       Type_Found := True;
17504       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
17505    end if;
17506
17507    --  If no type recognized, we have an unknown. Display what
17508    --  we _do_ know
17509    if Type_Found = False then
17510       Ada.Text_IO.Put_Line ("Unknown processor");
17511    end if;
17512
17513    -----------------------------------------
17514    --  Display processor stepping level.  --
17515    -----------------------------------------
17516
17517    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
17518
17519    ---------------------------------
17520    --  Display vendor ID string.  --
17521    ---------------------------------
17522
17523    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
17524
17525    ------------------------------------
17526    --  Get the processors features.  --
17527    ------------------------------------
17528
17529    Features := Intel_CPU.Features;
17530
17531    -----------------------------
17532    --  Check for a FPU unit.  --
17533    -----------------------------
17534
17535    if Features.FPU = True then
17536       Ada.Text_IO.Put_Line ("Floating-Point unit available");
17537    else
17538       Ada.Text_IO.Put_Line ("no Floating-Point unit");
17539    end if;  --  check for FPU
17540
17541    --------------------------------
17542    --  List processor features.  --
17543    --------------------------------
17544
17545    Ada.Text_IO.Put_Line ("Supported features: ");
17546
17547    --  Virtual Mode Extension
17548    if Features.VME = True then
17549       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
17550    end if;
17551
17552    --  Debugging Extension
17553    if Features.DE = True then
17554       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
17555    end if;
17556
17557    --  Page Size Extension
17558    if Features.PSE = True then
17559       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
17560    end if;
17561
17562    --  Time Stamp Counter
17563    if Features.TSC = True then
17564       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
17565    end if;
17566
17567    --  Model Specific Registers
17568    if Features.MSR = True then
17569       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
17570    end if;
17571
17572    --  Physical Address Extension
17573    if Features.PAE = True then
17574       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
17575    end if;
17576
17577    --  Machine Check Extension
17578    if Features.MCE = True then
17579       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
17580    end if;
17581
17582    --  CMPXCHG8 instruction supported
17583    if Features.CX8 = True then
17584       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
17585    end if;
17586
17587    --  on-chip APIC hardware support
17588    if Features.APIC = True then
17589       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
17590    end if;
17591
17592    --  Fast System Call
17593    if Features.SEP = True then
17594       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
17595    end if;
17596
17597    --  Memory Type Range Registers
17598    if Features.MTRR = True then
17599       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
17600    end if;
17601
17602    --  Page Global Enable
17603    if Features.PGE = True then
17604       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
17605    end if;
17606
17607    --  Machine Check Architecture
17608    if Features.MCA = True then
17609       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
17610    end if;
17611
17612    --  Conditional Move Instruction Supported
17613    if Features.CMOV = True then
17614       Ada.Text_IO.Put_Line
17615         ("    CMOV   - Conditional Move Instruction Supported");
17616    end if;
17617
17618    --  Page Attribute Table
17619    if Features.PAT = True then
17620       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
17621    end if;
17622
17623    --  36-bit Page Size Extension
17624    if Features.PSE_36 = True then
17625       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
17626    end if;
17627
17628    --  MMX technology supported
17629    if Features.MMX = True then
17630       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
17631    end if;
17632
17633    --  Fast FP Save and Restore
17634    if Features.FXSR = True then
17635       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
17636    end if;
17637
17638    ---------------------
17639    --  Program done.  --
17640    ---------------------
17641
17642    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17643
17644 exception
17645
17646    when others =>
17647       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
17648       raise;
17649
17650 end Check_CPU;
17651 @end smallexample
17652
17653 @c ---------------------------------------------------------------------------
17654 @node Intel_CPU Package Specification
17655 @subsection @code{Intel_CPU} Package Specification
17656 @cindex Intel_CPU package specification
17657
17658 @smallexample
17659 -------------------------------------------------------------------------
17660 --                                                                     --
17661 --  file: intel_cpu.ads                                                --
17662 --                                                                     --
17663 --           *********************************************             --
17664 --           * WARNING: for 32-bit Intel processors only *             --
17665 --           *********************************************             --
17666 --                                                                     --
17667 --  This package contains a number of subprograms that are useful in   --
17668 --  determining the Intel x86 CPU (and the features it supports) on    --
17669 --  which the program is running.                                      --
17670 --                                                                     --
17671 --  The package is based upon the information given in the Intel       --
17672 --  Application Note AP-485: "Intel Processor Identification and the   --
17673 --  CPUID Instruction" as of April 1998. This application note can be  --
17674 --  found on www.intel.com.                                            --
17675 --                                                                     --
17676 --  It currently deals with 32-bit processors only, will not detect    --
17677 --  features added after april 1998, and does not guarantee proper     --
17678 --  results on Intel-compatible processors.                            --
17679 --                                                                     --
17680 --  Cache info and x386 fpu type detection are not supported.          --
17681 --                                                                     --
17682 --  This package does not use any privileged instructions, so should   --
17683 --  work on any OS running on a 32-bit Intel processor.                --
17684 --                                                                     --
17685 -------------------------------------------------------------------------
17686
17687 with Interfaces;             use Interfaces;
17688 --  for using unsigned types
17689
17690 with System.Machine_Code;    use System.Machine_Code;
17691 --  for using inline assembler code
17692
17693 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
17694 --  for inserting control characters
17695
17696 package Intel_CPU is
17697
17698    ----------------------
17699    --  Processor bits  --
17700    ----------------------
17701
17702    subtype Num_Bits is Natural range 0 .. 31;
17703    --  the number of processor bits (32)
17704
17705    --------------------------
17706    --  Processor register  --
17707    --------------------------
17708
17709    --  define a processor register type for easy access to
17710    --  the individual bits
17711
17712    type Processor_Register is array (Num_Bits) of Boolean;
17713    pragma Pack (Processor_Register);
17714    for Processor_Register'Size use 32;
17715
17716    -------------------------
17717    --  Unsigned register  --
17718    -------------------------
17719
17720    --  define a processor register type for easy access to
17721    --  the individual bytes
17722
17723    type Unsigned_Register is
17724       record
17725          L1 : Unsigned_8;
17726          H1 : Unsigned_8;
17727          L2 : Unsigned_8;
17728          H2 : Unsigned_8;
17729       end record;
17730
17731    for Unsigned_Register use
17732       record
17733          L1 at 0 range  0 ..  7;
17734          H1 at 0 range  8 .. 15;
17735          L2 at 0 range 16 .. 23;
17736          H2 at 0 range 24 .. 31;
17737       end record;
17738
17739    for Unsigned_Register'Size use 32;
17740
17741    ---------------------------------
17742    --  Intel processor vendor ID  --
17743    ---------------------------------
17744
17745    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
17746    --  indicates an Intel manufactured processor
17747
17748    ------------------------------------
17749    --  Processor signature register  --
17750    ------------------------------------
17751
17752    --  a register type to hold the processor signature
17753
17754    type Processor_Signature is
17755       record
17756          Stepping       : Natural range 0 .. 15;
17757          Model          : Natural range 0 .. 15;
17758          Family         : Natural range 0 .. 15;
17759          Processor_Type : Natural range 0 .. 3;
17760          Reserved       : Natural range 0 .. 262143;
17761       end record;
17762
17763    for Processor_Signature use
17764       record
17765          Stepping       at 0 range  0 ..  3;
17766          Model          at 0 range  4 ..  7;
17767          Family         at 0 range  8 .. 11;
17768          Processor_Type at 0 range 12 .. 13;
17769          Reserved       at 0 range 14 .. 31;
17770       end record;
17771
17772    for Processor_Signature'Size use 32;
17773
17774    -----------------------------------
17775    --  Processor features register  --
17776    -----------------------------------
17777
17778    --  a processor register to hold the processor feature flags
17779
17780    type Processor_Features is
17781       record
17782          FPU    : Boolean;                --  floating point unit on chip
17783          VME    : Boolean;                --  virtual mode extension
17784          DE     : Boolean;                --  debugging extension
17785          PSE    : Boolean;                --  page size extension
17786          TSC    : Boolean;                --  time stamp counter
17787          MSR    : Boolean;                --  model specific registers
17788          PAE    : Boolean;                --  physical address extension
17789          MCE    : Boolean;                --  machine check extension
17790          CX8    : Boolean;                --  cmpxchg8 instruction
17791          APIC   : Boolean;                --  on-chip apic hardware
17792          Res_1  : Boolean;                --  reserved for extensions
17793          SEP    : Boolean;                --  fast system call
17794          MTRR   : Boolean;                --  memory type range registers
17795          PGE    : Boolean;                --  page global enable
17796          MCA    : Boolean;                --  machine check architecture
17797          CMOV   : Boolean;                --  conditional move supported
17798          PAT    : Boolean;                --  page attribute table
17799          PSE_36 : Boolean;                --  36-bit page size extension
17800          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
17801          MMX    : Boolean;                --  MMX technology supported
17802          FXSR   : Boolean;                --  fast FP save and restore
17803          Res_3  : Natural range 0 .. 127; --  reserved for extensions
17804       end record;
17805
17806    for Processor_Features use
17807       record
17808          FPU    at 0 range  0 ..  0;
17809          VME    at 0 range  1 ..  1;
17810          DE     at 0 range  2 ..  2;
17811          PSE    at 0 range  3 ..  3;
17812          TSC    at 0 range  4 ..  4;
17813          MSR    at 0 range  5 ..  5;
17814          PAE    at 0 range  6 ..  6;
17815          MCE    at 0 range  7 ..  7;
17816          CX8    at 0 range  8 ..  8;
17817          APIC   at 0 range  9 ..  9;
17818          Res_1  at 0 range 10 .. 10;
17819          SEP    at 0 range 11 .. 11;
17820          MTRR   at 0 range 12 .. 12;
17821          PGE    at 0 range 13 .. 13;
17822          MCA    at 0 range 14 .. 14;
17823          CMOV   at 0 range 15 .. 15;
17824          PAT    at 0 range 16 .. 16;
17825          PSE_36 at 0 range 17 .. 17;
17826          Res_2  at 0 range 18 .. 22;
17827          MMX    at 0 range 23 .. 23;
17828          FXSR   at 0 range 24 .. 24;
17829          Res_3  at 0 range 25 .. 31;
17830       end record;
17831
17832    for Processor_Features'Size use 32;
17833
17834    -------------------
17835    --  Subprograms  --
17836    -------------------
17837
17838    function Has_FPU return Boolean;
17839    --  return True if a FPU is found
17840    --  use only if CPUID is not supported
17841
17842    function Has_CPUID return Boolean;
17843    --  return True if the processor supports the CPUID instruction
17844
17845    function CPUID_Level return Natural;
17846    --  return the CPUID support level (0, 1 or 2)
17847    --  can only be called if the CPUID instruction is supported
17848
17849    function Vendor_ID return String;
17850    --  return the processor vendor identification string
17851    --  can only be called if the CPUID instruction is supported
17852
17853    function Signature return Processor_Signature;
17854    --  return the processor signature
17855    --  can only be called if the CPUID instruction is supported
17856
17857    function Features return Processor_Features;
17858    --  return the processors features
17859    --  can only be called if the CPUID instruction is supported
17860
17861 private
17862
17863    ------------------------
17864    --  EFLAGS bit names  --
17865    ------------------------
17866
17867    ID_Flag : constant Num_Bits := 21;
17868    --  ID flag bit
17869
17870 end Intel_CPU;
17871 @end smallexample
17872
17873 @c ---------------------------------------------------------------------------
17874 @node Intel_CPU Package Body
17875 @subsection @code{Intel_CPU} Package Body
17876 @cindex Intel_CPU package body
17877
17878 @smallexample
17879 package body Intel_CPU is
17880
17881    ---------------------------
17882    --  Detect FPU presence  --
17883    ---------------------------
17884
17885    --  There is a FPU present if we can set values to the FPU Status
17886    --  and Control Words.
17887
17888    function Has_FPU return Boolean is
17889
17890       Register : Unsigned_16;
17891       --  processor register to store a word
17892
17893    begin
17894
17895       --  check if we can change the status word
17896       Asm (
17897
17898            --  the assembler code
17899            "finit"              & LF & HT &    --  reset status word
17900            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
17901            "fnstsw %0"          & LF & HT &    --  save status word
17902            "movw %%ax, %0",                    --  store status word
17903
17904            --  output stored in Register
17905            --  register must be a memory location
17906            Outputs => Unsigned_16'Asm_output ("=m", Register),
17907
17908            --  tell compiler that we used eax
17909            Clobber => "eax");
17910
17911       --  if the status word is zero, there is no FPU
17912       if Register = 0 then
17913          return False;   --  no status word
17914       end if;  --  check status word value
17915
17916       --  check if we can get the control word
17917       Asm (
17918
17919            --  the assembler code
17920            "fnstcw %0",   --  save the control word
17921
17922            --  output into Register
17923            --  register must be a memory location
17924            Outputs => Unsigned_16'Asm_output ("=m", Register));
17925
17926       --  check the relevant bits
17927       if (Register and 16#103F#) /= 16#003F# then
17928          return False;   --  no control word
17929       end if;  --  check control word value
17930
17931       --  FPU found
17932       return True;
17933
17934    end Has_FPU;
17935
17936    --------------------------------
17937    --  Detect CPUID instruction  --
17938    --------------------------------
17939
17940    --  The processor supports the CPUID instruction if it is possible
17941    --  to change the value of ID flag bit in the EFLAGS register.
17942
17943    function Has_CPUID return Boolean is
17944
17945       Original_Flags, Modified_Flags : Processor_Register;
17946       --  EFLAG contents before and after changing the ID flag
17947
17948    begin
17949
17950       --  try flipping the ID flag in the EFLAGS register
17951       Asm (
17952
17953            --  the assembler code
17954            "pushfl"               & LF & HT &     --  push EFLAGS on stack
17955            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
17956            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
17957            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
17958            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
17959            "popfl"                & LF & HT &     --  load EFLAGS register
17960            "pushfl"               & LF & HT &     --  push EFLAGS on stack
17961            "pop %1",                              --  save EFLAGS content
17962
17963            --  output values, may be anything
17964            --  Original_Flags is %0
17965            --  Modified_Flags is %1
17966            Outputs =>
17967               (Processor_Register'Asm_output ("=g", Original_Flags),
17968                Processor_Register'Asm_output ("=g", Modified_Flags)),
17969
17970            --  tell compiler eax is destroyed
17971            Clobber => "eax");
17972
17973       --  check if CPUID is supported
17974       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
17975          return True;   --  ID flag was modified
17976       else
17977          return False;  --  ID flag unchanged
17978       end if;  --  check for CPUID
17979
17980    end Has_CPUID;
17981
17982    -------------------------------
17983    --  Get CPUID support level  --
17984    -------------------------------
17985
17986    function CPUID_Level return Natural is
17987
17988       Level : Unsigned_32;
17989       --  returned support level
17990
17991    begin
17992
17993       --  execute CPUID, storing the results in the Level register
17994       Asm (
17995
17996            --  the assembler code
17997            "cpuid",    --  execute CPUID
17998
17999            --  zero is stored in eax
18000            --  returning the support level in eax
18001            Inputs => Unsigned_32'Asm_input ("a", 0),
18002
18003            --  eax is stored in Level
18004            Outputs => Unsigned_32'Asm_output ("=a", Level),
18005
18006            --  tell compiler ebx, ecx and edx registers are destroyed
18007            Clobber => "ebx, ecx, edx");
18008
18009       --  return the support level
18010       return Natural (Level);
18011
18012    end CPUID_Level;
18013
18014    --------------------------------
18015    --  Get CPU Vendor ID String  --
18016    --------------------------------
18017
18018    --  The vendor ID string is returned in the ebx, ecx and edx register
18019    --  after executing the CPUID instruction with eax set to zero.
18020    --  In case of a true Intel processor the string returned is
18021    --  "GenuineIntel"
18022
18023    function Vendor_ID return String is
18024
18025       Ebx, Ecx, Edx : Unsigned_Register;
18026       --  registers containing the vendor ID string
18027
18028       Vendor_ID : String (1 .. 12);
18029       -- the vendor ID string
18030
18031    begin
18032
18033       --  execute CPUID, storing the results in the processor registers
18034       Asm (
18035
18036            --  the assembler code
18037            "cpuid",    --  execute CPUID
18038
18039            --  zero stored in eax
18040            --  vendor ID string returned in ebx, ecx and edx
18041            Inputs => Unsigned_32'Asm_input ("a", 0),
18042
18043            --  ebx is stored in Ebx
18044            --  ecx is stored in Ecx
18045            --  edx is stored in Edx
18046            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
18047                        Unsigned_Register'Asm_output ("=c", Ecx),
18048                        Unsigned_Register'Asm_output ("=d", Edx)));
18049
18050       --  now build the vendor ID string
18051       Vendor_ID( 1) := Character'Val (Ebx.L1);
18052       Vendor_ID( 2) := Character'Val (Ebx.H1);
18053       Vendor_ID( 3) := Character'Val (Ebx.L2);
18054       Vendor_ID( 4) := Character'Val (Ebx.H2);
18055       Vendor_ID( 5) := Character'Val (Edx.L1);
18056       Vendor_ID( 6) := Character'Val (Edx.H1);
18057       Vendor_ID( 7) := Character'Val (Edx.L2);
18058       Vendor_ID( 8) := Character'Val (Edx.H2);
18059       Vendor_ID( 9) := Character'Val (Ecx.L1);
18060       Vendor_ID(10) := Character'Val (Ecx.H1);
18061       Vendor_ID(11) := Character'Val (Ecx.L2);
18062       Vendor_ID(12) := Character'Val (Ecx.H2);
18063
18064       --  return string
18065       return Vendor_ID;
18066
18067    end Vendor_ID;
18068
18069    -------------------------------
18070    --  Get processor signature  --
18071    -------------------------------
18072
18073    function Signature return Processor_Signature is
18074
18075       Result : Processor_Signature;
18076       --  processor signature returned
18077
18078    begin
18079
18080       --  execute CPUID, storing the results in the Result variable
18081       Asm (
18082
18083            --  the assembler code
18084            "cpuid",    --  execute CPUID
18085
18086            --  one is stored in eax
18087            --  processor signature returned in eax
18088            Inputs => Unsigned_32'Asm_input ("a", 1),
18089
18090            --  eax is stored in Result
18091            Outputs => Processor_Signature'Asm_output ("=a", Result),
18092
18093            --  tell compiler that ebx, ecx and edx are also destroyed
18094            Clobber => "ebx, ecx, edx");
18095
18096       --  return processor signature
18097       return Result;
18098
18099    end Signature;
18100
18101    ------------------------------
18102    --  Get processor features  --
18103    ------------------------------
18104
18105    function Features return Processor_Features is
18106
18107       Result : Processor_Features;
18108       --  processor features returned
18109
18110    begin
18111
18112       --  execute CPUID, storing the results in the Result variable
18113       Asm (
18114
18115            --  the assembler code
18116            "cpuid",    --  execute CPUID
18117
18118            --  one stored in eax
18119            --  processor features returned in edx
18120            Inputs => Unsigned_32'Asm_input ("a", 1),
18121
18122            --  edx is stored in Result
18123            Outputs => Processor_Features'Asm_output ("=d", Result),
18124
18125            --  tell compiler that ebx and ecx are also destroyed
18126            Clobber => "ebx, ecx");
18127
18128       --  return processor signature
18129       return Result;
18130
18131    end Features;
18132
18133 end Intel_CPU;
18134 @end smallexample
18135 @c END OF INLINE ASSEMBLER CHAPTER
18136 @c ===============================
18137
18138
18139 @node VxWorks Topics
18140 @chapter VxWorks Topics
18141
18142 @noindent
18143 This chapter describes topics that are specific to the GNAT for VxWorks
18144 configurations.
18145
18146 @menu
18147 * Kernel Configuration for VxWorks::
18148 * Kernel Compilation Issues for VxWorks::
18149 * Handling Relocation Issues for PowerPc Targets::
18150 * Support for Software Floating Point on PowerPC Processors::
18151 * Interrupt Handling for VxWorks::
18152 * Simulating Command Line Arguments for VxWorks::
18153 * Debugging Issues for VxWorks::
18154 * Using GNAT from the Tornado 2 Project Facility::
18155 * Frequently Asked Questions for VxWorks::
18156 @end menu
18157
18158 @node Kernel Configuration for VxWorks
18159 @section Kernel Configuration for VxWorks
18160
18161 @noindent
18162 When configuring your VxWorks kernel we recommend including the target
18163 shell. If you omit it from the configuration, you may get undefined
18164 symbols at load time, e.g.
18165
18166 @smallexample
18167 -> ld < hello.exe
18168 Loading hello.exe
18169 Undefined symbols:
18170 mkdir
18171 @end smallexample
18172
18173 @noindent
18174 Generally, such undefined symbols are harmless since these are used by
18175 optional parts of the GNAT run time. However if running your application
18176 generates a VxWorks exception or illegal instruction, you should reconfigure
18177 your kernel to resolve these symbols.
18178
18179 @node Kernel Compilation Issues for VxWorks
18180 @section Kernel Compilation Issues for VxWorks
18181
18182 @noindent
18183 If you plan to link an Ada module with a Tornado 2 Kernel, follow these steps.
18184 (Note that these recommendations apply to @file{cygnus-2.7.2-960126},
18185 shipped with Tornado 2 as the C compiler toolchain.)
18186
18187 @itemize @bullet
18188 @item
18189 Compile your Ada module without linking it with the VxWorks Library:
18190 @smallexample
18191 gnatmake foo.adb -largs -nostdlib
18192 @end smallexample
18193
18194 @item
18195 Edit your makefile and add on the @code{LIBS} line the exact path and name
18196 of the GCC library file provided with GNAT.
18197 @smallexample
18198 LIBS             = $(WIND_BASE)/target/lib/libPPC604gnuvx.a \
18199 /opt/gnu/gnat/lib/gcc-lib/powerpc-wrs-vxworks/2.8.1/libgcc.a
18200 @end smallexample
18201
18202 @noindent
18203 To know the exact name and location of this file, type
18204 @code{<arch>-gcc -print-libgcc-file-name} in a console. Note that this version of GCC is the
18205 one provided with GNAT.
18206 @smallexample
18207 ~ >powerpc-wrs-vxworks-gcc -print-libgcc-file-name
18208 /opt/gnu/gnat/lib/gcc-lib/powerpc-wrs-vxworks/2.8.1/libgcc.a
18209 @end smallexample
18210 @end itemize
18211
18212
18213 @node Handling Relocation Issues for PowerPc Targets
18214 @section Handling Relocation Issues for PowerPc Targets
18215 @cindex Relocation issues for PowerPc VxWorks targets
18216 @cindex PowerPc VxWorks, relocation issues
18217 @cindex VxWorks PowerPc, relocation issues
18218
18219 @noindent
18220 Under certain circumstances, loading a program onto a PowerPC
18221 board will fail with the message
18222 @emph{Relocation value does not fit in 24 bits}.
18223
18224 For some background on this issue, please refer to WRS' SPRs
18225 6040, 20257, and 22767.
18226 In summary,
18227 VxWorks on the PowerPC follows the variation of the SVR4 ABI known
18228 as the Embedded ABI (@emph{EABI}).
18229 @cindex Embedded ABI (for VxWorks on PowerPc)
18230 @cindex EABI (for VxWorks on PowerPc)
18231 In order to save space and time in
18232 embedded applications, the EABI specifies that the default for
18233 subprogram calls should be the branch instruction with relative
18234 addressing using an immediate operand.  The immediate operand
18235 to this instruction (relative address) is 24 bits wide.  It
18236 is sign extended and 2#00# is appended for the last 2 bits (all
18237 instructions must be on a 4 byte boundary).
18238 The resulting
18239 26 bit offset means that the target of the branch must be within
18240 +/- 32 Mbytes of the relative branch instruction.  When VxWorks
18241 is loading a program it completes the linking phase by
18242 resolving all of the unresolved references in the object being
18243 loaded.  When one of those references is a relative address in
18244 a branch instruction, and the linker determines that the target
18245 is more than 32 Mbytes away from the branch, the error occurs.
18246
18247 This only happens when the BSP is configured to use
18248 more than 32 MBytes of memory.  The VxWorks kernel is loaded into
18249 low memory addresses, and the error usually occurs when the target
18250 loader is used (because it loads objects into high memory, and thus
18251 calls from the program to the VxWorks kernel can be too far).
18252 @cindex VxWorks kernel (relocation issues on PowerPc)
18253
18254 One way to solve this problem is to use the Tornado
18255 host loader; this will place programs in low memory, close to the kernel.
18256
18257 Another approach is to make use of the @code{-mlongcall} option to the
18258 compiler;
18259 @cindex @code{-mlongcall} (gcc)
18260 GNAT has incorporated WRS'
18261 gcc modification that implements this option.
18262 If a subprogram call is
18263 compiled with the @code{-mlongcall} option, then the generated code
18264 constructs an absolute address in a register and uses a branch
18265 instruction with absolute addressing mode.
18266
18267 Starting with release 3.15, the GNAT runtime libraries that are
18268 distributed are compiled with the @code{-mlongcall} option.  In many
18269 cases the use of these libraries is sufficient to avoid the
18270 relocation problem, since it is the runtime library that contains
18271 calls to the VxWorks kernel that need to span the address space gap.
18272 If you are using an earlier GNAT release or a manually-built runtime,
18273 you should recompile the GNAT runtime library with @code{-mlongcall};
18274 you can use the
18275 @file{Makefile.adalib} file from the @file{adalib} directory.
18276
18277 Application code may need to be compiled with @code{-mlongcall} if there
18278 are calls directly to the kernel, the application is very large,
18279 or in some specialized linking/loading scenarios.
18280
18281 You can compile individual files with @code{-mlongcall} by placing this
18282 option on the @code{gcc} command line (for brevity we are omitting the
18283 @code{powerpc-wrs-vxworks-} prefix on the commands shown in this
18284 paragraph).
18285 If you provide @code{-mlongcall} as an option for @code{gnatmake}, it will be
18286 passed to all invocations of @code{gcc} that @code{gnatmake} directly performs.
18287 Note that one other compilation is made by @code{gnatlink}, on the file created
18288 by @code{gnatbind} for the elaboration package body
18289 (see @ref{Binding Using gnatbind}).
18290 Passing @code{-mlongcall} to @code{gnatlink}, either directly
18291 on the @code{gnatlink} command line or by including @code{-mlongcall} in the
18292 @code{-largs} list of @code{gnatmake}, will direct @code{gnatlink} to compile the
18293 binder file with the @code{-mlongcall} option.
18294
18295 To see the effect of @code{-mlongcall}, consider the following small example:
18296
18297 @smallexample
18298    procedure Proc is
18299       procedure Imported_Proc;
18300       pragma Import (Ada, Imported_Proc);
18301    begin
18302       Imported_Proc;
18303    end;
18304 @end smallexample
18305
18306 @noindent
18307 If you compile @code{Proc} with the default options (no @code{-mlongcall}), the following code is generated:
18308
18309 @smallexample
18310    _ada_proc:
18311            ...
18312            bl imported_proc
18313            ...
18314 @end smallexample
18315
18316 @noindent
18317 In contrast, here is the result with the @code{-mlongcall} option:
18318
18319 @smallexample
18320    _ada_proc:
18321            ...
18322            addis 9,0,imported_proc@@ha
18323            addi 0,9,imported_proc@@l
18324            mtlr 0
18325            blrl
18326            ...
18327 @end smallexample
18328
18329
18330 @node Support for Software Floating Point on PowerPC Processors
18331 @section Support for Software Floating Point on PowerPC Processors
18332
18333 @noindent
18334 The PowerPC 860 processor does not have hardware floating-point support.
18335 In order to build and run GNAT modules properly, you need to install and
18336 invoke software-emulated floating-point support as follows:
18337
18338 @itemize @bullet
18339 @item
18340 At installation time:
18341 @itemize @bullet
18342 @item
18343 Create a file @file{ada_object_path} under the directory
18344 @file{BASE\lib\gcc-lib\powerpc-wrs-vxworks\2.8.1}
18345 (by default @file{BASE}=@file{c:\gnatpro})
18346 containing the following line:
18347 @smallexample
18348 rts-soft-float\adalib
18349 @end smallexample
18350
18351 @item
18352 Create a file @file{ada_source_path} under the directory
18353 @file{BASE\lib\gcc-lib\powerpc-wrs-vxworks\2.8.1}
18354 (by default @file{BASE}=@file{c:\gnatpro})
18355 containing the following line:
18356 @smallexample
18357 rts-soft-float\adainclude
18358 @end smallexample
18359 @end itemize
18360
18361 @item
18362 When using the compiler, specify @option{-msoft-float}
18363 as a compiler and a linker option, e.g.:
18364 @smallexample
18365 $powerpc-wrs-vxworks-gnatmake -msoft-float module -largs -msoft-float
18366 @end smallexample
18367 @end itemize
18368
18369
18370 @node Interrupt Handling for VxWorks
18371 @section Interrupt Handling for VxWorks
18372
18373 @noindent
18374 GNAT offers a range of options for hardware interrupt handling. In rough
18375 order of latency and lack of restrictions:
18376
18377 @itemize @bullet
18378 @item Directly vectored interrupt procedure handlers
18379 @item Directly vectored interrupt procedures that signal a task using
18380 a suspension object
18381 @item Ada 95 protected procedure handlers for interrupts
18382 @item Ada 83 style interrupt entry handlers for interrupts
18383 @end itemize
18384
18385 @noindent
18386 In general, the range of possible solutions trades off latency versus
18387 restrictions in the handler code.  Restrictions in direct vectored
18388 interrupt handlers  are documented in the @cite{VxWorks Programmer's Guide}.
18389 Protected procedure handlers have only the
18390 restriction that no potentially blocking operations are performed within
18391 the handler.  Interrupt entries have no restrictions.  We recommend the
18392 use of the protected procedure mechanism as providing the best balance
18393 of these considerations for most applications.
18394
18395 All handler types must explicitly perform any required hardware cleanups,
18396 such as issuing an end-of-interrupt if necessary.
18397
18398 For VxWorks/AE, applications that handle interrupts must be loaded into
18399 the kernel protection domain.
18400
18401 @itemize @bullet
18402 @item Direct Vectored Interrupt Routines
18403
18404 @noindent
18405 This approach provides the lowest interrupt latency, but has the most
18406 restrictions on what VxWorks and Ada runtime calls can be made, as well
18407 as on what Ada entities are accessible to the handler code.  Such handlers
18408 are most useful when there are stringent latency requirements, and very
18409 little processing is to be performed in the handler.   Access to the
18410 necessary VxWorks routines for setting up such handlers is provided in
18411 the package @code{Interfaces.VxWorks}.
18412
18413 VxWorks restrictions are described in the @cite{VxWorks Programmer's Manual}.
18414 Note in particular that floating point context is not automatically saved and
18415 restored when interrupts are vectored to the handler.  If the handler is
18416 to execute floating point instructions, the statements involved must be
18417 bracketed by a pair of calls to @code{fppSave} and @code{fppRestore} defined
18418 in @code{Interfaces.VxWorks}.
18419
18420 In general, it is a good idea to save and restore the handler that was
18421 installed prior to application startup.  The routines @code{intVecGet}
18422 and @code{intVecSet} are used for this purpose.  The Ada handler code
18423 is installed into the vector table using routine @code{intConnect},
18424 which generates wrapper code to save and restore registers.
18425
18426 Example:
18427
18428 @smallexample
18429 with Interfaces.VxWorks; use Interfaces.VxWorks;
18430 with System;
18431
18432 package P is
18433
18434    Count : Natural := 0;
18435    pragma Atomic (Count);
18436
18437    --  Interrupt level used by this example
18438    Level : constant := 1;
18439
18440    --  Be sure to use a reasonable interrupt number for the target
18441    --  board!  Refer to the BSP for details.
18442    Interrupt : constant := 16#14#;
18443
18444    procedure Handler (Parameter : System.Address);
18445
18446 end P;
18447
18448 package body P is
18449
18450    procedure Handler (parameter : System.Address) is
18451       S : Status;
18452    begin
18453       Count := Count + 1;
18454       --  Acknowledge interrupt.  Not necessary for all interrupts.
18455       S := sysBusIntAck (intLevel => Level);
18456    end Handler;
18457 end P;
18458
18459 with Interfaces.VxWorks; use Interfaces.VxWorks;
18460 with Ada.Text_IO; use Ada.Text_IO;
18461
18462 with P; use P;
18463 procedure Useint is
18464    task T;
18465
18466    S : Status;
18467
18468    task body T is
18469    begin
18470       for I in 1 .. 10 loop
18471          Put_Line ("Generating an interrupt...");
18472          delay 1.0;
18473
18474          --  Generate interrupt, using interrupt number
18475          S := sysBusIntGen (Level, Interrupt);
18476       end loop;
18477    end T;
18478
18479    --  Save old handler
18480    Old_Handler : VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interrupt));
18481 begin
18482    S := intConnect (INUM_TO_IVEC (Interrupt), Handler'Access);
18483    S := sysIntEnable (intLevel => Level);
18484
18485    for I in 1 .. 10 loop
18486       delay 2.0;
18487       Put_Line ("value of count:" & P.Count'Img);
18488    end loop;
18489
18490    --  Restore previous handler
18491    S := sysIntDisable (intLevel => Level);
18492    intVecSet (INUM_TO_IVEC (Interrupt), Old_Handler);
18493 end Useint;
18494 @end smallexample
18495
18496 @item Direct Vectored Interrupt Routines
18497
18498 @noindent
18499 A variation on the direct vectored routine that allows for less restrictive
18500 handler code is to separate the interrupt processing into two levels.
18501
18502 The first level is the same as in the previous section.  Here we perform
18503 simple hardware actions and signal a task pending on a Suspension_Object
18504 (defined in @code{Ada.Synchronous_Task_Control}) to perform the more complex
18505 and time-consuming operations.  The routine @code{Set_True} signals a task
18506 whose body loops and pends on the suspension object using @code{Suspend_Until_True}.
18507 The suspension object is declared in a scope global to both the handler and
18508 the task. This approach can be thought of as a slightly higher-level
18509 application of the @code{C} example using a binary semaphore given in the
18510 VxWorks Programmer's Manual.  In fact, the implementation of
18511 @code{Ada.Synchronous_Task_Control} is a very thin wrapper around a VxWorks
18512 binary semaphore.
18513
18514 This approach has a latency between the direct vectored approach and the
18515 protected procedure approach.  There are no restrictions in the Ada task
18516 code, while the handler code has the same restrictions as any other
18517 direct interrupt handler.
18518
18519 Example:
18520
18521 @smallexample
18522 with System;
18523 package Sem_Handler is
18524
18525    Count : Natural := 0;
18526    pragma Atomic (Count);
18527
18528    --  Interrupt level used by this example
18529    Level : constant := 1;
18530    Interrupt : constant := 16#14#;
18531
18532    --  Interrupt handler providing "immediate" handling
18533    procedure Handler (Param : System.Address);
18534
18535    --  Task whose body provides "deferred" handling
18536    task Receiver is
18537        pragma Interrupt_Priority
18538           (System.Interrupt_Priority'First + Level + 1);
18539     end Receiver;
18540
18541 end Sem_Handler;
18542
18543 with Ada.Synchronous_Task_Control; use Ada.Synchronous_Task_Control;
18544 with Interfaces.VxWorks; use Interfaces.VxWorks;
18545 package body Sema_Handler is
18546
18547    SO : Suspension_Object;
18548
18549    task body Receiver is
18550    begin
18551       loop
18552          --  Wait for notification from immediate handler
18553          Suspend_Until_True (SO);
18554
18555          --  Interrupt processing
18556          Count := Count + 1;
18557       end loop;
18558    end Receiver;
18559
18560    procedure Handler (Param : System.Address) is
18561       S : STATUS;
18562    begin
18563       --  Hardware cleanup, if necessary
18564       S := sysBusIntAck (Level);
18565
18566       --  Signal the task
18567       Set_True (SO);
18568    end Handler;
18569
18570 end Sem_Handler;
18571
18572 with Interfaces.VxWorks; use Interfaces.VxWorks;
18573 with Ada.Text_IO; use Ada.Text_IO;
18574 with Sem_Handler; use Sem_Handler;
18575 procedure Useint is
18576
18577    S : STATUS;
18578
18579    task T;
18580
18581    task body T is
18582    begin
18583       for I in 1 .. 10 loop
18584          Put_Line ("Generating an interrupt...");
18585          delay 1.0;
18586
18587          --  Generate interrupt, using interrupt number
18588          S := sysBusIntGen (Level, Interrupt);
18589       end loop;
18590    end T;
18591
18592    --  Save old handler
18593    Old_Handler : VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interrupt));
18594 begin
18595    S := intConnect (INUM_TO_IVEC (Interrupt), Handler'Access);
18596    S := sysIntEnable (intLevel => Level);
18597
18598    for I in 1 .. 10 loop
18599       delay 2.0;
18600       Put_Line ("value of Count:" & Sem_Handler.Count'Img);
18601    end loop;
18602
18603    --  Restore handler
18604    S := sysIntDisable (intLevel => Level);
18605    intVecSet (INUM_TO_IVEC (Interrupt), Old_Handler);
18606    abort Receiver;
18607 end Useint;
18608 @end smallexample
18609
18610 @item Protected Procedure Handlers for Interrupts
18611
18612 @noindent
18613 This is the recommended default mechanism for interrupt handling.
18614 It essentially wraps the hybrid handler / task mechanism in a higher-level
18615 abstraction, and provides a good balance between latency and capability.
18616
18617 Vectored interrupts are designated by their interrupt number, starting from
18618 0 and ranging to the number of entries in the interrupt vector table - 1.
18619
18620 In the GNAT VxWorks implementation, the following priority mappings are used:
18621 @itemize @bullet
18622 @item Normal task priorities are in the range 0 .. 245.
18623 @item Interrupt priority 246 is used by the GNAT @code{Interrupt_Manager}
18624 task.
18625 @item Interrupt priority 247 is used for vectored interrupts
18626 that do not correspond to those generated via an interrupt controller.
18627 @item Interrupt priorities 248 .. 255 correspond to PIC interrupt levels
18628 0 .. 7.
18629 @item Priority 256 is reserved to the VxWorks kernel.
18630 @end itemize
18631
18632 Except for reserved priorities, the above are recommendations for setting the
18633 ceiling priority of a protected object that handles interrupts, or the
18634 priority of a task with interrupt entries.  It's a very good idea to follow
18635 these recommendations for vectored interrupts that come in through the PIC
18636 as it will determine the priority of execution of the code in the protected
18637 procedure or interrupt entry.
18638
18639 No vectored interrupt numbers are reserved in this implementation, because
18640 dedicated interrupts are determined by the board support package. Obviously,
18641 careful consideration of the hardware is necessary when handling interrupts.
18642 The VxWorks BSP for the board is the definitive reference for interrupt
18643 assignments.
18644
18645 Example:
18646
18647 @smallexample
18648 package PO_Handler is
18649
18650    --  Interrupt level used by this example
18651    Level : constant := 1;
18652
18653    Interrupt : constant := 16#14#;
18654
18655    protected Protected_Handler is
18656       procedure Handler;
18657       pragma Attach_Handler (Handler, Interrupt);
18658
18659       function Count return Natural;
18660
18661       pragma Interrupt_Priority (248);
18662    private
18663       The_Count : Natural := 0;
18664    end Protected_Handler;
18665
18666 end PO_Handler;
18667
18668 with Interfaces.VxWorks; use Interfaces.VxWorks;
18669 package body PO_Handler is
18670
18671    protected body Protected_Handler is
18672
18673       procedure Handler is
18674          S : Status;
18675       begin
18676          --  Hardware cleanup if necessary
18677          S := sysBusIntAck (Level);
18678
18679          --  Interrupt processing
18680          The_Count := The_Count + 1;
18681       end Handler;
18682
18683       function Count return Natural is
18684       begin
18685          return The_Count;
18686       end Count;
18687    end Protected_Handler;
18688
18689 end PO_Handler;
18690
18691 with Interfaces.VxWorks; use Interfaces.VxWorks;
18692 with Ada.Text_IO; use Ada.Text_IO;
18693
18694 with PO_Handler; use PO_Handler;
18695 procedure Useint is
18696
18697    task T;
18698
18699    S : STATUS;
18700
18701    task body T is
18702    begin
18703       for I in 1 .. 10 loop
18704          Put_Line ("Generating an interrupt...");
18705          delay 1.0;
18706
18707          --  Generate interrupt, using interrupt number
18708          S := sysBusIntGen (Level, Interrupt);
18709       end loop;
18710    end T;
18711
18712 begin
18713    S := sysIntEnable (intLevel => Level);
18714
18715    for I in 1 .. 10 loop
18716       delay 2.0;
18717       Put_Line ("value of count:" & Protected_Handler.Count'Img);
18718    end loop;
18719
18720    S := sysIntDisable (intLevel => Level);
18721 end Useint;
18722 @end smallexample
18723
18724 @noindent
18725 This is obviously significantly higher-level and easier to write than the
18726 previous examples.
18727
18728 @item Ada 83 Style Interrupt Entries
18729
18730 GNAT provides a full implementation of the Ada 83 interrupt entry mechanism
18731 for vectored interrupts.  However, due to latency issues,
18732 we only recommend using these for backward compatibility.  The comments in
18733 the previous section regarding interrupt priorities and reserved interrupts
18734 apply here.
18735
18736 In order to associate an interrupt with an entry, GNAT provides the
18737 standard Ada convenience routine @code{Ada.Interrupts.Reference}.  It is used
18738 as follows:
18739
18740 @smallexample
18741 Interrupt_Address : constant System.Address :=
18742    Ada.Interrupts.Reference (Int_Num);
18743
18744 task Handler_Task is
18745    pragma Interrupt_Priority (248);  -- For instance
18746    entry Handler;
18747    for Handler'Address use Interrupt_Address;
18748 end Handler_Task;
18749 @end smallexample
18750
18751 @noindent
18752 Since there is no restriction within an interrupt entry on blocking operations,
18753 be sure to perform any hardware interrupt controller related operations before
18754 executing a call that could block within the entry's accept statements.  It
18755 is assumed that interrupt entries are always open alternatives when they
18756 appear within a selective wait statement.  The presence of a guard gives
18757 undefined behavior.
18758
18759 Example:
18760
18761 @smallexample
18762 with Ada.Interrupts;
18763 with System;
18764 package Task_Handler is
18765
18766    --  Interrupt level used by this example
18767    Level : constant := 1;
18768
18769    Interrupt : constant := 16#14#;
18770
18771    Interrupt_Address : constant System.Address :=
18772       Ada.Interrupts.Reference (Int_Num);
18773
18774    task Handler_Task is
18775       pragma Interrupt_Priority (248);  -- For instance
18776       entry Handler;
18777       for Handler'Address use Interrupt_Address;
18778
18779       entry Count (Value : out Natural);
18780    end Handler_Task;
18781 end Task_Handler;
18782
18783 with Interfaces.VxWorks; use Interfaces.VxWorks;
18784 package body Task_Handler is
18785
18786    task body Handler_Task is
18787       The_Count : Natural := 0;
18788       S : STATUS;
18789    begin
18790       loop
18791          select
18792             accept Handler do
18793                --  Hardware cleanup if necessary
18794                S := sysBusIntAck (Level);
18795
18796                --  Interrupt processing
18797                The_Count := The_Count + 1;
18798             end Handler;
18799          or
18800             accept Count (Value : out Natural) do
18801                Value := The_Count;
18802             end Count;
18803          end select;
18804       end loop;
18805    end Handler_Task;
18806
18807 end Handler_Task;
18808
18809 with Interfaces.VxWorks; use Interfaces.VxWorks;
18810 with Ada.Text_IO; use Ada.Text_IO;
18811
18812 with Handler_Task; use Handler_Task;
18813 procedure Useint is
18814
18815    task T;
18816
18817    S : STATUS;
18818    Current_Count : Natural := 0;
18819
18820    task body T is
18821    begin
18822       for I in 1 .. 10 loop
18823          Put_Line ("Generating an interrupt...");
18824          delay 1.0;
18825
18826          --  Generate interrupt, using interrupt number
18827          S := sysBusIntGen (Level, Interrupt);
18828       end loop;
18829    end T;
18830
18831 begin
18832    S := sysIntEnable (intLevel => Level);
18833
18834    for I in 1 .. 10 loop
18835       delay 2.0;
18836       Handler_Task.Count (Current_Count);
18837       Put_Line ("value of count:" & Current_Count'Img);
18838    end loop;
18839
18840    S := sysIntDisable (intLevel => Level);
18841    abort Handler_Task;
18842 end Useint;
18843 @end smallexample
18844 @end itemize
18845
18846
18847 @node Simulating Command Line Arguments for VxWorks
18848 @section Simulating Command Line Arguments for VxWorks
18849
18850 @noindent
18851 The GNAT implementation of @code{Ada.Command_Line} relies on the standard C
18852 symbols @code{argv} and @code{argc}.  The model for invoking "programs" under
18853 VxWorks does not provide these symbols.  The typical method for invoking a
18854 program under VxWorks is to call the @code{sp} function in order to spawn a
18855 thread in which to execute a designated function (in GNAT, this is the implicit
18856 main generated by gnatbind. @code{sp} provides the capability to push a variable
18857 number of arguments onto the stack when the function is invoked.  But this does
18858 not work for the implicit Ada main, because it has no way of knowing how many
18859 arguments might be required.  This eliminates the possibility to use
18860 @code{Ada.Command_Line}.
18861
18862 One way to solve this problem is to define symbols in the VxWorks environment,
18863 then import them into the Ada application.  For example, we could define the
18864 following package that imports two symbols, one an int and the other a string:
18865
18866 @smallexample
18867 with Interfaces.C.Strings;
18868 use Interfaces.C.Strings;
18869 package Args is
18870    --  Define and import a variable for each argument
18871    Int_Arg : Interfaces.C.Int;
18872    String_Arg : Chars_Ptr;
18873 private
18874    pragma Import (C, Int_Arg, "intarg");
18875    pragma Import (C, String_Arg, "stringarg");
18876 end Args;
18877 @end smallexample
18878
18879 @noindent
18880 An Ada unit could then use the two imported variables @code{Int_Arg} and
18881 @code{String_Arg} as follows:
18882
18883 @smallexample
18884 with Args; use Args;
18885 with Interfaces.C.Strings;
18886 use Interfaces.C, Interfaces.C.Strings;
18887 with Ada.Text_IO; use Ada.Text_IO;
18888 procedure Argtest is
18889 begin
18890    Put_Line (Int'Image (Int_Arg));
18891    Put_Line (Value (String_Arg));
18892 end Argtest;
18893 @end smallexample
18894
18895 @noindent
18896 When invoking the application from the shell, one will then set the values
18897 to be imported, and spawn the application, as follows:
18898
18899 @smallexample
18900 -> intarg=10
18901 -> stringarg="Hello"
18902 -> sp (argtest)
18903 @end smallexample
18904
18905
18906 @node Debugging Issues for VxWorks
18907 @section Debugging Issues for VxWorks
18908
18909 @noindent
18910 The debugger can be launched directly from the Tornado environment or from @code{glide}
18911 through its graphical interface: @code{gvd}. It can also be used
18912 directly in text mode as shown below:
18913 @noindent
18914 The command to run @code{GDB} in text mode is
18915
18916 @smallexample
18917 $ @i{target}-gdb
18918 @end smallexample
18919
18920 @noindent
18921 where @i{target} is the name of target of the cross GNAT
18922 compiler. In contrast with native @code{gdb}, it is not useful to give the name of
18923 the program to debug on the command line. Before starting a debugging
18924 session, one needs to connect to the VxWorks-configured board and load
18925 the relocatable object produced by @code{gnatlink}. This can be achieved
18926 by the following commands:
18927
18928 @smallexample
18929 (vxgdb) target wtx myboard
18930 (vxgdb) load program
18931 @end smallexample
18932
18933 @noindent
18934 where @code{myboard} is the host name or IP number of the target board, and
18935 @code{wtx} is the name of debugging protocol used to communicate
18936 with the VxWorks board. Early versions of VxWorks, up tp 5.2, only
18937 support the @code{<vxworks>} protocol whereas starting with VxWorks 5.3
18938 and Tornado, another protocol called  @code{<wtx>} was made available. The
18939 choice of the protocol can be made when configuring the VxWorks
18940 kernel itself. When available, the @code{<wtx>} is greatly preferable
18941 and actually the only supported protocol with GNAT. When the debugger
18942 is  launched directly from Tornado, the proper @code{target} command
18943 is automatically generated by the environment.
18944
18945 The GNAT debugger can be used for debugging multitasking programs in two
18946 different modes and some minimal understanding of these modes is
18947 necessary in order to use the debugger effectively. The two modes are:
18948
18949 @itemize @bullet
18950 @item Monotask mode: attach to, and debug, a single task.
18951 This mode is equivalent to the capabilities offered by CrossWind. The
18952 debugger interacts with a single task, while not affecting other tasks
18953 (insofar as possible). This is the DEFAULT mode.
18954
18955 @item Multitask mode:
18956 The debugger has control over all Ada tasks in an application. It is
18957 possible to gather information about all application tasks, and to
18958 switch from one to another within a single debugging session.
18959 @end itemize
18960
18961 @noindent
18962 It is not advised to switch between the two modes within a debugging
18963 session. A third mode called System mode is also available and can be
18964 used in place of the Multitask mode. Consult the Tornado documentation
18965 for this.
18966
18967 Among the criteria for selecting the appropriate mode is the effect of
18968 task synchronization on the application's behavior. Debugging a
18969 tasking application affects the timing of the application; minimizing
18970 such effects may be critical in certain situations. The two modes have
18971 different effects: monotask mode only affects the attached task:
18972 others will run normally (if possible). Multitask mode stops all tasks
18973 at each breakpoint and restarts them on single-step, next, finish or
18974 continue; this may help avoid deadlocks in the presence of task
18975 synchronization despite the inherent latency of stopping and
18976 restarting the tasks.
18977
18978 @subsection Using the debugger in monotask mode
18979
18980 @noindent
18981 There are two ways to begin your debugging session:
18982
18983 @itemize @bullet
18984 @item The program is already running on the board.
18985
18986 @noindent
18987 The sequence of commands to use this mode is:
18988 @itemize @bullet
18989 @item Launch GVD (possibly from the Tornado menu)
18990
18991 @noindent
18992 Verify that the debugger has access to the debug information of both
18993 your program and the kernel. The Console window should have a message
18994 "Looking for all loaded modules:" followed by the names of the modules
18995 on the board and "ok". If you have some error messages here instead of
18996 "ok", the debugging session may not work as expected.
18997
18998 @item Attach to the desired task using
18999 @smallexample
19000         File --> Attach...
19001 @end smallexample
19002 @noindent
19003 This task is stopped by the debugger. Other tasks continue to operate
19004 normally (unless they are blocked by synchronization with the stopped
19005 task). The source window should display the code on which the task has
19006 been stopped, and if the stack display is enabled, it should reflect
19007 the stack of the task.
19008 @end itemize
19009
19010 @item The program hasn't been loaded yet on the board
19011 @itemize @bullet
19012 @item Launch GVD (possibly from the Tornado menu)
19013 @item Load your program to the board:
19014 @smallexample
19015 File --> Open Program...
19016 @end smallexample
19017
19018 @noindent
19019 GVD should display:
19020 @smallexample
19021 Downloading your_program ...done.
19022 Reading symbols from your_program...expanding to full symbols...done.
19023 @end smallexample
19024
19025 @item Set breakpoints in your program.
19026
19027 @noindent
19028 WARNING: they must be set in the main task (if your program runs
19029 several tasks)
19030
19031 @item Run your program using one of the three methods below:
19032 @itemize @bullet
19033 @item
19034 Click on button <run> or <start>
19035
19036 @item Menu
19037 @smallexample
19038 Program --> Run/Start
19039 @end smallexample
19040
19041 @item
19042 Type in GVD's Console window
19043 @smallexample
19044 (gdb) run your_program
19045 @end smallexample
19046 @end itemize
19047 @end itemize
19048
19049 @item Whichever method you chose to start your debugging session,
19050 you can use the following commands at this point:
19051 @itemize @bullet
19052 @item  Browse sources and set breakpoints
19053 @item  Examine the call stack (Data --> call stack)
19054 @item  Go "up" and "down" in the call stack ("up" & "down" buttons)
19055 @item  Examine data
19056 (Data --> Display local variables, or any of the other methods for viewing data in GVD)
19057 @item Continue/finish
19058 @end itemize
19059
19060 Next/step/finish will only work if the top frame in the call stack has
19061 debug information.  This is almost never the case when first attaching
19062 to the task since the task is usually stopped by the attach operation
19063 in the GNAT runtime. You can verify which frames of the call stack
19064 have debug information by:
19065 @smallexample
19066 Data --> call stack
19067 <right Button> (contextual menu inside the call stack window)
19068  add "file location"
19069 @end smallexample
19070
19071 @noindent
19072 If the current frame does not have a "file location", then there is no
19073 debug information for the frame.  We strongly recommended that you set
19074 breakpoints in the source where debug information can be found and
19075 "continue" until a breakpoint is reached before using
19076 "next/step". Another convenient possibility is to use the "continue
19077 until" capability available from the contextual menu of the Source
19078 window.
19079
19080 You can also examine the state of other tasks using
19081 @smallexample
19082 Data -> tasks
19083 @end smallexample
19084
19085 @noindent
19086 but you can't "switch" to another task by clicking on the
19087 elements of the task list. If you try to, you will get an error
19088 message in GVD's console:
19089 @smallexample
19090 "Task switching is not allowed when multi-tasks mode is not active"
19091 @end smallexample
19092
19093 @noindent
19094 Once you have completed your debugging session on the attached
19095 task, you can detach from the task:
19096 @smallexample
19097 File --> detach
19098 @end smallexample
19099
19100 @noindent
19101 The task resumes normal execution at this stage.  WARNING: when you
19102 detach from a task, be sure that you are in a frame where there is
19103 debug information. Otherwise, the task won't resume properly. You can
19104 then start another attach/detach cycle if you wish.
19105
19106 Note that it is possible to launch several GVD sessions and
19107 simultaneously attach each to a distinct task in monotask mode:
19108 @smallexample
19109 File --> New Debugger...  (uncheck the box: Replace Current Debugger)
19110 File --> Attach...     (in the new window)
19111 File --> detach
19112 @end smallexample
19113 @end itemize
19114
19115
19116 @subsection Using the debugger in Multitask mode
19117
19118 @noindent
19119 The steps are as follows
19120
19121 @itemize @bullet
19122 @item
19123 Launch GVD (possibly from the Tornado menu)
19124
19125 @noindent
19126 There are two possibilities:
19127 @itemize @bullet
19128 @item
19129 If the program is already loaded on the target board, you need only verify
19130 that debug information has been found by the debugger as described
19131 above.
19132
19133 @item
19134 Otherwise, load the program on the board using
19135 @smallexample
19136 File --> Open program
19137 @end smallexample
19138 @end itemize
19139
19140 @item Set breakpoints in the desired parts of the program
19141
19142 @item Start the program
19143
19144 @noindent
19145 The simplest way to start the debugger in multitask mode is to use the
19146 menu
19147 @smallexample
19148 Program --> Run/Start
19149 @end smallexample
19150
19151 @noindent
19152 and check the box "enable vxWorks multi-tasks mode".
19153 You can also use the following gdb commands in the console window
19154 @smallexample
19155         (gdb) set multi-tasks-mode on
19156         (gdb) run your_program
19157 @end smallexample
19158
19159 @item Debug the stopped program
19160
19161 @noindent
19162 Once stopped at a breakpoint
19163 (or if you pressed the "stop" button), you can use all the standard
19164 commands listed for monotask mode + task switching (using Data -->
19165 tasks). Using next/step under this mode is possible with the same
19166 restrictions as for monotask mode, but is not recommended because all
19167 tasks are restarted, leading to the possibility that a different task
19168 hits a breakpoint before the stepping operation has completed.  Such
19169 an occurrence can result in a confusing state for both the user and
19170 the debugger. So we strongly suggest the use of only breakpoints and
19171 "continue" in this mode.
19172 @end itemize
19173
19174 A final reminder: whatever the mode, whether you are debugging or not,
19175 the program has to be reloaded before each new execution, so that data
19176 initialized by the loader is set correctly. For instance, if you wish
19177 to restart the same execution of the same program, you can use the
19178 following sequence of gdb commands in the console window:
19179 @smallexample
19180 (gdb) detach
19181 (gdb) unload your_program(.exe)
19182 (gdb) load your_program(.exe)
19183 (gdb) run your_program
19184 @end smallexample
19185
19186
19187 @node Using GNAT from the Tornado 2 Project Facility
19188 @section Using GNAT from the Tornado 2 Project Facility
19189 @cindex Tornado II Project
19190
19191 @menu
19192 * The GNAT Toolchain as Used from the Tornado 2 Project Facility::
19193 * Building a Simple Application::
19194 * Mixing C and Ada Code in a Tornado 2 Project::
19195 * Compilation Switches::
19196 * Autoscale and Minimal Kernel Configuration::
19197 * Adapting BSPs to GNAT::
19198 * Using GNAT Project Files in a Tornado 2 Project::
19199 @end menu
19200
19201 @noindent
19202 This section describes how to add an Ada module in a Tornado project
19203 using the Tornado 2 Project facility described in
19204 @cite{Tornado User's Guide}, Chapter 4.
19205 All recommendations apply for both 'Downloadable Modules' and 'Kernel'
19206 project types.
19207
19208
19209 @node The GNAT Toolchain as Used from the Tornado 2 Project Facility
19210 @subsection The GNAT Toolchain as Used from the Tornado 2 Project Facility
19211
19212 @noindent
19213 Tornado 2 allows you to integrate third-party C toolchains.
19214 (@cite{Tornado 2 API Programmer's Guide}, Chapter 7).
19215 Thus the GNAT toolchain will be seen as a new C toolchain when used from
19216 the Tornado 2 Project Facility. For each processor you can compile for,
19217 you will find a <proc>gnat toolchain, e.g. PPC604gnat. These toolchains will
19218 allow you to include Ada modules into your projects, and simply build them.
19219
19220 The name of the so-called C compiler is @emph{cc_gnat_<arch>}, the name
19221 of the 'linker' is @emph{ld_gnat_<arch>}, where <arch> is an architecture; e.g.,
19222 PPC. These scripts will call the correct executables during the compilation or
19223 link processes, thus the C compiler, the C linker, or the GNAT toolchain,
19224 depending on the context.
19225
19226
19227 @node  Building a Simple Application
19228 @subsection  Building a Simple Application
19229
19230 @noindent
19231 First, create a new project, using one of the gnat toolchains.
19232
19233 To add an Ada source file to the current project, just click on
19234 @code{Project -> Add/Include}, browse to the relevant file, and include it.
19235 The Ada source file included should be the Ada entry point. Only
19236 one Ada entry point is allowed in a project. Any other required Ada source
19237 files will be automatically compiled and linked by the underlying tools.
19238
19239 You can now compile the project, @code{Build->Rebuild all}.
19240 A log of the compilation process can be found in the build directory, in
19241 @file{gnatbuild.log}. It contains all the calls executed by the scripts, and
19242 associated information.
19243
19244
19245 @node Mixing C and Ada Code in a Tornado 2 Project
19246 @subsection Mixing C and Ada Code in a Tornado 2 Project
19247
19248 @noindent
19249 You can mix C and Ada code in your projects. Your source files and the build
19250 options should comply with the recommendations from the section
19251 @cite{Interfacing to C}.
19252 This means that you can have several or no C source files, and one or no Ada entry
19253 point in your Tornado 2 Project.
19254
19255
19256 @node Compilation Switches
19257 @subsection Compilation Switches
19258 @noindent
19259 Once you have included all your source files, you may modify some compilation
19260 and linking options.
19261 To pass specific options to the GNAT toolchain, go to the Project's build
19262 settings, on the @code{C/C++ Compiler} tab, and add your arguments in the
19263 input window.
19264
19265 You must comply with several rules to pass arguments to GNAT.
19266 Arguments to be passed should be
19267
19268 @itemize @bullet
19269
19270 @item after any arguments passed to the C toolchain.
19271
19272 @item prefixed depending on the tool that uses them, with the following syntax
19273
19274 @itemize @bullet
19275 @item @code{-cargs @emph{gnatmake-options}} to pass arguments to gnatmake
19276 @item @code{-bargs @emph{gnatbind-options}} to pass arguments to gnatbind
19277 @item @code{-largs @emph{gnatlink-options}} to pass arguments to gnatlink
19278 @end itemize
19279 @end itemize
19280
19281 @noindent
19282 You will find more information on the compilation process of Ada source files
19283 in the section @cite{The GNAT Compilation Model}.
19284 For a list of all available switches, refer to the sections describing
19285 @code{gnatmake}, @code{gnatbind} and @code{gnatlink}.
19286
19287 Here is an example that passes the option @code{-v} to the GNAT compiler :
19288 @smallexample
19289 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
19290 -fvolatile -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
19291 -cargs -v
19292 @end smallexample
19293
19294 @noindent
19295 Here is an example that passes the option @code{-v} to the GNAT compiler, binder and linker,
19296 and @code{-v} and @code{-g} to the compiler :
19297 @smallexample
19298 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
19299 -fvolatile -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
19300 -cargs -v -g -O2 -bargs -v -largs -v
19301 @end smallexample
19302
19303 @noindent
19304 In both examples, the following arguments have been automatically added by the Project
19305 Facility, and will be used by the C compiler.
19306 @smallexample
19307 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
19308 -fvolatile -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
19309 @end smallexample
19310
19311 @noindent
19312 Note: The @code{-prjtype $(PRJ_TYPE)} option present in a few input
19313 boxes is used by the GNAT toolchain. It is required for the compilation
19314 process. You should not remove it from any input box.
19315
19316
19317 @node Autoscale and Minimal Kernel Configuration
19318 @subsection Autoscale and Minimal Kernel Configuration
19319
19320 @noindent
19321 The Autoscale feature, present in the Project Facility  can be used on your
19322 VxWorks Kernel projects to determine the minimum set of components required
19323 for your kernel to work.
19324 (Please refer to the @cite{Tornado II User's Guide} Section 4.4 for more details.)
19325 This feature is also available for projects involving Ada code. Just click on
19326 @code{Project->Autoscale} to launch a check and determine the minimal kernel
19327 configuration.
19328
19329
19330 @node Adapting BSPs to GNAT
19331 @subsection Adapting BSPs to GNAT
19332
19333 @noindent
19334 To use your Board Support Packages with the GNAT toolchain, you will have to adapt them,
19335 either manually or using the @code{adaptbsp4gnat} script.
19336 This procedure is described in the @cite{Tornado API Programmer's Guide},
19337 Chapter 7.
19338 Here is a summary of this setup, depending on the context.
19339
19340 @itemize @bullet
19341 @item To do the adaptation manually:
19342
19343 @itemize @bullet
19344
19345 @item Copy your BSP directory contents into a new directory
19346
19347 @item Go to this directory
19348
19349 @item Edit the file @file{Makefile},
19350
19351 @itemize @bullet
19352 @item Set tool to gnat, @code{TOOL=gnat}
19353
19354 @item Reverse the order of the following lines
19355 @itemize @bullet
19356 @item @code{include $(TGT_DIR)/h/make/make.$(CPU)$(TOOL)}
19357 @item @code{include $(TGT_DIR)/h/make/defs.$(WIND_HOST_TYPE)}
19358 @end itemize
19359
19360 @end itemize
19361
19362 @end itemize
19363
19364 @item To do the adaptation automatically, you may use the @code{adaptbsp4gnat}
19365 script. Its syntax is @code{adaptbsp4gnat <path_to_bsp>}.
19366
19367 @noindent
19368 This script follows the different steps described above to perform the
19369 adaptation.
19370 The name of the new bsp is given after the modification.  By default, if
19371 @file{<bsp>} is the name of your BSP, @file{<bsp>-gnat}, will be the name of
19372 the BSP created.
19373 @end itemize
19374
19375
19376 @node Using GNAT Project Files in a Tornado 2 Project
19377 @subsection Using GNAT Project Files in a Tornado 2 Project
19378
19379 @noindent
19380 You can use GNAT Project files to compile your Ada files.
19381 To do so, you need to use the @option{-Pproject_file.gpr} option from @command{gnatmake}.
19382 The path to the project file can be either absolute, or relative to the build
19383 directory, i.e. where the executable will be placed (e.g. @file{~/myproject/PPC604gnat}).
19384 Your project file should set the @code{Object_Dir} variable to a specific
19385 value.
19386 @smallexample
19387 project Sample is
19388
19389    Target := external ("TARGET_DIR");
19390    for Object_Dir use Target;
19391
19392 end Sample;
19393 @end smallexample
19394
19395
19396 @node Frequently Asked Questions for VxWorks
19397 @section Frequently Asked Questions for VxWorks
19398
19399 @itemize @bullet
19400
19401 @item
19402 When I run my program twice on the board, it does not work, why?
19403
19404 @noindent
19405 Usually, Ada programs require elaboration and finalization, so the
19406 compiler creates a wrapper procedure whose name is the same as the Ada
19407 name of the main subprogram, which takes care of calling the elaboration
19408 and finalization routines before and after your program. But the static
19409 part of the elaboration is taken care of while loading the program
19410 itself and thus if you launch it twice this part of the elaboration will
19411 not be performed. This affects the proper elaboration of the
19412 GNAT runtime and thus it is mandatory to reload your program before
19413 relaunching it.
19414
19415 @item
19416 Can I load a collection of subprograms rather than a standalone program?
19417
19418 @noindent
19419 It is possible to write Ada programs with multiple entry points which
19420 can be called from the VxWorks shell; you just need to consider your
19421 main program as the VxWorks shell itself and generate an Ada subsystem
19422 callable from outside @xref{Binding with Non-Ada Main Programs}. If you
19423 use this method, you need to call @code{adainit} manually before calling
19424 any Ada entry point.
19425
19426 @item
19427 When I use the @code{break exception} command, I get the message
19428 @code{"exception" is not a function}, why?
19429
19430 You are not in the proper language mode. Issue the command:
19431 @smallexample
19432 (vxgdb) set language ada
19433 @end smallexample
19434
19435 @item
19436 When I load a large application from the VxWorks shell using the "ld"
19437 command, the load hangs and never finishes. How can I load large
19438 executables?
19439
19440 This is a classic VxWorks problem when using the default "rsh" communication
19441 method. Using NFS instead should work. Use the @code{nfsShowMount} command to
19442 verify that your program is in a NFS mounted directory.
19443
19444 @item
19445 When I load a large application from the debugger using the wtx target
19446 connection, the load never finishes, why?
19447
19448 Make sure that the memory cache size parameter of the target server is
19449 large enough. (@code{target -m big_enough_size}, or Memory cache size box in GUI.)
19450 See @cite{Tornado 1.01 API Programming Guide}, Section 3.6.2.
19451
19452 @item
19453 When I spawn my program under the VxWorks shell, interactive input does
19454 not work, why?
19455
19456 Only programs directly launched from the shell can have interactive
19457 input. For a program spawned with the @code{sp} or @code{taskSpawn}
19458 command, you need to have file redirection for input:
19459 @smallexample
19460 ->    # here you can have interactive input
19461 -> main
19462 ->    # here you cannot
19463 -> sp main
19464 ->    # neither here
19465 -> taskSpawn("ess",100,0,8000000,main)
19466 ->    # but you can input from a file:
19467 -> taskSpawn("Bae",100,0,8000000,main) < input_file
19468 @end smallexample
19469 @end itemize
19470
19471
19472 @node LynxOS Topics
19473 @chapter LynxOS Topics
19474 @noindent
19475 This chapter describes topics that are specific to the GNAT for LynxOS
19476 cross configurations.
19477
19478 @menu
19479 * Getting Started with GNAT on LynxOS::
19480 * Kernel Configuration for LynxOS::
19481 * Patch Level Issues for LynxOS::
19482 * Debugging Issues for LynxOS::
19483 * An Example Debugging Session for LynxOS::
19484 @end menu
19485
19486 @node Getting Started with GNAT on LynxOS
19487 @section Getting Started with GNAT on LynxOS
19488
19489 @noindent
19490 This section is a starting point for using GNAT to develop and
19491 execute Ada 95 programs for LynuxWorks' LynxOS target environment from a
19492 Unix host environment.
19493 We assume that you know how to use GNAT in a native environment
19494 and how to start a telnet or other login session to connect to your LynxOS board.
19495
19496 To compile code for a LynxOS system running on a PowerPC
19497 board, the basic compiler command is
19498 @command{powerpc-xcoff-lynxos-gcc}.
19499
19500 With GNAT, the easiest way to build the basic @code{Hello World} program is
19501 with @code{gnatmake}. For the LynxOS PowerPC target this would look
19502 like:
19503
19504 @smallexample
19505 $ powerpc-xcoff-lynxos-gnatmake hello
19506 @i{powerpc-xcoff-lynxos-gcc -c hello.adb
19507 powerpc-xcoff-lynxos-gnatbind -x hello.ali
19508 powerpc-xcoff-lynxos-gnatlink hello.ali}
19509 @end smallexample
19510
19511 @noindent
19512 (The first line is the command entered by the user -- the subseqent three
19513 are the programs run by @code{gnatmake}.)
19514
19515 This creates the executable @command{hello}" which you then need to load on the
19516 board (using ftp or an NFS directory for example) to run it.
19517
19518
19519 @node Kernel Configuration for LynxOS
19520 @section Kernel Configuration for LynxOS
19521
19522 @noindent
19523 The appropriate configuration for your LynxOS kernel depends
19524 on the target system and the requirements of your application. GNAT itself
19525 adds no additional demands; however in some situations it may be appropriate
19526 to increase the conservative
19527 resource assumptions made by the default configuration.
19528
19529 Kernel parameters limiting the maximum number of file descriptors,
19530 kernel and user threads, synchronization objects, etc., may be set in the
19531 file @file{uparam.h}. You may also wish to modify the file
19532 @file{/etc/starttab}, which places limits on data, stack, and core file
19533 size. See the documentation provided by LynuxWorks for more information.
19534
19535
19536 @node Patch Level Issues for LynxOS
19537 @section Patch Level Issues for LynxOS
19538
19539 @noindent
19540 The GNAT runtime requires that your system run at patch level 040 or
19541 later. Please see the file @file{PatchCompatibility.txt} from the
19542 distribution for more information.
19543
19544
19545 @node Debugging Issues for LynxOS
19546 @section Debugging Issues for LynxOS
19547
19548 @noindent
19549 GNAT's debugger is based on the same GNU gdb technology as the debugger
19550 provided by LynxOS, though with a great number of extensions and
19551 enhancements to support the Ada language and GNAT. The LynxOS
19552 documentation is relevant to understanding how to get the debugger
19553 started if you run into difficulties.
19554
19555 To demonstrate a debugging session, we will use a slightly more complex
19556 program called @file{demo1.adb}, which can be found in the @file{examples}
19557 directory of the GNAT distribution. This program is compiled with
19558 debugging information as follows:
19559
19560 @smallexample
19561 $ powerpc-xcoff-lynxos-gnatmake -g demo1
19562 powerpc-xcoff-lynxos-gcc -c -g demo1.adb
19563 powerpc-xcoff-lynxos-gcc -c -g gen_list.adb
19564 powerpc-xcoff-lynxos-gcc -c -g instr.adb
19565 powerpc-xcoff-lynxos-gnatbind -x demo1.ali
19566 powerpc-xcoff-lynxos-gnatlink -g demo1.ali
19567 @end smallexample
19568
19569 @noindent
19570 Once the executable is created, copy it to your working directory on the
19571 board. In this directory, you will have to launch the gdb server and
19572 choose a free port number on your TCP/IP socket. Presuming the Internet
19573 hostname of the board is @file{myboard} and the port chosen is 2345,
19574 issue the following command:
19575
19576 @smallexample
19577 myboard> gdbserver myboard:2345 demo1
19578 @end smallexample
19579
19580 @noindent
19581 Then return to your host environment.
19582
19583 The graphical debugger interface, @command{gvd}, supports both native
19584 and cross environments at the same time. @command{gvd} can be launched from
19585 @command{Glide} (see @file{README.Glide} for more information on customizing
19586 @command{Glide} for LynxOS) or it can be launched from the command line as
19587 follows:
19588
19589 @smallexample
19590 $ gvd --debugger powerpc-xcoff-lynxos-gdb
19591 @end smallexample
19592
19593 @noindent
19594 Then to attach to the target, enter in @command{gvd}'s command line window:
19595
19596 @smallexample
19597 (gdb) target remote myboard:2345
19598 @end smallexample
19599
19600 @noindent
19601 For more information see the GVD documentation.
19602
19603 The comments below concern debugging directly from the command line but
19604 they also apply to @command{gvd}, though in most cases an equivalent
19605 graphical command is also available.
19606
19607 To run the cross debugger from the command line without the visual
19608 interface use the command @code{powerpc-xcoff-lynxos-gdb}.
19609
19610 You will see something like:
19611
19612 @smallexample
19613 GNU gdb 4.17.gnat.3.14a1
19614 Copyright 1998 Free Software Foundation, Inc.
19615 GDB is free software, covered by the GNU General Public License, and you are
19616 welcome to change it and/or distribute copies of it under certain conditions.
19617 Type "show copying" to see the conditions.
19618 There is absolutely no warranty for GDB.  Type "show warranty" for details.
19619 This GDB was configured as "--host=sparc-sun-solaris2.5.1 --target=powerpc-xc
19620 off-lynxos".
19621 (gdb)
19622 @end smallexample
19623
19624 @noindent
19625 Where @command{(gdb)} is the debugger's prompt. The first thing to do at the
19626 prompt from within @command{gdb} is to load the symbol table from the
19627 executable:
19628
19629 @smallexample
19630 (gdb) file demo1
19631 Reading symbols from demo1...done.
19632 (gdb)
19633 @end smallexample
19634
19635 @noindent
19636 You then have to attach to the server running on the board. Issue the command:
19637
19638 @smallexample
19639 (gdb) target remote myboard:2345
19640 @end smallexample
19641
19642 @noindent
19643 After the server has been started and attached from the host, the program is
19644 running on the target but has halted execution at the very beginning.
19645 The following commands set a breakpoint and continue execution:
19646
19647 @smallexample
19648 (gdb) break demo1.adb:37
19649 Breakpoint 1 at 0x100064d0: file demo1.adb, line 37.
19650 (gdb) cont
19651 Continuing.
19652
19653 Breakpoint 1, demo1 () at demo1.adb:37
19654 37         Set_Name (Fuel, "Fuel");
19655 (gdb)
19656 @end smallexample
19657
19658 @noindent
19659 Here the execution has stopped at the breakpoint set above. Now
19660 you can use the standard @code{gdb} commands to examine the stack and
19661 program variables.
19662
19663 Note that once execution has completed, the server on the board must be
19664 restarted before a new debugging session may begin.
19665
19666 @node An Example Debugging Session for LynxOS
19667 @section An Example Debugging Session for LynxOS
19668
19669 @noindent
19670 Carrying on a little further with the debugging session, the following
19671 example illustrates some of the usual debugging commands for moving
19672 around and seeing where you are:
19673
19674 @smallexample
19675 (gdb) next
19676 38         Set_Name (Water, "Water");
19677 (gdb) bt
19678 #0  demo1 () at demo1.adb:38
19679 #1  0x10001218 in main (argc=1, argv=2147483640, envp=2147483520) at
19680 b~demo1.adb:118
19681 #2  0x10017538 in runmainthread ()
19682 #3  0x10001048 in __start ()
19683 (gdb) up
19684 #1  0x10001218 in main (argc=1, argv=2147483640, envp=2147483520) at
19685 b~demo1.adb:118
19686 118       Ada_Main_Program;
19687 (gdb) down
19688 #0  demo1 () at demo1.adb:38
19689 38         Set_Name (Water, "Water");
19690 (gdb)
19691 @end smallexample
19692
19693 @noindent
19694 To examine and modify variables (of a tagged type here):
19695
19696 @smallexample
19697 (gdb) print speed
19698 $1 = (name => "Speed         ", value => -286331154)
19699 (gdb) ptype speed
19700 type = new instr.instrument with record
19701     value: instr.speed;
19702 end record
19703 (gdb) speed.value := 3
19704 $2 = 3
19705 (gdb) print speed
19706 $3 = (name => "Speed         ", value => 3)
19707 (gdb) info local
19708 speed = (name => "Speed         ", value => 3)
19709 fuel = (name => "Fuel          ", value => -286331154)
19710 oil = (name => ' ' <repeats 14 times>, value => -286331154, size => 20,
19711   fill => 42 '*', empty => 46 '.')
19712 water = (name => ' ' <repeats 14 times>, value => -286331154, size => 20,
19713   fill => 42 '*', empty => 46 '.')
19714 time = (name => ' ' <repeats 14 times>, seconds => 0, minutes => 0, hours =>
19715 0)
19716 chrono = (name => ' ' <repeats 14 times>, seconds => 0, minutes => 0,
19717   hours => 0)
19718 db = (access demo1.dash_board.internal) 0x0
19719 (gdb)
19720 @end smallexample
19721
19722 @noindent
19723 And finally letting the program it run to completion:
19724
19725 @smallexample
19726 (gdb) c
19727 Continuing.
19728
19729 Program exited normally.
19730 (gdb)
19731 @end smallexample
19732
19733
19734 @node Performance Considerations
19735 @chapter Performance Considerations
19736 @cindex Performance
19737
19738 @noindent
19739 The GNAT system provides a number of options that allow a trade-off
19740 between
19741
19742 @itemize @bullet
19743 @item
19744 performance of the generated code
19745
19746 @item
19747 speed of compilation
19748
19749 @item
19750 minimization of dependences and recompilation
19751
19752 @item
19753 the degree of run-time checking.
19754 @end itemize
19755
19756 @noindent
19757 The defaults (if no options are selected) aim at improving the speed
19758 of compilation and minimizing dependences, at the expense of performance
19759 of the generated code:
19760
19761 @itemize @bullet
19762 @item
19763 no optimization
19764
19765 @item
19766 no inlining of subprogram calls
19767
19768 @item
19769 all run-time checks enabled except overflow and elaboration checks
19770 @end itemize
19771
19772 @noindent
19773 These options are suitable for most program development purposes. This
19774 chapter describes how you can modify these choices, and also provides
19775 some guidelines on debugging optimized code.
19776
19777 @menu
19778 * Controlling Run-Time Checks::
19779 * Optimization Levels::
19780 * Debugging Optimized Code::
19781 * Inlining of Subprograms::
19782 @end menu
19783
19784 @node Controlling Run-Time Checks
19785 @section Controlling Run-Time Checks
19786
19787 @noindent
19788 By default, GNAT generates all run-time checks, except arithmetic overflow
19789 checking for integer operations and checks for access before elaboration on
19790 subprogram calls. The latter are not required in default mode, because all
19791 necessary checking is done at compile time.
19792 @cindex @option{-gnatp} (@code{gcc})
19793 @cindex @option{-gnato} (@code{gcc})
19794 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
19795 be modified. @xref{Run-Time Checks}.
19796
19797 Our experience is that the default is suitable for most development
19798 purposes.
19799
19800 We treat integer overflow specially because these
19801 are quite expensive and in our experience are not as important as other
19802 run-time checks in the development process. Note that division by zero
19803 is not considered an overflow check, and divide by zero checks are
19804 generated where required by default.
19805
19806 Elaboration checks are off by default, and also not needed by default, since
19807 GNAT uses a static elaboration analysis approach that avoids the need for
19808 run-time checking. This manual contains a full chapter discussing the issue
19809 of elaboration checks, and if the default is not satisfactory for your use,
19810 you should read this chapter.
19811
19812 For validity checks, the minimal checks required by the Ada Reference
19813 Manual (for case statements and assignments to array elements) are on
19814 by default. These can be suppressed by use of the @option{-gnatVn} switch.
19815 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
19816 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
19817 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
19818 are also suppressed entirely if @option{-gnatp} is used.
19819
19820 @cindex Overflow checks
19821 @cindex Checks, overflow
19822 @findex Suppress
19823 @findex Unsuppress
19824 @cindex pragma Suppress
19825 @cindex pragma Unsuppress
19826 Note that the setting of the switches controls the default setting of
19827 the checks. They may be modified using either @code{pragma Suppress} (to
19828 remove checks) or @code{pragma Unsuppress} (to add back suppressed
19829 checks) in the program source.
19830
19831 @node Optimization Levels
19832 @section Optimization Levels
19833 @cindex @code{-O} (@code{gcc})
19834
19835 @noindent
19836 The default is optimization off. This results in the fastest compile
19837 times, but GNAT makes absolutely no attempt to optimize, and the
19838 generated programs are considerably larger and slower than when
19839 optimization is enabled. You can use the
19840 @code{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
19841 on the @code{gcc} command line to control the optimization level:
19842
19843 @table @code
19844 @item -O0
19845 no optimization (the default)
19846
19847 @item -O1
19848 medium level optimization
19849
19850 @item -O2
19851 full optimization
19852
19853 @item -O3
19854 full optimization, and also attempt automatic inlining of small
19855 subprograms within a unit (@pxref{Inlining of Subprograms}).
19856 @end table
19857
19858 Higher optimization levels perform more global transformations on the
19859 program and apply more expensive analysis algorithms in order to generate
19860 faster and more compact code. The price in compilation time, and the
19861 resulting improvement in execution time,
19862 both depend on the particular application and the hardware environment.
19863 You should experiment to find the best level for your application.
19864
19865 Note: Unlike some other compilation systems, @code{gcc} has
19866 been tested extensively at all optimization levels. There are some bugs
19867 which appear only with optimization turned on, but there have also been
19868 bugs which show up only in @emph{unoptimized} code. Selecting a lower
19869 level of optimization does not improve the reliability of the code
19870 generator, which in practice is highly reliable at all optimization
19871 levels.
19872
19873 Note regarding the use of @code{-O3}: The use of this optimization level
19874 is generally discouraged with GNAT, since it often results in larger
19875 executables which run more slowly. See further discussion of this point
19876 in @pxref{Inlining of Subprograms}.
19877
19878 @node Debugging Optimized Code
19879 @section Debugging Optimized Code
19880
19881 @noindent
19882 Since the compiler generates debugging tables for a compilation unit before
19883 it performs optimizations, the optimizing transformations may invalidate some
19884 of the debugging data.  You therefore need to anticipate certain
19885 anomalous situations that may arise while debugging optimized code.  This
19886 section describes the most common cases.
19887
19888 @enumerate
19889 @item
19890 @i{The "hopping Program Counter":}  Repeated 'step' or 'next' commands show the PC
19891 bouncing back and forth in the code.  This may result from any of the following
19892 optimizations:
19893
19894 @itemize @bullet
19895 @item
19896 @i{Common subexpression elimination:} using a single instance of code for a
19897 quantity that the source computes several times.  As a result you
19898 may not be able to stop on what looks like a statement.
19899
19900 @item
19901 @i{Invariant code motion:} moving an expression that does not change within a
19902 loop, to the beginning of the loop.
19903
19904 @item
19905 @i{Instruction scheduling:} moving instructions so as to
19906 overlap loads and stores (typically) with other code, or in
19907 general to move computations of values closer to their uses. Often
19908 this causes you to pass an assignment statement without the assignment
19909 happening and then later bounce back to the statement when the
19910 value is actually needed.  Placing a breakpoint on a line of code
19911 and then stepping over it may, therefore, not always cause all the
19912 expected side-effects.
19913 @end itemize
19914
19915 @item
19916 @i{The "big leap":} More commonly known as @i{cross-jumping}, in which two
19917 identical pieces of code are merged and the program counter suddenly
19918 jumps to a statement that is not supposed to be executed, simply because
19919 it (and the code following) translates to the same thing as the code
19920 that @emph{was} supposed to be executed.  This effect is typically seen in
19921 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
19922 a @code{break} in a C @code{switch} statement.
19923
19924 @item
19925 @i{The "roving variable":} The symptom is an unexpected value in a variable.
19926 There are various reasons for this effect:
19927
19928 @itemize @bullet
19929 @item
19930 In a subprogram prologue, a parameter may not yet have been moved to its
19931 "home".
19932
19933 @item
19934 A variable may be dead, and its register re-used.  This is
19935 probably the most common cause.
19936
19937 @item
19938 As mentioned above, the assignment of a value to a variable may
19939 have been moved.
19940
19941 @item
19942 A variable may be eliminated entirely by value propagation or
19943 other means.  In this case, GCC may incorrectly generate debugging
19944 information for the variable
19945 @end itemize
19946
19947 @noindent
19948 In general, when an unexpected value appears for a local variable or parameter
19949 you should first ascertain if that value was actually computed by
19950 your program, as opposed to being incorrectly reported by the debugger.
19951 Record fields or
19952 array elements in an object designated by an access value
19953 are generally less of a problem, once you have ascertained that the access value
19954 is sensible.
19955 Typically, this means checking variables in the preceding code and in the
19956 calling subprogram to verify that the value observed is explainable from other
19957 values (one must apply the procedure recursively to those
19958 other values); or re-running the code and stopping a little earlier
19959 (perhaps before the call) and stepping to better see how the variable obtained
19960 the value in question; or continuing to step @emph{from} the point of the
19961 strange value to see if code motion had simply moved the variable's
19962 assignments later.
19963 @end enumerate
19964
19965 @node Inlining of Subprograms
19966 @section Inlining of Subprograms
19967
19968 @noindent
19969 A call to a subprogram in the current unit is inlined if all the
19970 following conditions are met:
19971
19972 @itemize @bullet
19973 @item
19974 The optimization level is at least @code{-O1}.
19975
19976 @item
19977 The called subprogram is suitable for inlining: It must be small enough
19978 and not contain nested subprograms or anything else that @code{gcc}
19979 cannot support in inlined subprograms.
19980
19981 @item
19982 The call occurs after the definition of the body of the subprogram.
19983
19984 @item
19985 @cindex pragma Inline
19986 @findex Inline
19987 Either @code{pragma Inline} applies to the subprogram or it is
19988 small and automatic inlining (optimization level @code{-O3}) is
19989 specified.
19990 @end itemize
19991
19992 @noindent
19993 Calls to subprograms in @code{with}'ed units are normally not inlined.
19994 To achieve this level of inlining, the following conditions must all be
19995 true:
19996
19997 @itemize @bullet
19998 @item
19999 The optimization level is at least @code{-O1}.
20000
20001 @item
20002 The called subprogram is suitable for inlining: It must be small enough
20003 and not contain nested subprograms or anything else @code{gcc} cannot
20004 support in inlined subprograms.
20005
20006 @item
20007 The call appears in a body (not in a package spec).
20008
20009 @item
20010 There is a @code{pragma Inline} for the subprogram.
20011
20012 @item
20013 @cindex @option{-gnatn} (@code{gcc})
20014 The @code{-gnatn} switch
20015 is used in the @code{gcc} command line
20016 @end itemize
20017
20018 Note that specifying the @option{-gnatn} switch causes additional
20019 compilation dependencies. Consider the following:
20020
20021 @smallexample
20022 @group
20023 @cartouche
20024 @b{package} R @b{is}
20025    @b{procedure} Q;
20026    @b{pragma} Inline (Q);
20027 @b{end} R;
20028 @b{package body} R @b{is}
20029    ...
20030 @b{end} R;
20031
20032 @b{with} R;
20033 @b{procedure} Main @b{is}
20034 @b{begin}
20035    ...
20036    R.Q;
20037 @b{end} Main;
20038 @end cartouche
20039 @end group
20040 @end smallexample
20041
20042 @noindent
20043 With the default behavior (no @option{-gnatn} switch specified), the
20044 compilation of the @code{Main} procedure depends only on its own source,
20045 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
20046 means that editing the body of @code{R} does not require recompiling
20047 @code{Main}.
20048
20049 On the other hand, the call @code{R.Q} is not inlined under these
20050 circumstances. If the @option{-gnatn} switch is present when @code{Main}
20051 is compiled, the call will be inlined if the body of @code{Q} is small
20052 enough, but now @code{Main} depends on the body of @code{R} in
20053 @file{r.adb} as well as on the spec. This means that if this body is edited,
20054 the main program must be recompiled. Note that this extra dependency
20055 occurs whether or not the call is in fact inlined by @code{gcc}.
20056
20057 The use of front end inlining with @option{-gnatN} generates similar
20058 additional dependencies.
20059
20060 @cindex @code{-fno-inline} (@code{gcc})
20061 Note: The @code{-fno-inline} switch
20062 can be used to prevent
20063 all inlining. This switch overrides all other conditions and ensures
20064 that no inlining occurs. The extra dependences resulting from
20065 @option{-gnatn} will still be active, even if
20066 this switch is used to suppress the resulting inlining actions.
20067
20068 Note regarding the use of @code{-O3}: There is no difference in inlining
20069 behavior between @code{-O2} and @code{-O3} for subprograms with an explicit
20070 pragma @code{Inline} assuming the use of @option{-gnatn}
20071 or @option{-gnatN} (the switches that activate inlining). If you have used
20072 pragma @code{Inline} in appropriate cases, then it is usually much better
20073 to use @code{-O2} and @option{-gnatn} and avoid the use of @code{-O3} which
20074 in this case only has the effect of inlining subprograms you did not
20075 think should be inlined. We often find that the use of @code{-O3} slows
20076 down code by performing excessive inlining, leading to increased instruction
20077 cache pressure from the increased code size. So the bottom line here is
20078 that you should not automatically assume that @code{-O3} is better than
20079 @code{-O2}, and indeed you should use @code{-O3} only if tests show that
20080 it actually improves performance.
20081
20082
20083 @include fdl.texi
20084 @c GNU Free Documentation License
20085
20086 @node Index,,GNU Free Documentation License, Top
20087 @unnumbered Index
20088
20089 @printindex cp
20090
20091 @contents
20092
20093 @bye