[Ada] Fix unbalanced paren in documentation marker for GNAT Studio
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blobcf363c6d868f095612519e83369104f8e5c923c5
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename gnat_ugn.info
4 @documentencoding UTF-8
5 @ifinfo
6 @*Generated by Sphinx 4.3.1.@*
7 @end ifinfo
8 @settitle GNAT User's Guide for Native Platforms
9 @defindex ge
10 @paragraphindent 0
11 @exampleindent 4
12 @finalout
13 @dircategory GNU Ada Tools 
14 @direntry
15 * gnat_ugn: (gnat_ugn.info). gnat_ugn
16 @end direntry
18 @definfoenclose strong,`,'
19 @definfoenclose emph,`,'
20 @c %**end of header
22 @copying
23 @quotation
24 GNAT User's Guide for Native Platforms , Apr 22, 2022
26 AdaCore
28 Copyright @copyright{} 2008-2022, Free Software Foundation
29 @end quotation
31 @end copying
33 @titlepage
34 @title GNAT User's Guide for Native Platforms
35 @insertcopying
36 @end titlepage
37 @contents
39 @c %** start of user preamble
41 @c %** end of user preamble
43 @ifnottex
44 @node Top
45 @top GNAT User's Guide for Native Platforms
46 @insertcopying
47 @end ifnottex
49 @c %**start of body
50 @anchor{gnat_ugn doc}@anchor{0}
51 @emph{GNAT, The GNU Ada Development Environment}
54 @include gcc-common.texi
55 GCC version @value{version-GCC}@*
56 AdaCore
58 Permission is granted to copy, distribute and/or modify this document
59 under the terms of the GNU Free Documentation License, Version 1.3 or
60 any later version published by the Free Software Foundation; with no
61 Invariant Sections, with the Front-Cover Texts being
62 “GNAT User’s Guide for Native Platforms”,
63 and with no Back-Cover Texts.  A copy of the license is
64 included in the section entitled @ref{1,,GNU Free Documentation License}.
66 @menu
67 * About This Guide:: 
68 * Getting Started with GNAT:: 
69 * The GNAT Compilation Model:: 
70 * Building Executable Programs with GNAT:: 
71 * GNAT Utility Programs:: 
72 * GNAT and Program Execution:: 
73 * Platform-Specific Information:: 
74 * Example of Binder Output File:: 
75 * Elaboration Order Handling in GNAT:: 
76 * Inline Assembler:: 
77 * GNU Free Documentation License:: 
78 * Index:: 
80 @detailmenu
81  --- The Detailed Node Listing ---
83 About This Guide
85 * What This Guide Contains:: 
86 * What You Should Know before Reading This Guide:: 
87 * Related Information:: 
88 * Conventions:: 
90 Getting Started with GNAT
92 * System Requirements:: 
93 * Running GNAT:: 
94 * Running a Simple Ada Program:: 
95 * Running a Program with Multiple Units:: 
97 The GNAT Compilation Model
99 * Source Representation:: 
100 * Foreign Language Representation:: 
101 * File Naming Topics and Utilities:: 
102 * Configuration Pragmas:: 
103 * Generating Object Files:: 
104 * Source Dependencies:: 
105 * The Ada Library Information Files:: 
106 * Binding an Ada Program:: 
107 * GNAT and Libraries:: 
108 * Conditional Compilation:: 
109 * Mixed Language Programming:: 
110 * GNAT and Other Compilation Models:: 
111 * Using GNAT Files with External Tools:: 
113 Foreign Language Representation
115 * Latin-1:: 
116 * Other 8-Bit Codes:: 
117 * Wide_Character Encodings:: 
118 * Wide_Wide_Character Encodings:: 
120 File Naming Topics and Utilities
122 * File Naming Rules:: 
123 * Using Other File Names:: 
124 * Alternative File Naming Schemes:: 
125 * Handling Arbitrary File Naming Conventions with gnatname:: 
126 * File Name Krunching with gnatkr:: 
127 * Renaming Files with gnatchop:: 
129 Handling Arbitrary File Naming Conventions with gnatname
131 * Arbitrary File Naming Conventions:: 
132 * Running gnatname:: 
133 * Switches for gnatname:: 
134 * Examples of gnatname Usage:: 
136 File Name Krunching with gnatkr
138 * About gnatkr:: 
139 * Using gnatkr:: 
140 * Krunching Method:: 
141 * Examples of gnatkr Usage:: 
143 Renaming Files with gnatchop
145 * Handling Files with Multiple Units:: 
146 * Operating gnatchop in Compilation Mode:: 
147 * Command Line for gnatchop:: 
148 * Switches for gnatchop:: 
149 * Examples of gnatchop Usage:: 
151 Configuration Pragmas
153 * Handling of Configuration Pragmas:: 
154 * The Configuration Pragmas Files:: 
156 GNAT and Libraries
158 * Introduction to Libraries in GNAT:: 
159 * General Ada Libraries:: 
160 * Stand-alone Ada Libraries:: 
161 * Rebuilding the GNAT Run-Time Library:: 
163 General Ada Libraries
165 * Building a library:: 
166 * Installing a library:: 
167 * Using a library:: 
169 Stand-alone Ada Libraries
171 * Introduction to Stand-alone Libraries:: 
172 * Building a Stand-alone Library:: 
173 * Creating a Stand-alone Library to be used in a non-Ada context:: 
174 * Restrictions in Stand-alone Libraries:: 
176 Conditional Compilation
178 * Modeling Conditional Compilation in Ada:: 
179 * Preprocessing with gnatprep:: 
180 * Integrated Preprocessing:: 
182 Modeling Conditional Compilation in Ada
184 * Use of Boolean Constants:: 
185 * Debugging - A Special Case:: 
186 * Conditionalizing Declarations:: 
187 * Use of Alternative Implementations:: 
188 * Preprocessing:: 
190 Preprocessing with gnatprep
192 * Preprocessing Symbols:: 
193 * Using gnatprep:: 
194 * Switches for gnatprep:: 
195 * Form of Definitions File:: 
196 * Form of Input Text for gnatprep:: 
198 Mixed Language Programming
200 * Interfacing to C:: 
201 * Calling Conventions:: 
202 * Building Mixed Ada and C++ Programs:: 
203 * Generating Ada Bindings for C and C++ headers:: 
204 * Generating C Headers for Ada Specifications:: 
206 Building Mixed Ada and C++ Programs
208 * Interfacing to C++:: 
209 * Linking a Mixed C++ & Ada Program:: 
210 * A Simple Example:: 
211 * Interfacing with C++ constructors:: 
212 * Interfacing with C++ at the Class Level:: 
214 Generating Ada Bindings for C and C++ headers
216 * Running the Binding Generator:: 
217 * Generating Bindings for C++ Headers:: 
218 * Switches:: 
220 Generating C Headers for Ada Specifications
222 * Running the C Header Generator:: 
224 GNAT and Other Compilation Models
226 * Comparison between GNAT and C/C++ Compilation Models:: 
227 * Comparison between GNAT and Conventional Ada Library Models:: 
229 Using GNAT Files with External Tools
231 * Using Other Utility Programs with GNAT:: 
232 * The External Symbol Naming Scheme of GNAT:: 
234 Building Executable Programs with GNAT
236 * Building with gnatmake:: 
237 * Compiling with gcc:: 
238 * Compiler Switches:: 
239 * Linker Switches:: 
240 * Binding with gnatbind:: 
241 * Linking with gnatlink:: 
242 * Using the GNU make Utility:: 
244 Building with gnatmake
246 * Running gnatmake:: 
247 * Switches for gnatmake:: 
248 * Mode Switches for gnatmake:: 
249 * Notes on the Command Line:: 
250 * How gnatmake Works:: 
251 * Examples of gnatmake Usage:: 
253 Compiling with gcc
255 * Compiling Programs:: 
256 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
257 * Order of Compilation Issues:: 
258 * Examples:: 
260 Compiler Switches
262 * Alphabetical List of All Switches:: 
263 * Output and Error Message Control:: 
264 * Warning Message Control:: 
265 * Debugging and Assertion Control:: 
266 * Validity Checking:: 
267 * Style Checking:: 
268 * Run-Time Checks:: 
269 * Using gcc for Syntax Checking:: 
270 * Using gcc for Semantic Checking:: 
271 * Compiling Different Versions of Ada:: 
272 * Character Set Control:: 
273 * File Naming Control:: 
274 * Subprogram Inlining Control:: 
275 * Auxiliary Output Control:: 
276 * Debugging Control:: 
277 * Exception Handling Control:: 
278 * Units to Sources Mapping Files:: 
279 * Code Generation Control:: 
281 Binding with gnatbind
283 * Running gnatbind:: 
284 * Switches for gnatbind:: 
285 * Command-Line Access:: 
286 * Search Paths for gnatbind:: 
287 * Examples of gnatbind Usage:: 
289 Switches for gnatbind
291 * Consistency-Checking Modes:: 
292 * Binder Error Message Control:: 
293 * Elaboration Control:: 
294 * Output Control:: 
295 * Dynamic Allocation Control:: 
296 * Binding with Non-Ada Main Programs:: 
297 * Binding Programs with No Main Subprogram:: 
299 Linking with gnatlink
301 * Running gnatlink:: 
302 * Switches for gnatlink:: 
304 Using the GNU make Utility
306 * Using gnatmake in a Makefile:: 
307 * Automatically Creating a List of Directories:: 
308 * Generating the Command Line Switches:: 
309 * Overcoming Command Line Length Limits:: 
311 GNAT Utility Programs
313 * The File Cleanup Utility gnatclean:: 
314 * The GNAT Library Browser gnatls:: 
316 The File Cleanup Utility gnatclean
318 * Running gnatclean:: 
319 * Switches for gnatclean:: 
321 The GNAT Library Browser gnatls
323 * Running gnatls:: 
324 * Switches for gnatls:: 
325 * Example of gnatls Usage:: 
327 GNAT and Program Execution
329 * Running and Debugging Ada Programs:: 
330 * Profiling:: 
331 * Improving Performance:: 
332 * Overflow Check Handling in GNAT:: 
333 * Performing Dimensionality Analysis in GNAT:: 
334 * Stack Related Facilities:: 
335 * Memory Management Issues:: 
337 Running and Debugging Ada Programs
339 * The GNAT Debugger GDB:: 
340 * Running GDB:: 
341 * Introduction to GDB Commands:: 
342 * Using Ada Expressions:: 
343 * Calling User-Defined Subprograms:: 
344 * Using the next Command in a Function:: 
345 * Stopping When Ada Exceptions Are Raised:: 
346 * Ada Tasks:: 
347 * Debugging Generic Units:: 
348 * Remote Debugging with gdbserver:: 
349 * GNAT Abnormal Termination or Failure to Terminate:: 
350 * Naming Conventions for GNAT Source Files:: 
351 * Getting Internal Debugging Information:: 
352 * Stack Traceback:: 
353 * Pretty-Printers for the GNAT runtime:: 
355 Stack Traceback
357 * Non-Symbolic Traceback:: 
358 * Symbolic Traceback:: 
360 Profiling
362 * Profiling an Ada Program with gprof:: 
364 Profiling an Ada Program with gprof
366 * Compilation for profiling:: 
367 * Program execution:: 
368 * Running gprof:: 
369 * Interpretation of profiling results:: 
371 Improving Performance
373 * Performance Considerations:: 
374 * Text_IO Suggestions:: 
375 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
377 Performance Considerations
379 * Controlling Run-Time Checks:: 
380 * Use of Restrictions:: 
381 * Optimization Levels:: 
382 * Debugging Optimized Code:: 
383 * Inlining of Subprograms:: 
384 * Floating Point Operations:: 
385 * Vectorization of loops:: 
386 * Other Optimization Switches:: 
387 * Optimization and Strict Aliasing:: 
388 * Aliased Variables and Optimization:: 
389 * Atomic Variables and Optimization:: 
390 * Passive Task Optimization:: 
392 Reducing Size of Executables with Unused Subprogram/Data Elimination
394 * About unused subprogram/data elimination:: 
395 * Compilation options:: 
396 * Example of unused subprogram/data elimination:: 
398 Overflow Check Handling in GNAT
400 * Background:: 
401 * Management of Overflows in GNAT:: 
402 * Specifying the Desired Mode:: 
403 * Default Settings:: 
404 * Implementation Notes:: 
406 Stack Related Facilities
408 * Stack Overflow Checking:: 
409 * Static Stack Usage Analysis:: 
410 * Dynamic Stack Usage Analysis:: 
412 Memory Management Issues
414 * Some Useful Memory Pools:: 
415 * The GNAT Debug Pool Facility:: 
417 Platform-Specific Information
419 * Run-Time Libraries:: 
420 * Specifying a Run-Time Library:: 
421 * GNU/Linux Topics:: 
422 * Microsoft Windows Topics:: 
423 * Mac OS Topics:: 
425 Run-Time Libraries
427 * Summary of Run-Time Configurations:: 
429 Specifying a Run-Time Library
431 * Choosing the Scheduling Policy:: 
433 GNU/Linux Topics
435 * Required Packages on GNU/Linux:: 
436 * A GNU/Linux Debug Quirk:: 
438 Microsoft Windows Topics
440 * Using GNAT on Windows:: 
441 * Using a network installation of GNAT:: 
442 * CONSOLE and WINDOWS subsystems:: 
443 * Temporary Files:: 
444 * Disabling Command Line Argument Expansion:: 
445 * Windows Socket Timeouts:: 
446 * Mixed-Language Programming on Windows:: 
447 * Windows Specific Add-Ons:: 
449 Mixed-Language Programming on Windows
451 * Windows Calling Conventions:: 
452 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
453 * Using DLLs with GNAT:: 
454 * Building DLLs with GNAT Project files:: 
455 * Building DLLs with GNAT:: 
456 * Building DLLs with gnatdll:: 
457 * Ada DLLs and Finalization:: 
458 * Creating a Spec for Ada DLLs:: 
459 * GNAT and Windows Resources:: 
460 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
461 * Debugging a DLL:: 
462 * Setting Stack Size from gnatlink:: 
463 * Setting Heap Size from gnatlink:: 
465 Windows Calling Conventions
467 * C Calling Convention:: 
468 * Stdcall Calling Convention:: 
469 * Win32 Calling Convention:: 
470 * DLL Calling Convention:: 
472 Using DLLs with GNAT
474 * Creating an Ada Spec for the DLL Services:: 
475 * Creating an Import Library:: 
477 Building DLLs with gnatdll
479 * Limitations When Using Ada DLLs from Ada:: 
480 * Exporting Ada Entities:: 
481 * Ada DLLs and Elaboration:: 
483 Creating a Spec for Ada DLLs
485 * Creating the Definition File:: 
486 * Using gnatdll:: 
488 GNAT and Windows Resources
490 * Building Resources:: 
491 * Compiling Resources:: 
492 * Using Resources:: 
494 Debugging a DLL
496 * Program and DLL Both Built with GCC/GNAT:: 
497 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
499 Windows Specific Add-Ons
501 * Win32Ada:: 
502 * wPOSIX:: 
504 Mac OS Topics
506 * Codesigning the Debugger:: 
508 Elaboration Order Handling in GNAT
510 * Elaboration Code:: 
511 * Elaboration Order:: 
512 * Checking the Elaboration Order:: 
513 * Controlling the Elaboration Order in Ada:: 
514 * Controlling the Elaboration Order in GNAT:: 
515 * Mixing Elaboration Models:: 
516 * ABE Diagnostics:: 
517 * SPARK Diagnostics:: 
518 * Elaboration Circularities:: 
519 * Resolving Elaboration Circularities:: 
520 * Elaboration-related Compiler Switches:: 
521 * Summary of Procedures for Elaboration Control:: 
522 * Inspecting the Chosen Elaboration Order:: 
524 Inline Assembler
526 * Basic Assembler Syntax:: 
527 * A Simple Example of Inline Assembler:: 
528 * Output Variables in Inline Assembler:: 
529 * Input Variables in Inline Assembler:: 
530 * Inlining Inline Assembler Code:: 
531 * Other Asm Functionality:: 
533 Other Asm Functionality
535 * The Clobber Parameter:: 
536 * The Volatile Parameter:: 
538 @end detailmenu
539 @end menu
541 @node About This Guide,Getting Started with GNAT,Top,Top
542 @anchor{gnat_ugn/about_this_guide doc}@anchor{2}@anchor{gnat_ugn/about_this_guide about-this-guide}@anchor{3}@anchor{gnat_ugn/about_this_guide gnat-user-s-guide-for-native-platforms}@anchor{4}@anchor{gnat_ugn/about_this_guide id1}@anchor{5}
543 @chapter About This Guide
547 This guide describes the use of GNAT,
548 a compiler and software development
549 toolset for the full Ada programming language.
550 It documents the features of the compiler and tools, and explains
551 how to use them to build Ada applications.
553 GNAT implements Ada 95, Ada 2005, Ada 2012, and Ada 202x, and it may also be
554 invoked in Ada 83 compatibility mode.
555 By default, GNAT assumes Ada 2012, but you can override with a
556 compiler switch (@ref{6,,Compiling Different Versions of Ada})
557 to explicitly specify the language version.
558 Throughout this manual, references to ‘Ada’ without a year suffix
559 apply to all Ada versions of the language, starting with Ada 95.
561 @menu
562 * What This Guide Contains:: 
563 * What You Should Know before Reading This Guide:: 
564 * Related Information:: 
565 * Conventions:: 
567 @end menu
569 @node What This Guide Contains,What You Should Know before Reading This Guide,,About This Guide
570 @anchor{gnat_ugn/about_this_guide what-this-guide-contains}@anchor{7}
571 @section What This Guide Contains
574 This guide contains the following chapters:
577 @itemize *
579 @item 
580 @ref{8,,Getting Started with GNAT} describes how to get started compiling
581 and running Ada programs with the GNAT Ada programming environment.
583 @item 
584 @ref{9,,The GNAT Compilation Model} describes the compilation model used
585 by GNAT.
587 @item 
588 @ref{a,,Building Executable Programs with GNAT} describes how to use the
589 main GNAT tools to build executable programs, and it also gives examples of
590 using the GNU make utility with GNAT.
592 @item 
593 @ref{b,,GNAT Utility Programs} explains the various utility programs that
594 are included in the GNAT environment
596 @item 
597 @ref{c,,GNAT and Program Execution} covers a number of topics related to
598 running, debugging, and tuning the performace of programs developed
599 with GNAT
600 @end itemize
602 Appendices cover several additional topics:
605 @itemize *
607 @item 
608 @ref{d,,Platform-Specific Information} describes the different run-time
609 library implementations and also presents information on how to use
610 GNAT on several specific platforms
612 @item 
613 @ref{e,,Example of Binder Output File} shows the source code for the binder
614 output file for a sample program.
616 @item 
617 @ref{f,,Elaboration Order Handling in GNAT} describes how GNAT helps
618 you deal with elaboration order issues.
620 @item 
621 @ref{10,,Inline Assembler} shows how to use the inline assembly facility
622 in an Ada program.
623 @end itemize
625 @node What You Should Know before Reading This Guide,Related Information,What This Guide Contains,About This Guide
626 @anchor{gnat_ugn/about_this_guide what-you-should-know-before-reading-this-guide}@anchor{11}
627 @section What You Should Know before Reading This Guide
630 @geindex Ada 95 Language Reference Manual
632 @geindex Ada 2005 Language Reference Manual
634 This guide assumes a basic familiarity with the Ada 95 language, as
635 described in the International Standard ANSI/ISO/IEC-8652:1995, January
636 1995.
637 Reference manuals for Ada 95, Ada 2005, and Ada 2012 are included in
638 the GNAT documentation package.
640 @node Related Information,Conventions,What You Should Know before Reading This Guide,About This Guide
641 @anchor{gnat_ugn/about_this_guide related-information}@anchor{12}
642 @section Related Information
645 For further information about Ada and related tools, please refer to the
646 following documents:
649 @itemize *
651 @item 
652 @cite{Ada 95 Reference Manual}, @cite{Ada 2005 Reference Manual}, and
653 @cite{Ada 2012 Reference Manual}, which contain reference
654 material for the several revisions of the Ada language standard.
656 @item 
657 @cite{GNAT Reference_Manual}, which contains all reference material for the GNAT
658 implementation of Ada.
660 @item 
661 @cite{Using GNAT Studio}, which describes the GNAT Studio
662 Integrated Development Environment.
664 @item 
665 @cite{GNAT Studio Tutorial}, which introduces the
666 main GNAT Studio features through examples.
668 @item 
669 @cite{Debugging with GDB},
670 for all details on the use of the GNU source-level debugger.
672 @item 
673 @cite{GNU Emacs Manual},
674 for full information on the extensible editor and programming
675 environment Emacs.
676 @end itemize
678 @node Conventions,,Related Information,About This Guide
679 @anchor{gnat_ugn/about_this_guide conventions}@anchor{13}
680 @section Conventions
683 @geindex Conventions
684 @geindex typographical
686 @geindex Typographical conventions
688 Following are examples of the typographical and graphic conventions used
689 in this guide:
692 @itemize *
694 @item 
695 @code{Functions}, @code{utility program names}, @code{standard names},
696 and @code{classes}.
698 @item 
699 @code{Option flags}
701 @item 
702 @code{File names}
704 @item 
705 @code{Variables}
707 @item 
708 @emph{Emphasis}
710 @item 
711 [optional information or parameters]
713 @item 
714 Examples are described by text
716 @example
717 and then shown this way.
718 @end example
720 @item 
721 Commands that are entered by the user are shown as preceded by a prompt string
722 comprising the @code{$} character followed by a space.
724 @item 
725 Full file names are shown with the ‘/’ character
726 as the directory separator; e.g., @code{parent-dir/subdir/myfile.adb}.
727 If you are using GNAT on a Windows platform, please note that
728 the ‘\’ character should be used instead.
729 @end itemize
731 @node Getting Started with GNAT,The GNAT Compilation Model,About This Guide,Top
732 @anchor{gnat_ugn/getting_started_with_gnat doc}@anchor{14}@anchor{gnat_ugn/getting_started_with_gnat getting-started-with-gnat}@anchor{8}@anchor{gnat_ugn/getting_started_with_gnat id1}@anchor{15}
733 @chapter Getting Started with GNAT
736 This chapter describes how to use GNAT’s command line interface to build
737 executable Ada programs.
738 On most platforms a visually oriented Integrated Development Environment
739 is also available: GNAT Studio.
740 GNAT Studio offers a graphical “look and feel”, support for development in
741 other programming languages, comprehensive browsing features, and
742 many other capabilities.
743 For information on GNAT Studio please refer to the
744 @cite{GNAT Studio documentation}.
746 @menu
747 * System Requirements:: 
748 * Running GNAT:: 
749 * Running a Simple Ada Program:: 
750 * Running a Program with Multiple Units:: 
752 @end menu
754 @node System Requirements,Running GNAT,,Getting Started with GNAT
755 @anchor{gnat_ugn/getting_started_with_gnat id2}@anchor{16}@anchor{gnat_ugn/getting_started_with_gnat system-requirements}@anchor{17}
756 @section System Requirements
759 Even though any machine can run the GNAT toolset and GNAT Studio IDE, in order
760 to get the best experience, we recommend using a machine with as many cores
761 as possible since all individual compilations can run in parallel.
762 A comfortable setup for a compiler server is a machine with 24 physical cores
763 or more, with at least 48 GB of memory (2 GB per core).
765 For a desktop machine, a minimum of 4 cores is recommended (8 preferred),
766 with at least 2GB per core (so 8 to 16GB).
768 In addition, for running and navigating sources in GNAT Studio smoothly, we
769 recommend at least 1.5 GB plus 3 GB of RAM per 1 million source line of code.
770 In other words, we recommend at least 3 GB for for 500K lines of code and
771 7.5 GB for 2 million lines of code.
773 Note that using local and fast drives will also make a difference in terms of
774 build and link time. Network drives such as NFS, SMB, or worse, configuration
775 management filesystems (such as ClearCase dynamic views) should be avoided as
776 much as possible and will produce very degraded performance (typically 2 to 3
777 times slower than on local fast drives). If such slow drives cannot be avoided
778 for accessing the source code, then you should at least configure your project
779 file so that the result of the compilation is stored on a drive local to the
780 machine performing the run. This can be achieved by setting the @code{Object_Dir}
781 project file attribute.
783 @node Running GNAT,Running a Simple Ada Program,System Requirements,Getting Started with GNAT
784 @anchor{gnat_ugn/getting_started_with_gnat id3}@anchor{18}@anchor{gnat_ugn/getting_started_with_gnat running-gnat}@anchor{19}
785 @section Running GNAT
788 Three steps are needed to create an executable file from an Ada source
789 file:
792 @itemize *
794 @item 
795 The source file(s) must be compiled.
797 @item 
798 The file(s) must be bound using the GNAT binder.
800 @item 
801 All appropriate object files must be linked to produce an executable.
802 @end itemize
804 All three steps are most commonly handled by using the @code{gnatmake}
805 utility program that, given the name of the main program, automatically
806 performs the necessary compilation, binding and linking steps.
808 @node Running a Simple Ada Program,Running a Program with Multiple Units,Running GNAT,Getting Started with GNAT
809 @anchor{gnat_ugn/getting_started_with_gnat id4}@anchor{1a}@anchor{gnat_ugn/getting_started_with_gnat running-a-simple-ada-program}@anchor{1b}
810 @section Running a Simple Ada Program
813 Any text editor may be used to prepare an Ada program.
814 (If Emacs is used, the optional Ada mode may be helpful in laying out the
815 program.)
816 The program text is a normal text file. We will assume in our initial
817 example that you have used your editor to prepare the following
818 standard format text file:
820 @example
821 with Ada.Text_IO; use Ada.Text_IO;
822 procedure Hello is
823 begin
824    Put_Line ("Hello WORLD!");
825 end Hello;
826 @end example
828 This file should be named @code{hello.adb}.
829 With the normal default file naming conventions, GNAT requires
830 that each file
831 contain a single compilation unit whose file name is the
832 unit name,
833 with periods replaced by hyphens; the
834 extension is @code{ads} for a
835 spec and @code{adb} for a body.
836 You can override this default file naming convention by use of the
837 special pragma @code{Source_File_Name} (for further information please
838 see @ref{1c,,Using Other File Names}).
839 Alternatively, if you want to rename your files according to this default
840 convention, which is probably more convenient if you will be using GNAT
841 for all your compilations, then the @code{gnatchop} utility
842 can be used to generate correctly-named source files
843 (see @ref{1d,,Renaming Files with gnatchop}).
845 You can compile the program using the following command (@code{$} is used
846 as the command prompt in the examples in this document):
848 @example
849 $ gcc -c hello.adb
850 @end example
852 @code{gcc} is the command used to run the compiler. This compiler is
853 capable of compiling programs in several languages, including Ada and
854 C. It assumes that you have given it an Ada program if the file extension is
855 either @code{.ads} or @code{.adb}, and it will then call
856 the GNAT compiler to compile the specified file.
858 The @code{-c} switch is required. It tells @code{gcc} to only do a
859 compilation. (For C programs, @code{gcc} can also do linking, but this
860 capability is not used directly for Ada programs, so the @code{-c}
861 switch must always be present.)
863 This compile command generates a file
864 @code{hello.o}, which is the object
865 file corresponding to your Ada program. It also generates
866 an ‘Ada Library Information’ file @code{hello.ali},
867 which contains additional information used to check
868 that an Ada program is consistent.
870 To build an executable file, use either @code{gnatmake} or gprbuild with
871 the name of the main file: these tools are builders that will take care of
872 all the necessary build steps in the correct order.
873 In particular, these builders automatically recompile any sources that have
874 been modified since they were last compiled, or sources that depend
875 on such modified sources, so that ‘version skew’ is avoided.
877 @geindex Version skew (avoided by `@w{`}gnatmake`@w{`})
879 @example
880 $ gnatmake hello.adb
881 @end example
883 The result is an executable program called @code{hello}, which can be
884 run by entering:
886 @example
887 $ hello
888 @end example
890 assuming that the current directory is on the search path
891 for executable programs.
893 and, if all has gone well, you will see:
895 @example
896 Hello WORLD!
897 @end example
899 appear in response to this command.
901 @node Running a Program with Multiple Units,,Running a Simple Ada Program,Getting Started with GNAT
902 @anchor{gnat_ugn/getting_started_with_gnat id5}@anchor{1e}@anchor{gnat_ugn/getting_started_with_gnat running-a-program-with-multiple-units}@anchor{1f}
903 @section Running a Program with Multiple Units
906 Consider a slightly more complicated example that has three files: a
907 main program, and the spec and body of a package:
909 @example
910 package Greetings is
911    procedure Hello;
912    procedure Goodbye;
913 end Greetings;
915 with Ada.Text_IO; use Ada.Text_IO;
916 package body Greetings is
917    procedure Hello is
918    begin
919       Put_Line ("Hello WORLD!");
920    end Hello;
922    procedure Goodbye is
923    begin
924       Put_Line ("Goodbye WORLD!");
925    end Goodbye;
926 end Greetings;
928 with Greetings;
929 procedure Gmain is
930 begin
931    Greetings.Hello;
932    Greetings.Goodbye;
933 end Gmain;
934 @end example
936 Following the one-unit-per-file rule, place this program in the
937 following three separate files:
940 @table @asis
942 @item @emph{greetings.ads}
944 spec of package @code{Greetings}
946 @item @emph{greetings.adb}
948 body of package @code{Greetings}
950 @item @emph{gmain.adb}
952 body of main program
953 @end table
955 Note that there is no required order of compilation when using GNAT.
956 In particular it is perfectly fine to compile the main program first.
957 Also, it is not necessary to compile package specs in the case where
958 there is an accompanying body; you only need to compile the body. If you want
959 to submit these files to the compiler for semantic checking and not code
960 generation, then use the @code{-gnatc} switch:
962 @example
963 $ gcc -c greetings.ads -gnatc
964 @end example
966 Although the compilation can be done in separate steps, in practice it is
967 almost always more convenient to use the @code{gnatmake} or @code{gprbuild} tools:
969 @example
970 $ gnatmake gmain.adb
971 @end example
973 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
975 @node The GNAT Compilation Model,Building Executable Programs with GNAT,Getting Started with GNAT,Top
976 @anchor{gnat_ugn/the_gnat_compilation_model doc}@anchor{20}@anchor{gnat_ugn/the_gnat_compilation_model id1}@anchor{21}@anchor{gnat_ugn/the_gnat_compilation_model the-gnat-compilation-model}@anchor{9}
977 @chapter The GNAT Compilation Model
980 @geindex GNAT compilation model
982 @geindex Compilation model
984 This chapter describes the compilation model used by GNAT. Although
985 similar to that used by other languages such as C and C++, this model
986 is substantially different from the traditional Ada compilation models,
987 which are based on a centralized program library. The chapter covers
988 the following material:
991 @itemize *
993 @item 
994 Topics related to source file makeup and naming
997 @itemize *
999 @item 
1000 @ref{22,,Source Representation}
1002 @item 
1003 @ref{23,,Foreign Language Representation}
1005 @item 
1006 @ref{24,,File Naming Topics and Utilities}
1007 @end itemize
1009 @item 
1010 @ref{25,,Configuration Pragmas}
1012 @item 
1013 @ref{26,,Generating Object Files}
1015 @item 
1016 @ref{27,,Source Dependencies}
1018 @item 
1019 @ref{28,,The Ada Library Information Files}
1021 @item 
1022 @ref{29,,Binding an Ada Program}
1024 @item 
1025 @ref{2a,,GNAT and Libraries}
1027 @item 
1028 @ref{2b,,Conditional Compilation}
1030 @item 
1031 @ref{2c,,Mixed Language Programming}
1033 @item 
1034 @ref{2d,,GNAT and Other Compilation Models}
1036 @item 
1037 @ref{2e,,Using GNAT Files with External Tools}
1038 @end itemize
1040 @menu
1041 * Source Representation:: 
1042 * Foreign Language Representation:: 
1043 * File Naming Topics and Utilities:: 
1044 * Configuration Pragmas:: 
1045 * Generating Object Files:: 
1046 * Source Dependencies:: 
1047 * The Ada Library Information Files:: 
1048 * Binding an Ada Program:: 
1049 * GNAT and Libraries:: 
1050 * Conditional Compilation:: 
1051 * Mixed Language Programming:: 
1052 * GNAT and Other Compilation Models:: 
1053 * Using GNAT Files with External Tools:: 
1055 @end menu
1057 @node Source Representation,Foreign Language Representation,,The GNAT Compilation Model
1058 @anchor{gnat_ugn/the_gnat_compilation_model id2}@anchor{2f}@anchor{gnat_ugn/the_gnat_compilation_model source-representation}@anchor{22}
1059 @section Source Representation
1062 @geindex Latin-1
1064 @geindex VT
1065 @geindex HT
1066 @geindex CR
1067 @geindex LF
1068 @geindex FF
1070 Ada source programs are represented in standard text files, using
1071 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1072 7-bit ASCII set, plus additional characters used for
1073 representing foreign languages (see @ref{23,,Foreign Language Representation}
1074 for support of non-USA character sets). The format effector characters
1075 are represented using their standard ASCII encodings, as follows:
1077 @quotation
1080 @multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxx} 
1081 @item
1083 Character
1085 @tab
1087 Effect
1089 @tab
1091 Code
1093 @item
1095 @code{VT}
1097 @tab
1099 Vertical tab
1101 @tab
1103 @code{16#0B#}
1105 @item
1107 @code{HT}
1109 @tab
1111 Horizontal tab
1113 @tab
1115 @code{16#09#}
1117 @item
1119 @code{CR}
1121 @tab
1123 Carriage return
1125 @tab
1127 @code{16#0D#}
1129 @item
1131 @code{LF}
1133 @tab
1135 Line feed
1137 @tab
1139 @code{16#0A#}
1141 @item
1143 @code{FF}
1145 @tab
1147 Form feed
1149 @tab
1151 @code{16#0C#}
1153 @end multitable
1155 @end quotation
1157 Source files are in standard text file format. In addition, GNAT will
1158 recognize a wide variety of stream formats, in which the end of
1159 physical lines is marked by any of the following sequences:
1160 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1161 in accommodating files that are imported from other operating systems.
1163 @geindex End of source file; Source file@comma{} end
1165 @geindex SUB (control character)
1167 The end of a source file is normally represented by the physical end of
1168 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1169 recognized as signalling the end of the source file. Again, this is
1170 provided for compatibility with other operating systems where this
1171 code is used to represent the end of file.
1173 @geindex spec (definition)
1174 @geindex compilation (definition)
1176 Each file contains a single Ada compilation unit, including any pragmas
1177 associated with the unit. For example, this means you must place a
1178 package declaration (a package @emph{spec}) and the corresponding body in
1179 separate files. An Ada @emph{compilation} (which is a sequence of
1180 compilation units) is represented using a sequence of files. Similarly,
1181 you will place each subunit or child unit in a separate file.
1183 @node Foreign Language Representation,File Naming Topics and Utilities,Source Representation,The GNAT Compilation Model
1184 @anchor{gnat_ugn/the_gnat_compilation_model foreign-language-representation}@anchor{23}@anchor{gnat_ugn/the_gnat_compilation_model id3}@anchor{30}
1185 @section Foreign Language Representation
1188 GNAT supports the standard character sets defined in Ada as well as
1189 several other non-standard character sets for use in localized versions
1190 of the compiler (@ref{31,,Character Set Control}).
1192 @menu
1193 * Latin-1:: 
1194 * Other 8-Bit Codes:: 
1195 * Wide_Character Encodings:: 
1196 * Wide_Wide_Character Encodings:: 
1198 @end menu
1200 @node Latin-1,Other 8-Bit Codes,,Foreign Language Representation
1201 @anchor{gnat_ugn/the_gnat_compilation_model id4}@anchor{32}@anchor{gnat_ugn/the_gnat_compilation_model latin-1}@anchor{33}
1202 @subsection Latin-1
1205 @geindex Latin-1
1207 The basic character set is Latin-1. This character set is defined by ISO
1208 standard 8859, part 1. The lower half (character codes @code{16#00#}
1209 … @code{16#7F#)} is identical to standard ASCII coding, but the upper
1210 half is used to represent additional characters. These include extended letters
1211 used by European languages, such as French accents, the vowels with umlauts
1212 used in German, and the extra letter A-ring used in Swedish.
1214 @geindex Ada.Characters.Latin_1
1216 For a complete list of Latin-1 codes and their encodings, see the source
1217 file of library unit @code{Ada.Characters.Latin_1} in file
1218 @code{a-chlat1.ads}.
1219 You may use any of these extended characters freely in character or
1220 string literals. In addition, the extended characters that represent
1221 letters can be used in identifiers.
1223 @node Other 8-Bit Codes,Wide_Character Encodings,Latin-1,Foreign Language Representation
1224 @anchor{gnat_ugn/the_gnat_compilation_model id5}@anchor{34}@anchor{gnat_ugn/the_gnat_compilation_model other-8-bit-codes}@anchor{35}
1225 @subsection Other 8-Bit Codes
1228 GNAT also supports several other 8-bit coding schemes:
1230 @geindex Latin-2
1232 @geindex ISO 8859-2
1235 @table @asis
1237 @item @emph{ISO 8859-2 (Latin-2)}
1239 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1240 equivalence.
1241 @end table
1243 @geindex Latin-3
1245 @geindex ISO 8859-3
1248 @table @asis
1250 @item @emph{ISO 8859-3 (Latin-3)}
1252 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1253 equivalence.
1254 @end table
1256 @geindex Latin-4
1258 @geindex ISO 8859-4
1261 @table @asis
1263 @item @emph{ISO 8859-4 (Latin-4)}
1265 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1266 equivalence.
1267 @end table
1269 @geindex ISO 8859-5
1271 @geindex Cyrillic
1274 @table @asis
1276 @item @emph{ISO 8859-5 (Cyrillic)}
1278 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1279 lowercase equivalence.
1280 @end table
1282 @geindex ISO 8859-15
1284 @geindex Latin-9
1287 @table @asis
1289 @item @emph{ISO 8859-15 (Latin-9)}
1291 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1292 lowercase equivalence
1293 @end table
1295 @geindex code page 437 (IBM PC)
1298 @table @asis
1300 @item @emph{IBM PC (code page 437)}
1302 This code page is the normal default for PCs in the U.S. It corresponds
1303 to the original IBM PC character set. This set has some, but not all, of
1304 the extended Latin-1 letters, but these letters do not have the same
1305 encoding as Latin-1. In this mode, these letters are allowed in
1306 identifiers with uppercase and lowercase equivalence.
1307 @end table
1309 @geindex code page 850 (IBM PC)
1312 @table @asis
1314 @item @emph{IBM PC (code page 850)}
1316 This code page is a modification of 437 extended to include all the
1317 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1318 mode, all these letters are allowed in identifiers with uppercase and
1319 lowercase equivalence.
1321 @item @emph{Full Upper 8-bit}
1323 Any character in the range 80-FF allowed in identifiers, and all are
1324 considered distinct. In other words, there are no uppercase and lowercase
1325 equivalences in this range. This is useful in conjunction with
1326 certain encoding schemes used for some foreign character sets (e.g.,
1327 the typical method of representing Chinese characters on the PC).
1329 @item @emph{No Upper-Half}
1331 No upper-half characters in the range 80-FF are allowed in identifiers.
1332 This gives Ada 83 compatibility for identifier names.
1333 @end table
1335 For precise data on the encodings permitted, and the uppercase and lowercase
1336 equivalences that are recognized, see the file @code{csets.adb} in
1337 the GNAT compiler sources. You will need to obtain a full source release
1338 of GNAT to obtain this file.
1340 @node Wide_Character Encodings,Wide_Wide_Character Encodings,Other 8-Bit Codes,Foreign Language Representation
1341 @anchor{gnat_ugn/the_gnat_compilation_model id6}@anchor{36}@anchor{gnat_ugn/the_gnat_compilation_model wide-character-encodings}@anchor{37}
1342 @subsection Wide_Character Encodings
1345 GNAT allows wide character codes to appear in character and string
1346 literals, and also optionally in identifiers, by means of the following
1347 possible encoding schemes:
1350 @table @asis
1352 @item @emph{Hex Coding}
1354 In this encoding, a wide character is represented by the following five
1355 character sequence:
1357 @example
1358 ESC a b c d
1359 @end example
1361 where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1362 characters (using uppercase letters) of the wide character code. For
1363 example, ESC A345 is used to represent the wide character with code
1364 @code{16#A345#}.
1365 This scheme is compatible with use of the full Wide_Character set.
1367 @item @emph{Upper-Half Coding}
1369 @geindex Upper-Half Coding
1371 The wide character with encoding @code{16#abcd#} where the upper bit is on
1372 (in other words, ‘a’ is in the range 8-F) is represented as two bytes,
1373 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1374 character, but is not required to be in the upper half. This method can
1375 be also used for shift-JIS or EUC, where the internal coding matches the
1376 external coding.
1378 @item @emph{Shift JIS Coding}
1380 @geindex Shift JIS Coding
1382 A wide character is represented by a two-character sequence,
1383 @code{16#ab#} and
1384 @code{16#cd#}, with the restrictions described for upper-half encoding as
1385 described above. The internal character code is the corresponding JIS
1386 character according to the standard algorithm for Shift-JIS
1387 conversion. Only characters defined in the JIS code set table can be
1388 used with this encoding method.
1390 @item @emph{EUC Coding}
1392 @geindex EUC Coding
1394 A wide character is represented by a two-character sequence
1395 @code{16#ab#} and
1396 @code{16#cd#}, with both characters being in the upper half. The internal
1397 character code is the corresponding JIS character according to the EUC
1398 encoding algorithm. Only characters defined in the JIS code set table
1399 can be used with this encoding method.
1401 @item @emph{UTF-8 Coding}
1403 A wide character is represented using
1404 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1405 10646-1/Am.2. Depending on the character value, the representation
1406 is a one, two, or three byte sequence:
1408 @example
1409 16#0000#-16#007f#: 2#0xxxxxxx#
1410 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1411 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1412 @end example
1414 where the @code{xxx} bits correspond to the left-padded bits of the
1415 16-bit character value. Note that all lower half ASCII characters
1416 are represented as ASCII bytes and all upper half characters and
1417 other wide characters are represented as sequences of upper-half
1418 (The full UTF-8 scheme allows for encoding 31-bit characters as
1419 6-byte sequences, and in the following section on wide wide
1420 characters, the use of these sequences is documented).
1422 @item @emph{Brackets Coding}
1424 In this encoding, a wide character is represented by the following eight
1425 character sequence:
1427 @example
1428 [ " a b c d " ]
1429 @end example
1431 where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1432 characters (using uppercase letters) of the wide character code. For
1433 example, [‘A345’] is used to represent the wide character with code
1434 @code{16#A345#}. It is also possible (though not required) to use the
1435 Brackets coding for upper half characters. For example, the code
1436 @code{16#A3#} can be represented as @code{['A3']}.
1438 This scheme is compatible with use of the full Wide_Character set,
1439 and is also the method used for wide character encoding in some standard
1440 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1441 @end table
1443 @cartouche
1444 @quotation Note 
1445 Some of these coding schemes do not permit the full use of the
1446 Ada character set. For example, neither Shift JIS nor EUC allow the
1447 use of the upper half of the Latin-1 set.
1448 @end quotation
1449 @end cartouche
1451 @node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1452 @anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{38}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{39}
1453 @subsection Wide_Wide_Character Encodings
1456 GNAT allows wide wide character codes to appear in character and string
1457 literals, and also optionally in identifiers, by means of the following
1458 possible encoding schemes:
1461 @table @asis
1463 @item @emph{UTF-8 Coding}
1465 A wide character is represented using
1466 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1467 10646-1/Am.2. Depending on the character value, the representation
1468 of character codes with values greater than 16#FFFF# is a
1469 is a four, five, or six byte sequence:
1471 @example
1472 16#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
1473                              10xxxxxx
1474 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1475                              10xxxxxx 10xxxxxx
1476 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1477                              10xxxxxx 10xxxxxx 10xxxxxx
1478 @end example
1480 where the @code{xxx} bits correspond to the left-padded bits of the
1481 32-bit character value.
1483 @item @emph{Brackets Coding}
1485 In this encoding, a wide wide character is represented by the following ten or
1486 twelve byte character sequence:
1488 @example
1489 [ " a b c d e f " ]
1490 [ " a b c d e f g h " ]
1491 @end example
1493 where @code{a-h} are the six or eight hexadecimal
1494 characters (using uppercase letters) of the wide wide character code. For
1495 example, [“1F4567”] is used to represent the wide wide character with code
1496 @code{16#001F_4567#}.
1498 This scheme is compatible with use of the full Wide_Wide_Character set,
1499 and is also the method used for wide wide character encoding in some standard
1500 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1501 @end table
1503 @node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1504 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{24}@anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{3a}
1505 @section File Naming Topics and Utilities
1508 GNAT has a default file naming scheme and also provides the user with
1509 a high degree of control over how the names and extensions of the
1510 source files correspond to the Ada compilation units that they contain.
1512 @menu
1513 * File Naming Rules:: 
1514 * Using Other File Names:: 
1515 * Alternative File Naming Schemes:: 
1516 * Handling Arbitrary File Naming Conventions with gnatname:: 
1517 * File Name Krunching with gnatkr:: 
1518 * Renaming Files with gnatchop:: 
1520 @end menu
1522 @node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1523 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{3b}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{3c}
1524 @subsection File Naming Rules
1527 The default file name is determined by the name of the unit that the
1528 file contains. The name is formed by taking the full expanded name of
1529 the unit and replacing the separating dots with hyphens and using
1530 lowercase for all letters.
1532 An exception arises if the file name generated by the above rules starts
1533 with one of the characters
1534 @code{a}, @code{g}, @code{i}, or @code{s}, and the second character is a
1535 minus. In this case, the character tilde is used in place
1536 of the minus. The reason for this special rule is to avoid clashes with
1537 the standard names for child units of the packages System, Ada,
1538 Interfaces, and GNAT, which use the prefixes
1539 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
1540 respectively.
1542 The file extension is @code{.ads} for a spec and
1543 @code{.adb} for a body. The following table shows some
1544 examples of these rules.
1546 @quotation
1549 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
1550 @item
1552 Source File
1554 @tab
1556 Ada Compilation Unit
1558 @item
1560 @code{main.ads}
1562 @tab
1564 Main (spec)
1566 @item
1568 @code{main.adb}
1570 @tab
1572 Main (body)
1574 @item
1576 @code{arith_functions.ads}
1578 @tab
1580 Arith_Functions (package spec)
1582 @item
1584 @code{arith_functions.adb}
1586 @tab
1588 Arith_Functions (package body)
1590 @item
1592 @code{func-spec.ads}
1594 @tab
1596 Func.Spec (child package spec)
1598 @item
1600 @code{func-spec.adb}
1602 @tab
1604 Func.Spec (child package body)
1606 @item
1608 @code{main-sub.adb}
1610 @tab
1612 Sub (subunit of Main)
1614 @item
1616 @code{a~bad.adb}
1618 @tab
1620 A.Bad (child package body)
1622 @end multitable
1624 @end quotation
1626 Following these rules can result in excessively long
1627 file names if corresponding
1628 unit names are long (for example, if child units or subunits are
1629 heavily nested). An option is available to shorten such long file names
1630 (called file name ‘krunching’). This may be particularly useful when
1631 programs being developed with GNAT are to be used on operating systems
1632 with limited file name lengths. @ref{3d,,Using gnatkr}.
1634 Of course, no file shortening algorithm can guarantee uniqueness over
1635 all possible unit names; if file name krunching is used, it is your
1636 responsibility to ensure no name clashes occur. Alternatively you
1637 can specify the exact file names that you want used, as described
1638 in the next section. Finally, if your Ada programs are migrating from a
1639 compiler with a different naming convention, you can use the gnatchop
1640 utility to produce source files that follow the GNAT naming conventions.
1641 (For details see @ref{1d,,Renaming Files with gnatchop}.)
1643 Note: in the case of Windows or Mac OS operating systems, case is not
1644 significant. So for example on Windows if the canonical name is
1645 @code{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1646 However, case is significant for other operating systems, so for example,
1647 if you want to use other than canonically cased file names on a Unix system,
1648 you need to follow the procedures described in the next section.
1650 @node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1651 @anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{3e}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{1c}
1652 @subsection Using Other File Names
1655 @geindex File names
1657 In the previous section, we have described the default rules used by
1658 GNAT to determine the file name in which a given unit resides. It is
1659 often convenient to follow these default rules, and if you follow them,
1660 the compiler knows without being explicitly told where to find all
1661 the files it needs.
1663 @geindex Source_File_Name pragma
1665 However, in some cases, particularly when a program is imported from
1666 another Ada compiler environment, it may be more convenient for the
1667 programmer to specify which file names contain which units. GNAT allows
1668 arbitrary file names to be used by means of the Source_File_Name pragma.
1669 The form of this pragma is as shown in the following examples:
1671 @example
1672 pragma Source_File_Name (My_Utilities.Stacks,
1673   Spec_File_Name => "myutilst_a.ada");
1674 pragma Source_File_name (My_Utilities.Stacks,
1675   Body_File_Name => "myutilst.ada");
1676 @end example
1678 As shown in this example, the first argument for the pragma is the unit
1679 name (in this example a child unit). The second argument has the form
1680 of a named association. The identifier
1681 indicates whether the file name is for a spec or a body;
1682 the file name itself is given by a string literal.
1684 The source file name pragma is a configuration pragma, which means that
1685 normally it will be placed in the @code{gnat.adc}
1686 file used to hold configuration
1687 pragmas that apply to a complete compilation environment.
1688 For more details on how the @code{gnat.adc} file is created and used
1689 see @ref{3f,,Handling of Configuration Pragmas}.
1691 @geindex gnat.adc
1693 GNAT allows completely arbitrary file names to be specified using the
1694 source file name pragma. However, if the file name specified has an
1695 extension other than @code{.ads} or @code{.adb} it is necessary to use
1696 a special syntax when compiling the file. The name in this case must be
1697 preceded by the special sequence @code{-x} followed by a space and the name
1698 of the language, here @code{ada}, as in:
1700 @example
1701 $ gcc -c -x ada peculiar_file_name.sim
1702 @end example
1704 @code{gnatmake} handles non-standard file names in the usual manner (the
1705 non-standard file name for the main program is simply used as the
1706 argument to gnatmake). Note that if the extension is also non-standard,
1707 then it must be included in the @code{gnatmake} command, it may not
1708 be omitted.
1710 @node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
1711 @anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{41}
1712 @subsection Alternative File Naming Schemes
1715 @geindex File naming schemes
1716 @geindex alternative
1718 @geindex File names
1720 The previous section described the use of the @code{Source_File_Name}
1721 pragma to allow arbitrary names to be assigned to individual source files.
1722 However, this approach requires one pragma for each file, and especially in
1723 large systems can result in very long @code{gnat.adc} files, and also create
1724 a maintenance problem.
1726 @geindex Source_File_Name pragma
1728 GNAT also provides a facility for specifying systematic file naming schemes
1729 other than the standard default naming scheme previously described. An
1730 alternative scheme for naming is specified by the use of
1731 @code{Source_File_Name} pragmas having the following format:
1733 @example
1734 pragma Source_File_Name (
1735    Spec_File_Name  => FILE_NAME_PATTERN
1736  [ , Casing          => CASING_SPEC]
1737  [ , Dot_Replacement => STRING_LITERAL ] );
1739 pragma Source_File_Name (
1740    Body_File_Name  => FILE_NAME_PATTERN
1741  [ , Casing          => CASING_SPEC ]
1742  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1744 pragma Source_File_Name (
1745    Subunit_File_Name  => FILE_NAME_PATTERN
1746  [ , Casing          => CASING_SPEC ]
1747  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1749 FILE_NAME_PATTERN ::= STRING_LITERAL
1750 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1751 @end example
1753 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1754 It contains a single asterisk character, and the unit name is substituted
1755 systematically for this asterisk. The optional parameter
1756 @code{Casing} indicates
1757 whether the unit name is to be all upper-case letters, all lower-case letters,
1758 or mixed-case. If no
1759 @code{Casing} parameter is used, then the default is all
1760 lower-case.
1762 The optional @code{Dot_Replacement} string is used to replace any periods
1763 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1764 argument is used then separating dots appear unchanged in the resulting
1765 file name.
1766 Although the above syntax indicates that the
1767 @code{Casing} argument must appear
1768 before the @code{Dot_Replacement} argument, but it
1769 is also permissible to write these arguments in the opposite order.
1771 As indicated, it is possible to specify different naming schemes for
1772 bodies, specs, and subunits. Quite often the rule for subunits is the
1773 same as the rule for bodies, in which case, there is no need to give
1774 a separate @code{Subunit_File_Name} rule, and in this case the
1775 @code{Body_File_name} rule is used for subunits as well.
1777 The separate rule for subunits can also be used to implement the rather
1778 unusual case of a compilation environment (e.g., a single directory) which
1779 contains a subunit and a child unit with the same unit name. Although
1780 both units cannot appear in the same partition, the Ada Reference Manual
1781 allows (but does not require) the possibility of the two units coexisting
1782 in the same environment.
1784 The file name translation works in the following steps:
1787 @itemize *
1789 @item 
1790 If there is a specific @code{Source_File_Name} pragma for the given unit,
1791 then this is always used, and any general pattern rules are ignored.
1793 @item 
1794 If there is a pattern type @code{Source_File_Name} pragma that applies to
1795 the unit, then the resulting file name will be used if the file exists. If
1796 more than one pattern matches, the latest one will be tried first, and the
1797 first attempt resulting in a reference to a file that exists will be used.
1799 @item 
1800 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1801 for which the corresponding file exists, then the standard GNAT default
1802 naming rules are used.
1803 @end itemize
1805 As an example of the use of this mechanism, consider a commonly used scheme
1806 in which file names are all lower case, with separating periods copied
1807 unchanged to the resulting file name, and specs end with @code{.1.ada}, and
1808 bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
1809 two pragmas appear:
1811 @example
1812 pragma Source_File_Name
1813   (Spec_File_Name => ".1.ada");
1814 pragma Source_File_Name
1815   (Body_File_Name => ".2.ada");
1816 @end example
1818 The default GNAT scheme is actually implemented by providing the following
1819 default pragmas internally:
1821 @example
1822 pragma Source_File_Name
1823   (Spec_File_Name => ".ads", Dot_Replacement => "-");
1824 pragma Source_File_Name
1825   (Body_File_Name => ".adb", Dot_Replacement => "-");
1826 @end example
1828 Our final example implements a scheme typically used with one of the
1829 Ada 83 compilers, where the separator character for subunits was ‘__’
1830 (two underscores), specs were identified by adding @code{_.ADA}, bodies
1831 by adding @code{.ADA}, and subunits by
1832 adding @code{.SEP}. All file names were
1833 upper case. Child units were not present of course since this was an
1834 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1835 the same double underscore separator for child units.
1837 @example
1838 pragma Source_File_Name
1839   (Spec_File_Name => "_.ADA",
1840    Dot_Replacement => "__",
1841    Casing = Uppercase);
1842 pragma Source_File_Name
1843   (Body_File_Name => ".ADA",
1844    Dot_Replacement => "__",
1845    Casing = Uppercase);
1846 pragma Source_File_Name
1847   (Subunit_File_Name => ".SEP",
1848    Dot_Replacement => "__",
1849    Casing = Uppercase);
1850 @end example
1852 @geindex gnatname
1854 @node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
1855 @anchor{gnat_ugn/the_gnat_compilation_model handling-arbitrary-file-naming-conventions-with-gnatname}@anchor{42}@anchor{gnat_ugn/the_gnat_compilation_model id12}@anchor{43}
1856 @subsection Handling Arbitrary File Naming Conventions with @code{gnatname}
1859 @geindex File Naming Conventions
1861 @menu
1862 * Arbitrary File Naming Conventions:: 
1863 * Running gnatname:: 
1864 * Switches for gnatname:: 
1865 * Examples of gnatname Usage:: 
1867 @end menu
1869 @node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
1870 @anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{44}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{45}
1871 @subsubsection Arbitrary File Naming Conventions
1874 The GNAT compiler must be able to know the source file name of a compilation
1875 unit.  When using the standard GNAT default file naming conventions
1876 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
1877 does not need additional information.
1879 When the source file names do not follow the standard GNAT default file naming
1880 conventions, the GNAT compiler must be given additional information through
1881 a configuration pragmas file (@ref{25,,Configuration Pragmas})
1882 or a project file.
1883 When the non-standard file naming conventions are well-defined,
1884 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
1885 (@ref{40,,Alternative File Naming Schemes}) may be sufficient. However,
1886 if the file naming conventions are irregular or arbitrary, a number
1887 of pragma @code{Source_File_Name} for individual compilation units
1888 must be defined.
1889 To help maintain the correspondence between compilation unit names and
1890 source file names within the compiler,
1891 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
1892 set of files.
1894 @node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
1895 @anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{46}@anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{47}
1896 @subsubsection Running @code{gnatname}
1899 The usual form of the @code{gnatname} command is:
1901 @example
1902 $ gnatname [ switches ]  naming_pattern  [ naming_patterns ]
1903     [--and [ switches ]  naming_pattern  [ naming_patterns ]]
1904 @end example
1906 All of the arguments are optional. If invoked without any argument,
1907 @code{gnatname} will display its usage.
1909 When used with at least one naming pattern, @code{gnatname} will attempt to
1910 find all the compilation units in files that follow at least one of the
1911 naming patterns. To find these compilation units,
1912 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
1913 regular files.
1915 One or several Naming Patterns may be given as arguments to @code{gnatname}.
1916 Each Naming Pattern is enclosed between double quotes (or single
1917 quotes on Windows).
1918 A Naming Pattern is a regular expression similar to the wildcard patterns
1919 used in file names by the Unix shells or the DOS prompt.
1921 @code{gnatname} may be called with several sections of directories/patterns.
1922 Sections are separated by the switch @code{--and}. In each section, there must be
1923 at least one pattern. If no directory is specified in a section, the current
1924 directory (or the project directory if @code{-P} is used) is implied.
1925 The options other that the directory switches and the patterns apply globally
1926 even if they are in different sections.
1928 Examples of Naming Patterns are:
1930 @example
1931 "*.[12].ada"
1932 "*.ad[sb]*"
1933 "body_*"    "spec_*"
1934 @end example
1936 For a more complete description of the syntax of Naming Patterns,
1937 see the second kind of regular expressions described in @code{g-regexp.ads}
1938 (the ‘Glob’ regular expressions).
1940 When invoked without the switch @code{-P}, @code{gnatname} will create a
1941 configuration pragmas file @code{gnat.adc} in the current working directory,
1942 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
1943 unit.
1945 @node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
1946 @anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{48}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{49}
1947 @subsubsection Switches for @code{gnatname}
1950 Switches for @code{gnatname} must precede any specified Naming Pattern.
1952 You may specify any of the following switches to @code{gnatname}:
1954 @geindex --version (gnatname)
1957 @table @asis
1959 @item @code{--version}
1961 Display Copyright and version, then exit disregarding all other options.
1962 @end table
1964 @geindex --help (gnatname)
1967 @table @asis
1969 @item @code{--help}
1971 If @code{--version} was not used, display usage, then exit disregarding
1972 all other options.
1974 @item @code{--subdirs=@emph{dir}}
1976 Real object, library or exec directories are subdirectories <dir> of the
1977 specified ones.
1979 @item @code{--no-backup}
1981 Do not create a backup copy of an existing project file.
1983 @item @code{--and}
1985 Start another section of directories/patterns.
1986 @end table
1988 @geindex -c (gnatname)
1991 @table @asis
1993 @item @code{-c@emph{filename}}
1995 Create a configuration pragmas file @code{filename} (instead of the default
1996 @code{gnat.adc}).
1997 There may be zero, one or more space between @code{-c} and
1998 @code{filename}.
1999 @code{filename} may include directory information. @code{filename} must be
2000 writable. There may be only one switch @code{-c}.
2001 When a switch @code{-c} is
2002 specified, no switch @code{-P} may be specified (see below).
2003 @end table
2005 @geindex -d (gnatname)
2008 @table @asis
2010 @item @code{-d@emph{dir}}
2012 Look for source files in directory @code{dir}. There may be zero, one or more
2013 spaces between @code{-d} and @code{dir}.
2014 @code{dir} may end with @code{/**}, that is it may be of the form
2015 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
2016 subdirectories, recursively, have to be searched for sources.
2017 When a switch @code{-d}
2018 is specified, the current working directory will not be searched for source
2019 files, unless it is explicitly specified with a @code{-d}
2020 or @code{-D} switch.
2021 Several switches @code{-d} may be specified.
2022 If @code{dir} is a relative path, it is relative to the directory of
2023 the configuration pragmas file specified with switch
2024 @code{-c},
2025 or to the directory of the project file specified with switch
2026 @code{-P} or,
2027 if neither switch @code{-c}
2028 nor switch @code{-P} are specified, it is relative to the
2029 current working directory. The directory
2030 specified with switch @code{-d} must exist and be readable.
2031 @end table
2033 @geindex -D (gnatname)
2036 @table @asis
2038 @item @code{-D@emph{filename}}
2040 Look for source files in all directories listed in text file @code{filename}.
2041 There may be zero, one or more spaces between @code{-D}
2042 and @code{filename}.
2043 @code{filename} must be an existing, readable text file.
2044 Each nonempty line in @code{filename} must be a directory.
2045 Specifying switch @code{-D} is equivalent to specifying as many
2046 switches @code{-d} as there are nonempty lines in
2047 @code{file}.
2049 @item @code{-eL}
2051 Follow symbolic links when processing project files.
2053 @geindex -f (gnatname)
2055 @item @code{-f@emph{pattern}}
2057 Foreign patterns. Using this switch, it is possible to add sources of languages
2058 other than Ada to the list of sources of a project file.
2059 It is only useful if a -P switch is used.
2060 For example,
2062 @example
2063 gnatname -Pprj -f"*.c" "*.ada"
2064 @end example
2066 will look for Ada units in all files with the @code{.ada} extension,
2067 and will add to the list of file for project @code{prj.gpr} the C files
2068 with extension @code{.c}.
2070 @geindex -h (gnatname)
2072 @item @code{-h}
2074 Output usage (help) information. The output is written to @code{stdout}.
2076 @geindex -P (gnatname)
2078 @item @code{-P@emph{proj}}
2080 Create or update project file @code{proj}. There may be zero, one or more space
2081 between @code{-P} and @code{proj}. @code{proj} may include directory
2082 information. @code{proj} must be writable.
2083 There may be only one switch @code{-P}.
2084 When a switch @code{-P} is specified,
2085 no switch @code{-c} may be specified.
2086 On all platforms, except on VMS, when @code{gnatname} is invoked for an
2087 existing project file <proj>.gpr, a backup copy of the project file is created
2088 in the project directory with file name <proj>.gpr.saved_x. ‘x’ is the first
2089 non negative number that makes this backup copy a new file.
2091 @geindex -v (gnatname)
2093 @item @code{-v}
2095 Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2096 This includes name of the file written, the name of the directories to search
2097 and, for each file in those directories whose name matches at least one of
2098 the Naming Patterns, an indication of whether the file contains a unit,
2099 and if so the name of the unit.
2100 @end table
2102 @geindex -v -v (gnatname)
2105 @table @asis
2107 @item @code{-v -v}
2109 Very Verbose mode. In addition to the output produced in verbose mode,
2110 for each file in the searched directories whose name matches none of
2111 the Naming Patterns, an indication is given that there is no match.
2113 @geindex -x (gnatname)
2115 @item @code{-x@emph{pattern}}
2117 Excluded patterns. Using this switch, it is possible to exclude some files
2118 that would match the name patterns. For example,
2120 @example
2121 gnatname -x "*_nt.ada" "*.ada"
2122 @end example
2124 will look for Ada units in all files with the @code{.ada} extension,
2125 except those whose names end with @code{_nt.ada}.
2126 @end table
2128 @node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2129 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{4a}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{4b}
2130 @subsubsection Examples of @code{gnatname} Usage
2133 @example
2134 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2135 @end example
2137 In this example, the directory @code{/home/me} must already exist
2138 and be writable. In addition, the directory
2139 @code{/home/me/sources} (specified by
2140 @code{-d sources}) must exist and be readable.
2142 Note the optional spaces after @code{-c} and @code{-d}.
2144 @example
2145 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
2146 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2147 @end example
2149 Note that several switches @code{-d} may be used,
2150 even in conjunction with one or several switches
2151 @code{-D}. Several Naming Patterns and one excluded pattern
2152 are used in this example.
2154 @node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2155 @anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{4c}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{4d}
2156 @subsection File Name Krunching with @code{gnatkr}
2159 @geindex gnatkr
2161 This section discusses the method used by the compiler to shorten
2162 the default file names chosen for Ada units so that they do not
2163 exceed the maximum length permitted. It also describes the
2164 @code{gnatkr} utility that can be used to determine the result of
2165 applying this shortening.
2167 @menu
2168 * About gnatkr:: 
2169 * Using gnatkr:: 
2170 * Krunching Method:: 
2171 * Examples of gnatkr Usage:: 
2173 @end menu
2175 @node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2176 @anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{4e}@anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{4f}
2177 @subsubsection About @code{gnatkr}
2180 The default file naming rule in GNAT
2181 is that the file name must be derived from
2182 the unit name. The exact default rule is as follows:
2185 @itemize *
2187 @item 
2188 Take the unit name and replace all dots by hyphens.
2190 @item 
2191 If such a replacement occurs in the
2192 second character position of a name, and the first character is
2193 @code{a}, @code{g}, @code{s}, or @code{i},
2194 then replace the dot by the character
2195 @code{~} (tilde)
2196 instead of a minus.
2198 The reason for this exception is to avoid clashes
2199 with the standard names for children of System, Ada, Interfaces,
2200 and GNAT, which use the prefixes
2201 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
2202 respectively.
2203 @end itemize
2205 The @code{-gnatk@emph{nn}}
2206 switch of the compiler activates a ‘krunching’
2207 circuit that limits file names to nn characters (where nn is a decimal
2208 integer).
2210 The @code{gnatkr} utility can be used to determine the krunched name for
2211 a given file, when krunched to a specified maximum length.
2213 @node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2214 @anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{50}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{3d}
2215 @subsubsection Using @code{gnatkr}
2218 The @code{gnatkr} command has the form:
2220 @example
2221 $ gnatkr name [ length ]
2222 @end example
2224 @code{name} is the uncrunched file name, derived from the name of the unit
2225 in the standard manner described in the previous section (i.e., in particular
2226 all dots are replaced by hyphens). The file name may or may not have an
2227 extension (defined as a suffix of the form period followed by arbitrary
2228 characters other than period). If an extension is present then it will
2229 be preserved in the output. For example, when krunching @code{hellofile.ads}
2230 to eight characters, the result will be hellofil.ads.
2232 Note: for compatibility with previous versions of @code{gnatkr} dots may
2233 appear in the name instead of hyphens, but the last dot will always be
2234 taken as the start of an extension. So if @code{gnatkr} is given an argument
2235 such as @code{Hello.World.adb} it will be treated exactly as if the first
2236 period had been a hyphen, and for example krunching to eight characters
2237 gives the result @code{hellworl.adb}.
2239 Note that the result is always all lower case.
2240 Characters of the other case are folded as required.
2242 @code{length} represents the length of the krunched name. The default
2243 when no argument is given is 8 characters. A length of zero stands for
2244 unlimited, in other words do not chop except for system files where the
2245 implied crunching length is always eight characters.
2247 The output is the krunched name. The output has an extension only if the
2248 original argument was a file name with an extension.
2250 @node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2251 @anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{52}
2252 @subsubsection Krunching Method
2255 The initial file name is determined by the name of the unit that the file
2256 contains. The name is formed by taking the full expanded name of the
2257 unit and replacing the separating dots with hyphens and
2258 using lowercase
2259 for all letters, except that a hyphen in the second character position is
2260 replaced by a tilde if the first character is
2261 @code{a}, @code{i}, @code{g}, or @code{s}.
2262 The extension is @code{.ads} for a
2263 spec and @code{.adb} for a body.
2264 Krunching does not affect the extension, but the file name is shortened to
2265 the specified length by following these rules:
2268 @itemize *
2270 @item 
2271 The name is divided into segments separated by hyphens, tildes or
2272 underscores and all hyphens, tildes, and underscores are
2273 eliminated. If this leaves the name short enough, we are done.
2275 @item 
2276 If the name is too long, the longest segment is located (left-most
2277 if there are two of equal length), and shortened by dropping
2278 its last character. This is repeated until the name is short enough.
2280 As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2281 to fit the name into 8 characters as required by some operating systems:
2283 @example
2284 our-strings-wide_fixed 22
2285 our strings wide fixed 19
2286 our string  wide fixed 18
2287 our strin   wide fixed 17
2288 our stri    wide fixed 16
2289 our stri    wide fixe  15
2290 our str     wide fixe  14
2291 our str     wid  fixe  13
2292 our str     wid  fix   12
2293 ou  str     wid  fix   11
2294 ou  st      wid  fix   10
2295 ou  st      wi   fix   9
2296 ou  st      wi   fi    8
2297 Final file name: oustwifi.adb
2298 @end example
2300 @item 
2301 The file names for all predefined units are always krunched to eight
2302 characters. The krunching of these predefined units uses the following
2303 special prefix replacements:
2306 @multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
2307 @item
2309 Prefix
2311 @tab
2313 Replacement
2315 @item
2317 @code{ada-}
2319 @tab
2321 @code{a-}
2323 @item
2325 @code{gnat-}
2327 @tab
2329 @code{g-}
2331 @item
2333 @code{interfac es-}
2335 @tab
2337 @code{i-}
2339 @item
2341 @code{system-}
2343 @tab
2345 @code{s-}
2347 @end multitable
2350 These system files have a hyphen in the second character position. That
2351 is why normal user files replace such a character with a
2352 tilde, to avoid confusion with system file names.
2354 As an example of this special rule, consider
2355 @code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2357 @example
2358 ada-strings-wide_fixed 22
2359 a-  strings wide fixed 18
2360 a-  string  wide fixed 17
2361 a-  strin   wide fixed 16
2362 a-  stri    wide fixed 15
2363 a-  stri    wide fixe  14
2364 a-  str     wide fixe  13
2365 a-  str     wid  fixe  12
2366 a-  str     wid  fix   11
2367 a-  st      wid  fix   10
2368 a-  st      wi   fix   9
2369 a-  st      wi   fi    8
2370 Final file name: a-stwifi.adb
2371 @end example
2372 @end itemize
2374 Of course no file shortening algorithm can guarantee uniqueness over all
2375 possible unit names, and if file name krunching is used then it is your
2376 responsibility to ensure that no name clashes occur. The utility
2377 program @code{gnatkr} is supplied for conveniently determining the
2378 krunched name of a file.
2380 @node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2381 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{53}@anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{54}
2382 @subsubsection Examples of @code{gnatkr} Usage
2385 @example
2386 $ gnatkr very_long_unit_name.ads      --> velounna.ads
2387 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
2388 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2389 $ gnatkr grandparent-parent-child     --> grparchi
2390 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2391 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2392 @end example
2394 @node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2395 @anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{55}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{1d}
2396 @subsection Renaming Files with @code{gnatchop}
2399 @geindex gnatchop
2401 This section discusses how to handle files with multiple units by using
2402 the @code{gnatchop} utility. This utility is also useful in renaming
2403 files to meet the standard GNAT default file naming conventions.
2405 @menu
2406 * Handling Files with Multiple Units:: 
2407 * Operating gnatchop in Compilation Mode:: 
2408 * Command Line for gnatchop:: 
2409 * Switches for gnatchop:: 
2410 * Examples of gnatchop Usage:: 
2412 @end menu
2414 @node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2415 @anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{56}@anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{57}
2416 @subsubsection Handling Files with Multiple Units
2419 The basic compilation model of GNAT requires that a file submitted to the
2420 compiler have only one unit and there be a strict correspondence
2421 between the file name and the unit name.
2423 If you want to keep your files with multiple units,
2424 perhaps to maintain compatibility with some other Ada compilation system,
2425 you can use @code{gnatname} to generate or update your project files.
2426 Generated or modified project files can be processed by GNAT.
2428 See @ref{42,,Handling Arbitrary File Naming Conventions with gnatname}
2429 for more details on how to use @cite{gnatname}.
2431 Alternatively, if you want to permanently restructure a set of ‘foreign’
2432 files so that they match the GNAT rules, and do the remaining development
2433 using the GNAT structure, you can simply use @code{gnatchop} once, generate the
2434 new set of files and work with them from that point on.
2436 Note that if your file containing multiple units starts with a byte order
2437 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2438 will each start with a copy of this BOM, meaning that they can be compiled
2439 automatically in UTF-8 mode without needing to specify an explicit encoding.
2441 @node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2442 @anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{58}@anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{59}
2443 @subsubsection Operating gnatchop in Compilation Mode
2446 The basic function of @code{gnatchop} is to take a file with multiple units
2447 and split it into separate files. The boundary between files is reasonably
2448 clear, except for the issue of comments and pragmas. In default mode, the
2449 rule is that any pragmas between units belong to the previous unit, except
2450 that configuration pragmas always belong to the following unit. Any comments
2451 belong to the following unit. These rules
2452 almost always result in the right choice of
2453 the split point without needing to mark it explicitly and most users will
2454 find this default to be what they want. In this default mode it is incorrect to
2455 submit a file containing only configuration pragmas, or one that ends in
2456 configuration pragmas, to @code{gnatchop}.
2458 However, using a special option to activate ‘compilation mode’,
2459 @code{gnatchop}
2460 can perform another function, which is to provide exactly the semantics
2461 required by the RM for handling of configuration pragmas in a compilation.
2462 In the absence of configuration pragmas (at the main file level), this
2463 option has no effect, but it causes such configuration pragmas to be handled
2464 in a quite different manner.
2466 First, in compilation mode, if @code{gnatchop} is given a file that consists of
2467 only configuration pragmas, then this file is appended to the
2468 @code{gnat.adc} file in the current directory. This behavior provides
2469 the required behavior described in the RM for the actions to be taken
2470 on submitting such a file to the compiler, namely that these pragmas
2471 should apply to all subsequent compilations in the same compilation
2472 environment. Using GNAT, the current directory, possibly containing a
2473 @code{gnat.adc} file is the representation
2474 of a compilation environment. For more information on the
2475 @code{gnat.adc} file, see @ref{3f,,Handling of Configuration Pragmas}.
2477 Second, in compilation mode, if @code{gnatchop}
2478 is given a file that starts with
2479 configuration pragmas, and contains one or more units, then these
2480 configuration pragmas are prepended to each of the chopped files. This
2481 behavior provides the required behavior described in the RM for the
2482 actions to be taken on compiling such a file, namely that the pragmas
2483 apply to all units in the compilation, but not to subsequently compiled
2484 units.
2486 Finally, if configuration pragmas appear between units, they are appended
2487 to the previous unit. This results in the previous unit being illegal,
2488 since the compiler does not accept configuration pragmas that follow
2489 a unit. This provides the required RM behavior that forbids configuration
2490 pragmas other than those preceding the first compilation unit of a
2491 compilation.
2493 For most purposes, @code{gnatchop} will be used in default mode. The
2494 compilation mode described above is used only if you need exactly
2495 accurate behavior with respect to compilations, and you have files
2496 that contain multiple units and configuration pragmas. In this
2497 circumstance the use of @code{gnatchop} with the compilation mode
2498 switch provides the required behavior, and is for example the mode
2499 in which GNAT processes the ACVC tests.
2501 @node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2502 @anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{5a}@anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{5b}
2503 @subsubsection Command Line for @code{gnatchop}
2506 The @code{gnatchop} command has the form:
2508 @example
2509 $ gnatchop switches file_name [file_name ...]
2510       [directory]
2511 @end example
2513 The only required argument is the file name of the file to be chopped.
2514 There are no restrictions on the form of this file name. The file itself
2515 contains one or more Ada units, in normal GNAT format, concatenated
2516 together. As shown, more than one file may be presented to be chopped.
2518 When run in default mode, @code{gnatchop} generates one output file in
2519 the current directory for each unit in each of the files.
2521 @code{directory}, if specified, gives the name of the directory to which
2522 the output files will be written. If it is not specified, all files are
2523 written to the current directory.
2525 For example, given a
2526 file called @code{hellofiles} containing
2528 @example
2529 procedure Hello;
2531 with Ada.Text_IO; use Ada.Text_IO;
2532 procedure Hello is
2533 begin
2534    Put_Line ("Hello");
2535 end Hello;
2536 @end example
2538 the command
2540 @example
2541 $ gnatchop hellofiles
2542 @end example
2544 generates two files in the current directory, one called
2545 @code{hello.ads} containing the single line that is the procedure spec,
2546 and the other called @code{hello.adb} containing the remaining text. The
2547 original file is not affected. The generated files can be compiled in
2548 the normal manner.
2550 When gnatchop is invoked on a file that is empty or that contains only empty
2551 lines and/or comments, gnatchop will not fail, but will not produce any
2552 new sources.
2554 For example, given a
2555 file called @code{toto.txt} containing
2557 @example
2558 --  Just a comment
2559 @end example
2561 the command
2563 @example
2564 $ gnatchop toto.txt
2565 @end example
2567 will not produce any new file and will result in the following warnings:
2569 @example
2570 toto.txt:1:01: warning: empty file, contains no compilation units
2571 no compilation units found
2572 no source files written
2573 @end example
2575 @node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2576 @anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{5c}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{5d}
2577 @subsubsection Switches for @code{gnatchop}
2580 @code{gnatchop} recognizes the following switches:
2582 @geindex --version (gnatchop)
2585 @table @asis
2587 @item @code{--version}
2589 Display Copyright and version, then exit disregarding all other options.
2590 @end table
2592 @geindex --help (gnatchop)
2595 @table @asis
2597 @item @code{--help}
2599 If @code{--version} was not used, display usage, then exit disregarding
2600 all other options.
2601 @end table
2603 @geindex -c (gnatchop)
2606 @table @asis
2608 @item @code{-c}
2610 Causes @code{gnatchop} to operate in compilation mode, in which
2611 configuration pragmas are handled according to strict RM rules. See
2612 previous section for a full description of this mode.
2614 @item @code{-gnat@emph{xxx}}
2616 This passes the given @code{-gnat@emph{xxx}} switch to @code{gnat} which is
2617 used to parse the given file. Not all @emph{xxx} options make sense,
2618 but for example, the use of @code{-gnati2} allows @code{gnatchop} to
2619 process a source file that uses Latin-2 coding for identifiers.
2621 @item @code{-h}
2623 Causes @code{gnatchop} to generate a brief help summary to the standard
2624 output file showing usage information.
2625 @end table
2627 @geindex -k (gnatchop)
2630 @table @asis
2632 @item @code{-k@emph{mm}}
2634 Limit generated file names to the specified number @code{mm}
2635 of characters.
2636 This is useful if the
2637 resulting set of files is required to be interoperable with systems
2638 which limit the length of file names.
2639 No space is allowed between the @code{-k} and the numeric value. The numeric
2640 value may be omitted in which case a default of @code{-k8},
2641 suitable for use
2642 with DOS-like file systems, is used. If no @code{-k} switch
2643 is present then
2644 there is no limit on the length of file names.
2645 @end table
2647 @geindex -p (gnatchop)
2650 @table @asis
2652 @item @code{-p}
2654 Causes the file modification time stamp of the input file to be
2655 preserved and used for the time stamp of the output file(s). This may be
2656 useful for preserving coherency of time stamps in an environment where
2657 @code{gnatchop} is used as part of a standard build process.
2658 @end table
2660 @geindex -q (gnatchop)
2663 @table @asis
2665 @item @code{-q}
2667 Causes output of informational messages indicating the set of generated
2668 files to be suppressed. Warnings and error messages are unaffected.
2669 @end table
2671 @geindex -r (gnatchop)
2673 @geindex Source_Reference pragmas
2676 @table @asis
2678 @item @code{-r}
2680 Generate @code{Source_Reference} pragmas. Use this switch if the output
2681 files are regarded as temporary and development is to be done in terms
2682 of the original unchopped file. This switch causes
2683 @code{Source_Reference} pragmas to be inserted into each of the
2684 generated files to refers back to the original file name and line number.
2685 The result is that all error messages refer back to the original
2686 unchopped file.
2687 In addition, the debugging information placed into the object file (when
2688 the @code{-g} switch of @code{gcc} or @code{gnatmake} is
2689 specified)
2690 also refers back to this original file so that tools like profilers and
2691 debuggers will give information in terms of the original unchopped file.
2693 If the original file to be chopped itself contains
2694 a @code{Source_Reference}
2695 pragma referencing a third file, then gnatchop respects
2696 this pragma, and the generated @code{Source_Reference} pragmas
2697 in the chopped file refer to the original file, with appropriate
2698 line numbers. This is particularly useful when @code{gnatchop}
2699 is used in conjunction with @code{gnatprep} to compile files that
2700 contain preprocessing statements and multiple units.
2701 @end table
2703 @geindex -v (gnatchop)
2706 @table @asis
2708 @item @code{-v}
2710 Causes @code{gnatchop} to operate in verbose mode. The version
2711 number and copyright notice are output, as well as exact copies of
2712 the gnat1 commands spawned to obtain the chop control information.
2713 @end table
2715 @geindex -w (gnatchop)
2718 @table @asis
2720 @item @code{-w}
2722 Overwrite existing file names. Normally @code{gnatchop} regards it as a
2723 fatal error if there is already a file with the same name as a
2724 file it would otherwise output, in other words if the files to be
2725 chopped contain duplicated units. This switch bypasses this
2726 check, and causes all but the last instance of such duplicated
2727 units to be skipped.
2728 @end table
2730 @geindex --GCC= (gnatchop)
2733 @table @asis
2735 @item @code{--GCC=@emph{xxxx}}
2737 Specify the path of the GNAT parser to be used. When this switch is used,
2738 no attempt is made to add the prefix to the GNAT parser executable.
2739 @end table
2741 @node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
2742 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{5e}@anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{5f}
2743 @subsubsection Examples of @code{gnatchop} Usage
2746 @example
2747 $ gnatchop -w hello_s.ada prerelease/files
2748 @end example
2750 Chops the source file @code{hello_s.ada}. The output files will be
2751 placed in the directory @code{prerelease/files},
2752 overwriting any
2753 files with matching names in that directory (no files in the current
2754 directory are modified).
2756 @example
2757 $ gnatchop archive
2758 @end example
2760 Chops the source file @code{archive}
2761 into the current directory. One
2762 useful application of @code{gnatchop} is in sending sets of sources
2763 around, for example in email messages. The required sources are simply
2764 concatenated (for example, using a Unix @code{cat}
2765 command), and then
2766 @code{gnatchop} is used at the other end to reconstitute the original
2767 file names.
2769 @example
2770 $ gnatchop file1 file2 file3 direc
2771 @end example
2773 Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
2774 the resulting files in the directory @code{direc}. Note that if any units
2775 occur more than once anywhere within this set of files, an error message
2776 is generated, and no files are written. To override this check, use the
2777 @code{-w} switch,
2778 in which case the last occurrence in the last file will
2779 be the one that is output, and earlier duplicate occurrences for a given
2780 unit will be skipped.
2782 @node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
2783 @anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{25}@anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{60}
2784 @section Configuration Pragmas
2787 @geindex Configuration pragmas
2789 @geindex Pragmas
2790 @geindex configuration
2792 Configuration pragmas include those pragmas described as
2793 such in the Ada Reference Manual, as well as
2794 implementation-dependent pragmas that are configuration pragmas.
2795 See the @code{Implementation_Defined_Pragmas} chapter in the
2796 @cite{GNAT_Reference_Manual} for details on these
2797 additional GNAT-specific configuration pragmas.
2798 Most notably, the pragma @code{Source_File_Name}, which allows
2799 specifying non-default names for source files, is a configuration
2800 pragma. The following is a complete list of configuration pragmas
2801 recognized by GNAT:
2803 @example
2804 Ada_83
2805 Ada_95
2806 Ada_05
2807 Ada_2005
2808 Ada_12
2809 Ada_2012
2810 Ada_2022
2811 Allow_Integer_Address
2812 Annotate
2813 Assertion_Policy
2814 Assume_No_Invalid_Values
2815 C_Pass_By_Copy
2816 Check_Float_Overflow
2817 Check_Name
2818 Check_Policy
2819 Component_Alignment
2820 Convention_Identifier
2821 Debug_Policy
2822 Default_Scalar_Storage_Order
2823 Default_Storage_Pool
2824 Detect_Blocking
2825 Disable_Atomic_Synchronization
2826 Discard_Names
2827 Elaboration_Checks
2828 Eliminate
2829 Enable_Atomic_Synchronization
2830 Extend_System
2831 Extensions_Allowed
2832 External_Name_Casing
2833 Fast_Math
2834 Favor_Top_Level
2835 Ignore_Pragma
2836 Implicit_Packing
2837 Initialize_Scalars
2838 Interrupt_State
2839 License
2840 Locking_Policy
2841 No_Component_Reordering
2842 No_Heap_Finalization
2843 No_Strict_Aliasing
2844 Normalize_Scalars
2845 Optimize_Alignment
2846 Overflow_Mode
2847 Overriding_Renamings
2848 Partition_Elaboration_Policy
2849 Persistent_BSS
2850 Prefix_Exception_Messages
2851 Priority_Specific_Dispatching
2852 Profile
2853 Profile_Warnings
2854 Queuing_Policy
2855 Rename_Pragma
2856 Restrictions
2857 Restriction_Warnings
2858 Reviewable
2859 Short_Circuit_And_Or
2860 Source_File_Name
2861 Source_File_Name_Project
2862 SPARK_Mode
2863 Style_Checks
2864 Suppress
2865 Suppress_Exception_Locations
2866 Task_Dispatching_Policy
2867 Unevaluated_Use_Of_Old
2868 Unsuppress
2869 Use_VADS_Size
2870 Validity_Checks
2871 Warning_As_Error
2872 Warnings
2873 Wide_Character_Encoding
2874 @end example
2876 @menu
2877 * Handling of Configuration Pragmas:: 
2878 * The Configuration Pragmas Files:: 
2880 @end menu
2882 @node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
2883 @anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{3f}@anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{61}
2884 @subsection Handling of Configuration Pragmas
2887 Configuration pragmas may either appear at the start of a compilation
2888 unit, or they can appear in a configuration pragma file to apply to
2889 all compilations performed in a given compilation environment.
2891 GNAT also provides the @code{gnatchop} utility to provide an automatic
2892 way to handle configuration pragmas following the semantics for
2893 compilations (that is, files with multiple units), described in the RM.
2894 See @ref{59,,Operating gnatchop in Compilation Mode} for details.
2895 However, for most purposes, it will be more convenient to edit the
2896 @code{gnat.adc} file that contains configuration pragmas directly,
2897 as described in the following section.
2899 In the case of @code{Restrictions} pragmas appearing as configuration
2900 pragmas in individual compilation units, the exact handling depends on
2901 the type of restriction.
2903 Restrictions that require partition-wide consistency (like
2904 @code{No_Tasking}) are
2905 recognized wherever they appear
2906 and can be freely inherited, e.g. from a @emph{with}ed unit to the @emph{with}ing
2907 unit. This makes sense since the binder will in any case insist on seeing
2908 consistent use, so any unit not conforming to any restrictions that are
2909 anywhere in the partition will be rejected, and you might as well find
2910 that out at compile time rather than at bind time.
2912 For restrictions that do not require partition-wide consistency, e.g.
2913 SPARK or No_Implementation_Attributes, in general the restriction applies
2914 only to the unit in which the pragma appears, and not to any other units.
2916 The exception is No_Elaboration_Code which always applies to the entire
2917 object file from a compilation, i.e. to the body, spec, and all subunits.
2918 This restriction can be specified in a configuration pragma file, or it
2919 can be on the body and/or the spec (in either case it applies to all the
2920 relevant units). It can appear on a subunit only if it has previously
2921 appeared in the body of spec.
2923 @node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
2924 @anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{62}@anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{63}
2925 @subsection The Configuration Pragmas Files
2928 @geindex gnat.adc
2930 In GNAT a compilation environment is defined by the current
2931 directory at the time that a compile command is given. This current
2932 directory is searched for a file whose name is @code{gnat.adc}. If
2933 this file is present, it is expected to contain one or more
2934 configuration pragmas that will be applied to the current compilation.
2935 However, if the switch @code{-gnatA} is used, @code{gnat.adc} is not
2936 considered. When taken into account, @code{gnat.adc} is added to the
2937 dependencies, so that if @code{gnat.adc} is modified later, an invocation of
2938 @code{gnatmake} will recompile the source.
2940 Configuration pragmas may be entered into the @code{gnat.adc} file
2941 either by running @code{gnatchop} on a source file that consists only of
2942 configuration pragmas, or more conveniently by direct editing of the
2943 @code{gnat.adc} file, which is a standard format source file.
2945 Besides @code{gnat.adc}, additional files containing configuration
2946 pragmas may be applied to the current compilation using the switch
2947 @code{-gnatec=@emph{path}} where @code{path} must designate an existing file that
2948 contains only configuration pragmas. These configuration pragmas are
2949 in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
2950 is present and switch @code{-gnatA} is not used).
2952 It is allowable to specify several switches @code{-gnatec=}, all of which
2953 will be taken into account.
2955 Files containing configuration pragmas specified with switches
2956 @code{-gnatec=} are added to the dependencies, unless they are
2957 temporary files. A file is considered temporary if its name ends in
2958 @code{.tmp} or @code{.TMP}. Certain tools follow this naming
2959 convention because they pass information to @code{gcc} via
2960 temporary files that are immediately deleted; it doesn’t make sense to
2961 depend on a file that no longer exists. Such tools include
2962 @code{gprbuild}, @code{gnatmake}, and @code{gnatcheck}.
2964 By default, configuration pragma files are stored by their absolute paths in
2965 ALI files. You can use the @code{-gnateb} switch in order to store them by
2966 their basename instead.
2968 If you are using project file, a separate mechanism is provided using
2969 project attributes.
2971 @c --Comment
2972 @c See :ref:`Specifying_Configuration_Pragmas` for more details.
2974 @node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
2975 @anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{26}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{64}
2976 @section Generating Object Files
2979 An Ada program consists of a set of source files, and the first step in
2980 compiling the program is to generate the corresponding object files.
2981 These are generated by compiling a subset of these source files.
2982 The files you need to compile are the following:
2985 @itemize *
2987 @item 
2988 If a package spec has no body, compile the package spec to produce the
2989 object file for the package.
2991 @item 
2992 If a package has both a spec and a body, compile the body to produce the
2993 object file for the package. The source file for the package spec need
2994 not be compiled in this case because there is only one object file, which
2995 contains the code for both the spec and body of the package.
2997 @item 
2998 For a subprogram, compile the subprogram body to produce the object file
2999 for the subprogram. The spec, if one is present, is as usual in a
3000 separate file, and need not be compiled.
3001 @end itemize
3003 @geindex Subunits
3006 @itemize *
3008 @item 
3009 In the case of subunits, only compile the parent unit. A single object
3010 file is generated for the entire subunit tree, which includes all the
3011 subunits.
3013 @item 
3014 Compile child units independently of their parent units
3015 (though, of course, the spec of all the ancestor unit must be present in order
3016 to compile a child unit).
3018 @geindex Generics
3020 @item 
3021 Compile generic units in the same manner as any other units. The object
3022 files in this case are small dummy files that contain at most the
3023 flag used for elaboration checking. This is because GNAT always handles generic
3024 instantiation by means of macro expansion. However, it is still necessary to
3025 compile generic units, for dependency checking and elaboration purposes.
3026 @end itemize
3028 The preceding rules describe the set of files that must be compiled to
3029 generate the object files for a program. Each object file has the same
3030 name as the corresponding source file, except that the extension is
3031 @code{.o} as usual.
3033 You may wish to compile other files for the purpose of checking their
3034 syntactic and semantic correctness. For example, in the case where a
3035 package has a separate spec and body, you would not normally compile the
3036 spec. However, it is convenient in practice to compile the spec to make
3037 sure it is error-free before compiling clients of this spec, because such
3038 compilations will fail if there is an error in the spec.
3040 GNAT provides an option for compiling such files purely for the
3041 purposes of checking correctness; such compilations are not required as
3042 part of the process of building a program. To compile a file in this
3043 checking mode, use the @code{-gnatc} switch.
3045 @node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3046 @anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{27}
3047 @section Source Dependencies
3050 A given object file clearly depends on the source file which is compiled
3051 to produce it. Here we are using “depends” in the sense of a typical
3052 @code{make} utility; in other words, an object file depends on a source
3053 file if changes to the source file require the object file to be
3054 recompiled.
3055 In addition to this basic dependency, a given object may depend on
3056 additional source files as follows:
3059 @itemize *
3061 @item 
3062 If a file being compiled @emph{with}s a unit @code{X}, the object file
3063 depends on the file containing the spec of unit @code{X}. This includes
3064 files that are @emph{with}ed implicitly either because they are parents
3065 of @emph{with}ed child units or they are run-time units required by the
3066 language constructs used in a particular unit.
3068 @item 
3069 If a file being compiled instantiates a library level generic unit, the
3070 object file depends on both the spec and body files for this generic
3071 unit.
3073 @item 
3074 If a file being compiled instantiates a generic unit defined within a
3075 package, the object file depends on the body file for the package as
3076 well as the spec file.
3077 @end itemize
3079 @geindex Inline
3081 @geindex -gnatn switch
3084 @itemize *
3086 @item 
3087 If a file being compiled contains a call to a subprogram for which
3088 pragma @code{Inline} applies and inlining is activated with the
3089 @code{-gnatn} switch, the object file depends on the file containing the
3090 body of this subprogram as well as on the file containing the spec. Note
3091 that for inlining to actually occur as a result of the use of this switch,
3092 it is necessary to compile in optimizing mode.
3094 @geindex -gnatN switch
3096 The use of @code{-gnatN} activates  inlining optimization
3097 that is performed by the front end of the compiler. This inlining does
3098 not require that the code generation be optimized. Like @code{-gnatn},
3099 the use of this switch generates additional dependencies.
3101 When using a gcc-based back end, then the use of
3102 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
3103 Historically front end inlining was more extensive than the gcc back end
3104 inlining, but that is no longer the case.
3106 @item 
3107 If an object file @code{O} depends on the proper body of a subunit through
3108 inlining or instantiation, it depends on the parent unit of the subunit.
3109 This means that any modification of the parent unit or one of its subunits
3110 affects the compilation of @code{O}.
3112 @item 
3113 The object file for a parent unit depends on all its subunit body files.
3115 @item 
3116 The previous two rules meant that for purposes of computing dependencies and
3117 recompilation, a body and all its subunits are treated as an indivisible whole.
3119 These rules are applied transitively: if unit @code{A} @emph{with}s
3120 unit @code{B}, whose elaboration calls an inlined procedure in package
3121 @code{C}, the object file for unit @code{A} will depend on the body of
3122 @code{C}, in file @code{c.adb}.
3124 The set of dependent files described by these rules includes all the
3125 files on which the unit is semantically dependent, as dictated by the
3126 Ada language standard. However, it is a superset of what the
3127 standard describes, because it includes generic, inline, and subunit
3128 dependencies.
3130 An object file must be recreated by recompiling the corresponding source
3131 file if any of the source files on which it depends are modified. For
3132 example, if the @code{make} utility is used to control compilation,
3133 the rule for an Ada object file must mention all the source files on
3134 which the object file depends, according to the above definition.
3135 The determination of the necessary
3136 recompilations is done automatically when one uses @code{gnatmake}.
3137 @end itemize
3139 @node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3140 @anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{66}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{28}
3141 @section The Ada Library Information Files
3144 @geindex Ada Library Information files
3146 @geindex ALI files
3148 Each compilation actually generates two output files. The first of these
3149 is the normal object file that has a @code{.o} extension. The second is a
3150 text file containing full dependency information. It has the same
3151 name as the source file, but an @code{.ali} extension.
3152 This file is known as the Ada Library Information (@code{ALI}) file.
3153 The following information is contained in the @code{ALI} file.
3156 @itemize *
3158 @item 
3159 Version information (indicates which version of GNAT was used to compile
3160 the unit(s) in question)
3162 @item 
3163 Main program information (including priority and time slice settings,
3164 as well as the wide character encoding used during compilation).
3166 @item 
3167 List of arguments used in the @code{gcc} command for the compilation
3169 @item 
3170 Attributes of the unit, including configuration pragmas used, an indication
3171 of whether the compilation was successful, exception model used etc.
3173 @item 
3174 A list of relevant restrictions applying to the unit (used for consistency)
3175 checking.
3177 @item 
3178 Categorization information (e.g., use of pragma @code{Pure}).
3180 @item 
3181 Information on all @emph{with}ed units, including presence of
3182 @code{Elaborate} or @code{Elaborate_All} pragmas.
3184 @item 
3185 Information from any @code{Linker_Options} pragmas used in the unit
3187 @item 
3188 Information on the use of @code{Body_Version} or @code{Version}
3189 attributes in the unit.
3191 @item 
3192 Dependency information. This is a list of files, together with
3193 time stamp and checksum information. These are files on which
3194 the unit depends in the sense that recompilation is required
3195 if any of these units are modified.
3197 @item 
3198 Cross-reference data. Contains information on all entities referenced
3199 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
3200 provide cross-reference information.
3201 @end itemize
3203 For a full detailed description of the format of the @code{ALI} file,
3204 see the source of the body of unit @code{Lib.Writ}, contained in file
3205 @code{lib-writ.adb} in the GNAT compiler sources.
3207 @node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3208 @anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{29}@anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{67}
3209 @section Binding an Ada Program
3212 When using languages such as C and C++, once the source files have been
3213 compiled the only remaining step in building an executable program
3214 is linking the object modules together. This means that it is possible to
3215 link an inconsistent version of a program, in which two units have
3216 included different versions of the same header.
3218 The rules of Ada do not permit such an inconsistent program to be built.
3219 For example, if two clients have different versions of the same package,
3220 it is illegal to build a program containing these two clients.
3221 These rules are enforced by the GNAT binder, which also determines an
3222 elaboration order consistent with the Ada rules.
3224 The GNAT binder is run after all the object files for a program have
3225 been created. It is given the name of the main program unit, and from
3226 this it determines the set of units required by the program, by reading the
3227 corresponding ALI files. It generates error messages if the program is
3228 inconsistent or if no valid order of elaboration exists.
3230 If no errors are detected, the binder produces a main program, in Ada by
3231 default, that contains calls to the elaboration procedures of those
3232 compilation unit that require them, followed by
3233 a call to the main program. This Ada program is compiled to generate the
3234 object file for the main program. The name of
3235 the Ada file is @code{b~xxx}.adb` (with the corresponding spec
3236 @code{b~xxx}.ads`) where @code{xxx} is the name of the
3237 main program unit.
3239 Finally, the linker is used to build the resulting executable program,
3240 using the object from the main program from the bind step as well as the
3241 object files for the Ada units of the program.
3243 @node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3244 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{2a}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{68}
3245 @section GNAT and Libraries
3248 @geindex Library building and using
3250 This section describes how to build and use libraries with GNAT, and also shows
3251 how to recompile the GNAT run-time library. You should be familiar with the
3252 Project Manager facility (see the @emph{GNAT_Project_Manager} chapter of the
3253 @emph{GPRbuild User’s Guide}) before reading this chapter.
3255 @menu
3256 * Introduction to Libraries in GNAT:: 
3257 * General Ada Libraries:: 
3258 * Stand-alone Ada Libraries:: 
3259 * Rebuilding the GNAT Run-Time Library:: 
3261 @end menu
3263 @node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3264 @anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{69}@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{6a}
3265 @subsection Introduction to Libraries in GNAT
3268 A library is, conceptually, a collection of objects which does not have its
3269 own main thread of execution, but rather provides certain services to the
3270 applications that use it. A library can be either statically linked with the
3271 application, in which case its code is directly included in the application,
3272 or, on platforms that support it, be dynamically linked, in which case
3273 its code is shared by all applications making use of this library.
3275 GNAT supports both types of libraries.
3276 In the static case, the compiled code can be provided in different ways. The
3277 simplest approach is to provide directly the set of objects resulting from
3278 compilation of the library source files. Alternatively, you can group the
3279 objects into an archive using whatever commands are provided by the operating
3280 system. For the latter case, the objects are grouped into a shared library.
3282 In the GNAT environment, a library has three types of components:
3285 @itemize *
3287 @item 
3288 Source files,
3290 @item 
3291 @code{ALI} files (see @ref{28,,The Ada Library Information Files}), and
3293 @item 
3294 Object files, an archive or a shared library.
3295 @end itemize
3297 A GNAT library may expose all its source files, which is useful for
3298 documentation purposes. Alternatively, it may expose only the units needed by
3299 an external user to make use of the library. That is to say, the specs
3300 reflecting the library services along with all the units needed to compile
3301 those specs, which can include generic bodies or any body implementing an
3302 inlined routine. In the case of @emph{stand-alone libraries} those exposed
3303 units are called @emph{interface units} (@ref{6b,,Stand-alone Ada Libraries}).
3305 All compilation units comprising an application, including those in a library,
3306 need to be elaborated in an order partially defined by Ada’s semantics. GNAT
3307 computes the elaboration order from the @code{ALI} files and this is why they
3308 constitute a mandatory part of GNAT libraries.
3309 @emph{Stand-alone libraries} are the exception to this rule because a specific
3310 library elaboration routine is produced independently of the application(s)
3311 using the library.
3313 @node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3314 @anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{6d}
3315 @subsection General Ada Libraries
3318 @menu
3319 * Building a library:: 
3320 * Installing a library:: 
3321 * Using a library:: 
3323 @end menu
3325 @node Building a library,Installing a library,,General Ada Libraries
3326 @anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{6e}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{6f}
3327 @subsubsection Building a library
3330 The easiest way to build a library is to use the Project Manager,
3331 which supports a special type of project called a @emph{Library Project}
3332 (see the @emph{Library Projects} section in the @emph{GNAT Project Manager}
3333 chapter of the @emph{GPRbuild User’s Guide}).
3335 A project is considered a library project, when two project-level attributes
3336 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
3337 control different aspects of library configuration, additional optional
3338 project-level attributes can be specified:
3341 @itemize *
3343 @item 
3345 @table @asis
3347 @item @code{Library_Kind}
3349 This attribute controls whether the library is to be static or dynamic
3350 @end table
3352 @item 
3354 @table @asis
3356 @item @code{Library_Version}
3358 This attribute specifies the library version; this value is used
3359 during dynamic linking of shared libraries to determine if the currently
3360 installed versions of the binaries are compatible.
3361 @end table
3363 @item 
3364 @code{Library_Options}
3366 @item 
3368 @table @asis
3370 @item @code{Library_GCC}
3372 These attributes specify additional low-level options to be used during
3373 library generation, and redefine the actual application used to generate
3374 library.
3375 @end table
3376 @end itemize
3378 The GNAT Project Manager takes full care of the library maintenance task,
3379 including recompilation of the source files for which objects do not exist
3380 or are not up to date, assembly of the library archive, and installation of
3381 the library (i.e., copying associated source, object and @code{ALI} files
3382 to the specified location).
3384 Here is a simple library project file:
3386 @example
3387 project My_Lib is
3388   for Source_Dirs use ("src1", "src2");
3389   for Object_Dir use "obj";
3390   for Library_Name use "mylib";
3391   for Library_Dir use "lib";
3392   for Library_Kind use "dynamic";
3393 end My_lib;
3394 @end example
3396 and the compilation command to build and install the library:
3398 @example
3399 $ gnatmake -Pmy_lib
3400 @end example
3402 It is not entirely trivial to perform manually all the steps required to
3403 produce a library. We recommend that you use the GNAT Project Manager
3404 for this task. In special cases where this is not desired, the necessary
3405 steps are discussed below.
3407 There are various possibilities for compiling the units that make up the
3408 library: for example with a Makefile (@ref{70,,Using the GNU make Utility}) or
3409 with a conventional script. For simple libraries, it is also possible to create
3410 a dummy main program which depends upon all the packages that comprise the
3411 interface of the library. This dummy main program can then be given to
3412 @code{gnatmake}, which will ensure that all necessary objects are built.
3414 After this task is accomplished, you should follow the standard procedure
3415 of the underlying operating system to produce the static or shared library.
3417 Here is an example of such a dummy program:
3419 @example
3420 with My_Lib.Service1;
3421 with My_Lib.Service2;
3422 with My_Lib.Service3;
3423 procedure My_Lib_Dummy is
3424 begin
3425    null;
3426 end;
3427 @end example
3429 Here are the generic commands that will build an archive or a shared library.
3431 @example
3432 # compiling the library
3433 $ gnatmake -c my_lib_dummy.adb
3435 # we don't need the dummy object itself
3436 $ rm my_lib_dummy.o my_lib_dummy.ali
3438 # create an archive with the remaining objects
3439 $ ar rc libmy_lib.a *.o
3440 # some systems may require "ranlib" to be run as well
3442 # or create a shared library
3443 $ gcc -shared -o libmy_lib.so *.o
3444 # some systems may require the code to have been compiled with -fPIC
3446 # remove the object files that are now in the library
3447 $ rm *.o
3449 # Make the ALI files read-only so that gnatmake will not try to
3450 # regenerate the objects that are in the library
3451 $ chmod -w *.ali
3452 @end example
3454 Please note that the library must have a name of the form @code{lib@emph{xxx}.a}
3455 or @code{lib@emph{xxx}.so} (or @code{lib@emph{xxx}.dll} on Windows) in order to
3456 be accessed by the directive @code{-l@emph{xxx}} at link time.
3458 @node Installing a library,Using a library,Building a library,General Ada Libraries
3459 @anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{72}
3460 @subsubsection Installing a library
3463 @geindex ADA_PROJECT_PATH
3465 @geindex GPR_PROJECT_PATH
3467 If you use project files, library installation is part of the library build
3468 process (see the @emph{Installing a Library with Project Files} section of the
3469 @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User’s Guide}).
3471 When project files are not an option, it is also possible, but not recommended,
3472 to install the library so that the sources needed to use the library are on the
3473 Ada source path and the ALI files & libraries be on the Ada Object path (see
3474 @ref{73,,Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
3475 administrator can place general-purpose libraries in the default compiler
3476 paths, by specifying the libraries’ location in the configuration files
3477 @code{ada_source_path} and @code{ada_object_path}. These configuration files
3478 must be located in the GNAT installation tree at the same place as the gcc spec
3479 file. The location of the gcc spec file can be determined as follows:
3481 @example
3482 $ gcc -v
3483 @end example
3485 The configuration files mentioned above have a simple format: each line
3486 must contain one unique directory name.
3487 Those names are added to the corresponding path
3488 in their order of appearance in the file. The names can be either absolute
3489 or relative; in the latter case, they are relative to where theses files
3490 are located.
3492 The files @code{ada_source_path} and @code{ada_object_path} might not be
3493 present in a
3494 GNAT installation, in which case, GNAT will look for its run-time library in
3495 the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3496 objects and @code{ALI} files). When the files exist, the compiler does not
3497 look in @code{adainclude} and @code{adalib}, and thus the
3498 @code{ada_source_path} file
3499 must contain the location for the GNAT run-time sources (which can simply
3500 be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3501 contain the location for the GNAT run-time objects (which can simply
3502 be @code{adalib}).
3504 You can also specify a new default path to the run-time library at compilation
3505 time with the switch @code{--RTS=rts-path}. You can thus choose / change
3506 the run-time library you want your program to be compiled with. This switch is
3507 recognized by @code{gcc}, @code{gnatmake}, @code{gnatbind},
3508 @code{gnatls}, @code{gnatfind} and @code{gnatxref}.
3510 It is possible to install a library before or after the standard GNAT
3511 library, by reordering the lines in the configuration files. In general, a
3512 library must be installed before the GNAT library if it redefines
3513 any part of it.
3515 @node Using a library,,Installing a library,General Ada Libraries
3516 @anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{74}@anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{75}
3517 @subsubsection Using a library
3520 Once again, the project facility greatly simplifies the use of
3521 libraries. In this context, using a library is just a matter of adding a
3522 @emph{with} clause in the user project. For instance, to make use of the
3523 library @code{My_Lib} shown in examples in earlier sections, you can
3524 write:
3526 @example
3527 with "my_lib";
3528 project My_Proj is
3529   ...
3530 end My_Proj;
3531 @end example
3533 Even if you have a third-party, non-Ada library, you can still use GNAT’s
3534 Project Manager facility to provide a wrapper for it. For example, the
3535 following project, when @emph{with}ed by your main project, will link with the
3536 third-party library @code{liba.a}:
3538 @example
3539 project Liba is
3540    for Externally_Built use "true";
3541    for Source_Files use ();
3542    for Library_Dir use "lib";
3543    for Library_Name use "a";
3544    for Library_Kind use "static";
3545 end Liba;
3546 @end example
3548 This is an alternative to the use of @code{pragma Linker_Options}. It is
3549 especially interesting in the context of systems with several interdependent
3550 static libraries where finding a proper linker order is not easy and best be
3551 left to the tools having visibility over project dependence information.
3553 In order to use an Ada library manually, you need to make sure that this
3554 library is on both your source and object path
3555 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}
3556 and @ref{76,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3557 in an archive or a shared library, you need to specify the desired
3558 library at link time.
3560 For example, you can use the library @code{mylib} installed in
3561 @code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3563 @example
3564 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3565   -largs -lmy_lib
3566 @end example
3568 This can be expressed more simply:
3570 @example
3571 $ gnatmake my_appl
3572 @end example
3574 when the following conditions are met:
3577 @itemize *
3579 @item 
3580 @code{/dir/my_lib_src} has been added by the user to the environment
3581 variable 
3582 @geindex ADA_INCLUDE_PATH
3583 @geindex environment variable; ADA_INCLUDE_PATH
3584 @code{ADA_INCLUDE_PATH}, or by the administrator to the file
3585 @code{ada_source_path}
3587 @item 
3588 @code{/dir/my_lib_obj} has been added by the user to the environment
3589 variable 
3590 @geindex ADA_OBJECTS_PATH
3591 @geindex environment variable; ADA_OBJECTS_PATH
3592 @code{ADA_OBJECTS_PATH}, or by the administrator to the file
3593 @code{ada_object_path}
3595 @item 
3596 a pragma @code{Linker_Options} has been added to one of the sources.
3597 For example:
3599 @example
3600 pragma Linker_Options ("-lmy_lib");
3601 @end example
3602 @end itemize
3604 Note that you may also load a library dynamically at
3605 run time given its filename, as illustrated in the GNAT @code{plugins} example
3606 in the directory @code{share/examples/gnat/plugins} within the GNAT
3607 install area.
3609 @node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3610 @anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{6b}
3611 @subsection Stand-alone Ada Libraries
3614 @geindex Stand-alone libraries
3616 @menu
3617 * Introduction to Stand-alone Libraries:: 
3618 * Building a Stand-alone Library:: 
3619 * Creating a Stand-alone Library to be used in a non-Ada context:: 
3620 * Restrictions in Stand-alone Libraries:: 
3622 @end menu
3624 @node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3625 @anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{78}@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{79}
3626 @subsubsection Introduction to Stand-alone Libraries
3629 A Stand-alone Library (abbreviated ‘SAL’) is a library that contains the
3630 necessary code to
3631 elaborate the Ada units that are included in the library. In contrast with
3632 an ordinary library, which consists of all sources, objects and @code{ALI}
3633 files of the
3634 library, a SAL may specify a restricted subset of compilation units
3635 to serve as a library interface. In this case, the fully
3636 self-sufficient set of files will normally consist of an objects
3637 archive, the sources of interface units’ specs, and the @code{ALI}
3638 files of interface units.
3639 If an interface spec contains a generic unit or an inlined subprogram,
3640 the body’s
3641 source must also be provided; if the units that must be provided in the source
3642 form depend on other units, the source and @code{ALI} files of those must
3643 also be provided.
3645 The main purpose of a SAL is to minimize the recompilation overhead of client
3646 applications when a new version of the library is installed. Specifically,
3647 if the interface sources have not changed, client applications do not need to
3648 be recompiled. If, furthermore, a SAL is provided in the shared form and its
3649 version, controlled by @code{Library_Version} attribute, is not changed,
3650 then the clients do not need to be relinked.
3652 SALs also allow the library providers to minimize the amount of library source
3653 text exposed to the clients.  Such ‘information hiding’ might be useful or
3654 necessary for various reasons.
3656 Stand-alone libraries are also well suited to be used in an executable whose
3657 main routine is not written in Ada.
3659 @node Building a Stand-alone Library,Creating a Stand-alone Library to be used in a non-Ada context,Introduction to Stand-alone Libraries,Stand-alone Ada Libraries
3660 @anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{7a}@anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{7b}
3661 @subsubsection Building a Stand-alone Library
3664 GNAT’s Project facility provides a simple way of building and installing
3665 stand-alone libraries; see the @emph{Stand-alone Library Projects} section
3666 in the @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User’s Guide}.
3667 To be a Stand-alone Library Project, in addition to the two attributes
3668 that make a project a Library Project (@code{Library_Name} and
3669 @code{Library_Dir}; see the @emph{Library Projects} section in the
3670 @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User’s Guide}),
3671 the attribute @code{Library_Interface} must be defined.  For example:
3673 @example
3674 for Library_Dir use "lib_dir";
3675 for Library_Name use "dummy";
3676 for Library_Interface use ("int1", "int1.child");
3677 @end example
3679 Attribute @code{Library_Interface} has a non-empty string list value,
3680 each string in the list designating a unit contained in an immediate source
3681 of the project file.
3683 When a Stand-alone Library is built, first the binder is invoked to build
3684 a package whose name depends on the library name
3685 (@code{b~dummy.ads/b} in the example above).
3686 This binder-generated package includes initialization and
3687 finalization procedures whose
3688 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
3689 in the example
3690 above). The object corresponding to this package is included in the library.
3692 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
3693 calling of these procedures if a static SAL is built, or if a shared SAL
3694 is built
3695 with the project-level attribute @code{Library_Auto_Init} set to
3696 @code{"false"}.
3698 For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
3699 (those that are listed in attribute @code{Library_Interface}) are copied to
3700 the Library Directory. As a consequence, only the Interface Units may be
3701 imported from Ada units outside of the library. If other units are imported,
3702 the binding phase will fail.
3704 It is also possible to build an encapsulated library where not only
3705 the code to elaborate and finalize the library is embedded but also
3706 ensuring that the library is linked only against static
3707 libraries. So an encapsulated library only depends on system
3708 libraries, all other code, including the GNAT runtime, is embedded. To
3709 build an encapsulated library the attribute
3710 @code{Library_Standalone} must be set to @code{encapsulated}:
3712 @example
3713 for Library_Dir use "lib_dir";
3714 for Library_Name use "dummy";
3715 for Library_Kind use "dynamic";
3716 for Library_Interface use ("int1", "int1.child");
3717 for Library_Standalone use "encapsulated";
3718 @end example
3720 The default value for this attribute is @code{standard} in which case
3721 a stand-alone library is built.
3723 The attribute @code{Library_Src_Dir} may be specified for a
3724 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
3725 single string value. Its value must be the path (absolute or relative to the
3726 project directory) of an existing directory. This directory cannot be the
3727 object directory or one of the source directories, but it can be the same as
3728 the library directory. The sources of the Interface
3729 Units of the library that are needed by an Ada client of the library will be
3730 copied to the designated directory, called the Interface Copy directory.
3731 These sources include the specs of the Interface Units, but they may also
3732 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
3733 are used, or when there is a generic unit in the spec. Before the sources
3734 are copied to the Interface Copy directory, an attempt is made to delete all
3735 files in the Interface Copy directory.
3737 Building stand-alone libraries by hand is somewhat tedious, but for those
3738 occasions when it is necessary here are the steps that you need to perform:
3741 @itemize *
3743 @item 
3744 Compile all library sources.
3746 @item 
3747 Invoke the binder with the switch @code{-n} (No Ada main program),
3748 with all the @code{ALI} files of the interfaces, and
3749 with the switch @code{-L} to give specific names to the @code{init}
3750 and @code{final} procedures.  For example:
3752 @example
3753 $ gnatbind -n int1.ali int2.ali -Lsal1
3754 @end example
3756 @item 
3757 Compile the binder generated file:
3759 @example
3760 $ gcc -c b~int2.adb
3761 @end example
3763 @item 
3764 Link the dynamic library with all the necessary object files,
3765 indicating to the linker the names of the @code{init} (and possibly
3766 @code{final}) procedures for automatic initialization (and finalization).
3767 The built library should be placed in a directory different from
3768 the object directory.
3770 @item 
3771 Copy the @code{ALI} files of the interface to the library directory,
3772 add in this copy an indication that it is an interface to a SAL
3773 (i.e., add a word @code{SL} on the line in the @code{ALI} file that starts
3774 with letter ‘P’) and make the modified copy of the @code{ALI} file
3775 read-only.
3776 @end itemize
3778 Using SALs is not different from using other libraries
3779 (see @ref{75,,Using a library}).
3781 @node Creating a Stand-alone Library to be used in a non-Ada context,Restrictions in Stand-alone Libraries,Building a Stand-alone Library,Stand-alone Ada Libraries
3782 @anchor{gnat_ugn/the_gnat_compilation_model creating-a-stand-alone-library-to-be-used-in-a-non-ada-context}@anchor{7c}@anchor{gnat_ugn/the_gnat_compilation_model id44}@anchor{7d}
3783 @subsubsection Creating a Stand-alone Library to be used in a non-Ada context
3786 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
3787 a non-Ada context.
3789 The only extra step required is to ensure that library interface subprograms
3790 are compatible with the main program, by means of @code{pragma Export}
3791 or @code{pragma Convention}.
3793 Here is an example of simple library interface for use with C main program:
3795 @example
3796 package My_Package is
3798    procedure Do_Something;
3799    pragma Export (C, Do_Something, "do_something");
3801    procedure Do_Something_Else;
3802    pragma Export (C, Do_Something_Else, "do_something_else");
3804 end My_Package;
3805 @end example
3807 On the foreign language side, you must provide a ‘foreign’ view of the
3808 library interface; remember that it should contain elaboration routines in
3809 addition to interface subprograms.
3811 The example below shows the content of @code{mylib_interface.h} (note
3812 that there is no rule for the naming of this file, any name can be used)
3814 @example
3815 /* the library elaboration procedure */
3816 extern void mylibinit (void);
3818 /* the library finalization procedure */
3819 extern void mylibfinal (void);
3821 /* the interface exported by the library */
3822 extern void do_something (void);
3823 extern void do_something_else (void);
3824 @end example
3826 Libraries built as explained above can be used from any program, provided
3827 that the elaboration procedures (named @code{mylibinit} in the previous
3828 example) are called before the library services are used. Any number of
3829 libraries can be used simultaneously, as long as the elaboration
3830 procedure of each library is called.
3832 Below is an example of a C program that uses the @code{mylib} library.
3834 @example
3835 #include "mylib_interface.h"
3838 main (void)
3840    /* First, elaborate the library before using it */
3841    mylibinit ();
3843    /* Main program, using the library exported entities */
3844    do_something ();
3845    do_something_else ();
3847    /* Library finalization at the end of the program */
3848    mylibfinal ();
3849    return 0;
3851 @end example
3853 Note that invoking any library finalization procedure generated by
3854 @code{gnatbind} shuts down the Ada run-time environment.
3855 Consequently, the
3856 finalization of all Ada libraries must be performed at the end of the program.
3857 No call to these libraries or to the Ada run-time library should be made
3858 after the finalization phase.
3860 Note also that special care must be taken with multi-tasks
3861 applications. The initialization and finalization routines are not
3862 protected against concurrent access. If such requirement is needed it
3863 must be ensured at the application level using a specific operating
3864 system services like a mutex or a critical-section.
3866 @node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
3867 @anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{7e}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{7f}
3868 @subsubsection Restrictions in Stand-alone Libraries
3871 The pragmas listed below should be used with caution inside libraries,
3872 as they can create incompatibilities with other Ada libraries:
3875 @itemize *
3877 @item 
3878 pragma @code{Locking_Policy}
3880 @item 
3881 pragma @code{Partition_Elaboration_Policy}
3883 @item 
3884 pragma @code{Queuing_Policy}
3886 @item 
3887 pragma @code{Task_Dispatching_Policy}
3889 @item 
3890 pragma @code{Unreserve_All_Interrupts}
3891 @end itemize
3893 When using a library that contains such pragmas, the user must make sure
3894 that all libraries use the same pragmas with the same values. Otherwise,
3895 @code{Program_Error} will
3896 be raised during the elaboration of the conflicting
3897 libraries. The usage of these pragmas and its consequences for the user
3898 should therefore be well documented.
3900 Similarly, the traceback in the exception occurrence mechanism should be
3901 enabled or disabled in a consistent manner across all libraries.
3902 Otherwise, Program_Error will be raised during the elaboration of the
3903 conflicting libraries.
3905 If the @code{Version} or @code{Body_Version}
3906 attributes are used inside a library, then you need to
3907 perform a @code{gnatbind} step that specifies all @code{ALI} files in all
3908 libraries, so that version identifiers can be properly computed.
3909 In practice these attributes are rarely used, so this is unlikely
3910 to be a consideration.
3912 @node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
3913 @anchor{gnat_ugn/the_gnat_compilation_model id46}@anchor{80}@anchor{gnat_ugn/the_gnat_compilation_model rebuilding-the-gnat-run-time-library}@anchor{81}
3914 @subsection Rebuilding the GNAT Run-Time Library
3917 @geindex GNAT Run-Time Library
3918 @geindex rebuilding
3920 @geindex Building the GNAT Run-Time Library
3922 @geindex Rebuilding the GNAT Run-Time Library
3924 @geindex Run-Time Library
3925 @geindex rebuilding
3927 It may be useful to recompile the GNAT library in various debugging or
3928 experimentation contexts. A project file called
3929 @code{libada.gpr} is provided to that effect and can be found in
3930 the directory containing the GNAT library. The location of this
3931 directory depends on the way the GNAT environment has been installed and can
3932 be determined by means of the command:
3934 @example
3935 $ gnatls -v
3936 @end example
3938 The last entry in the source search path usually contains the
3939 gnat library (the @code{adainclude} directory). This project file contains its
3940 own documentation and in particular the set of instructions needed to rebuild a
3941 new library and to use it.
3943 Note that rebuilding the GNAT Run-Time is only recommended for temporary
3944 experiments or debugging, and is not supported.
3946 @geindex Conditional compilation
3948 @node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
3949 @anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{2b}@anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{82}
3950 @section Conditional Compilation
3953 This section presents some guidelines for modeling conditional compilation in Ada and describes the
3954 gnatprep preprocessor utility.
3956 @geindex Conditional compilation
3958 @menu
3959 * Modeling Conditional Compilation in Ada:: 
3960 * Preprocessing with gnatprep:: 
3961 * Integrated Preprocessing:: 
3963 @end menu
3965 @node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
3966 @anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{83}@anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{84}
3967 @subsection Modeling Conditional Compilation in Ada
3970 It is often necessary to arrange for a single source program
3971 to serve multiple purposes, where it is compiled in different
3972 ways to achieve these different goals. Some examples of the
3973 need for this feature are
3976 @itemize *
3978 @item 
3979 Adapting a program to a different hardware environment
3981 @item 
3982 Adapting a program to a different target architecture
3984 @item 
3985 Turning debugging features on and off
3987 @item 
3988 Arranging for a program to compile with different compilers
3989 @end itemize
3991 In C, or C++, the typical approach would be to use the preprocessor
3992 that is defined as part of the language. The Ada language does not
3993 contain such a feature. This is not an oversight, but rather a very
3994 deliberate design decision, based on the experience that overuse of
3995 the preprocessing features in C and C++ can result in programs that
3996 are extremely difficult to maintain. For example, if we have ten
3997 switches that can be on or off, this means that there are a thousand
3998 separate programs, any one of which might not even be syntactically
3999 correct, and even if syntactically correct, the resulting program
4000 might not work correctly. Testing all combinations can quickly become
4001 impossible.
4003 Nevertheless, the need to tailor programs certainly exists, and in
4004 this section we will discuss how this can
4005 be achieved using Ada in general, and GNAT in particular.
4007 @menu
4008 * Use of Boolean Constants:: 
4009 * Debugging - A Special Case:: 
4010 * Conditionalizing Declarations:: 
4011 * Use of Alternative Implementations:: 
4012 * Preprocessing:: 
4014 @end menu
4016 @node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4017 @anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{85}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{86}
4018 @subsubsection Use of Boolean Constants
4021 In the case where the difference is simply which code
4022 sequence is executed, the cleanest solution is to use Boolean
4023 constants to control which code is executed.
4025 @example
4026 FP_Initialize_Required : constant Boolean := True;
4028 if FP_Initialize_Required then
4030 end if;
4031 @end example
4033 Not only will the code inside the @code{if} statement not be executed if
4034 the constant Boolean is @code{False}, but it will also be completely
4035 deleted from the program.
4036 However, the code is only deleted after the @code{if} statement
4037 has been checked for syntactic and semantic correctness.
4038 (In contrast, with preprocessors the code is deleted before the
4039 compiler ever gets to see it, so it is not checked until the switch
4040 is turned on.)
4042 @geindex Preprocessors (contrasted with conditional compilation)
4044 Typically the Boolean constants will be in a separate package,
4045 something like:
4047 @example
4048 package Config is
4049    FP_Initialize_Required : constant Boolean := True;
4050    Reset_Available        : constant Boolean := False;
4051    ...
4052 end Config;
4053 @end example
4055 The @code{Config} package exists in multiple forms for the various targets,
4056 with an appropriate script selecting the version of @code{Config} needed.
4057 Then any other unit requiring conditional compilation can do a @emph{with}
4058 of @code{Config} to make the constants visible.
4060 @node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4061 @anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{87}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{88}
4062 @subsubsection Debugging - A Special Case
4065 A common use of conditional code is to execute statements (for example
4066 dynamic checks, or output of intermediate results) under control of a
4067 debug switch, so that the debugging behavior can be turned on and off.
4068 This can be done using a Boolean constant to control whether the code
4069 is active:
4071 @example
4072 if Debugging then
4073    Put_Line ("got to the first stage!");
4074 end if;
4075 @end example
4079 @example
4080 if Debugging and then Temperature > 999.0 then
4081    raise Temperature_Crazy;
4082 end if;
4083 @end example
4085 @geindex pragma Assert
4087 Since this is a common case, there are special features to deal with
4088 this in a convenient manner. For the case of tests, Ada 2005 has added
4089 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
4090 on the @code{Assert} pragma that has always been available in GNAT, so this
4091 feature may be used with GNAT even if you are not using Ada 2005 features.
4092 The use of pragma @code{Assert} is described in the
4093 @cite{GNAT_Reference_Manual}, but as an
4094 example, the last test could be written:
4096 @example
4097 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4098 @end example
4100 or simply
4102 @example
4103 pragma Assert (Temperature <= 999.0);
4104 @end example
4106 In both cases, if assertions are active and the temperature is excessive,
4107 the exception @code{Assert_Failure} will be raised, with the given string in
4108 the first case or a string indicating the location of the pragma in the second
4109 case used as the exception message.
4111 @geindex pragma Assertion_Policy
4113 You can turn assertions on and off by using the @code{Assertion_Policy}
4114 pragma.
4116 @geindex -gnata switch
4118 This is an Ada 2005 pragma which is implemented in all modes by
4119 GNAT. Alternatively, you can use the @code{-gnata} switch
4120 to enable assertions from the command line, which applies to
4121 all versions of Ada.
4123 @geindex pragma Debug
4125 For the example above with the @code{Put_Line}, the GNAT-specific pragma
4126 @code{Debug} can be used:
4128 @example
4129 pragma Debug (Put_Line ("got to the first stage!"));
4130 @end example
4132 If debug pragmas are enabled, the argument, which must be of the form of
4133 a procedure call, is executed (in this case, @code{Put_Line} will be called).
4134 Only one call can be present, but of course a special debugging procedure
4135 containing any code you like can be included in the program and then
4136 called in a pragma @code{Debug} argument as needed.
4138 One advantage of pragma @code{Debug} over the @code{if Debugging then}
4139 construct is that pragma @code{Debug} can appear in declarative contexts,
4140 such as at the very beginning of a procedure, before local declarations have
4141 been elaborated.
4143 @geindex pragma Debug_Policy
4145 Debug pragmas are enabled using either the @code{-gnata} switch that also
4146 controls assertions, or with a separate Debug_Policy pragma.
4148 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4149 in Ada 95 and Ada 83 programs as well), and is analogous to
4150 pragma @code{Assertion_Policy} to control assertions.
4152 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
4153 and thus they can appear in @code{gnat.adc} if you are not using a
4154 project file, or in the file designated to contain configuration pragmas
4155 in a project file.
4156 They then apply to all subsequent compilations. In practice the use of
4157 the @code{-gnata} switch is often the most convenient method of controlling
4158 the status of these pragmas.
4160 Note that a pragma is not a statement, so in contexts where a statement
4161 sequence is required, you can’t just write a pragma on its own. You have
4162 to add a @code{null} statement.
4164 @example
4165 if ... then
4166    ... -- some statements
4167 else
4168    pragma Assert (Num_Cases < 10);
4169    null;
4170 end if;
4171 @end example
4173 @node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4174 @anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{89}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{8a}
4175 @subsubsection Conditionalizing Declarations
4178 In some cases it may be necessary to conditionalize declarations to meet
4179 different requirements. For example we might want a bit string whose length
4180 is set to meet some hardware message requirement.
4182 This may be possible using declare blocks controlled
4183 by conditional constants:
4185 @example
4186 if Small_Machine then
4187    declare
4188       X : Bit_String (1 .. 10);
4189    begin
4190       ...
4191    end;
4192 else
4193    declare
4194       X : Large_Bit_String (1 .. 1000);
4195    begin
4196       ...
4197    end;
4198 end if;
4199 @end example
4201 Note that in this approach, both declarations are analyzed by the
4202 compiler so this can only be used where both declarations are legal,
4203 even though one of them will not be used.
4205 Another approach is to define integer constants, e.g., @code{Bits_Per_Word},
4206 or Boolean constants, e.g., @code{Little_Endian}, and then write declarations
4207 that are parameterized by these constants. For example
4209 @example
4210 for Rec use
4211   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4212 end record;
4213 @end example
4215 If @code{Bits_Per_Word} is set to 32, this generates either
4217 @example
4218 for Rec use
4219   Field1 at 0 range 0 .. 32;
4220 end record;
4221 @end example
4223 for the big endian case, or
4225 @example
4226 for Rec use record
4227     Field1 at 0 range 10 .. 32;
4228 end record;
4229 @end example
4231 for the little endian case. Since a powerful subset of Ada expression
4232 notation is usable for creating static constants, clever use of this
4233 feature can often solve quite difficult problems in conditionalizing
4234 compilation (note incidentally that in Ada 95, the little endian
4235 constant was introduced as @code{System.Default_Bit_Order}, so you do not
4236 need to define this one yourself).
4238 @node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4239 @anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{8b}@anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{8c}
4240 @subsubsection Use of Alternative Implementations
4243 In some cases, none of the approaches described above are adequate. This
4244 can occur for example if the set of declarations required is radically
4245 different for two different configurations.
4247 In this situation, the official Ada way of dealing with conditionalizing
4248 such code is to write separate units for the different cases. As long as
4249 this does not result in excessive duplication of code, this can be done
4250 without creating maintenance problems. The approach is to share common
4251 code as far as possible, and then isolate the code and declarations
4252 that are different. Subunits are often a convenient method for breaking
4253 out a piece of a unit that is to be conditionalized, with separate files
4254 for different versions of the subunit for different targets, where the
4255 build script selects the right one to give to the compiler.
4257 @geindex Subunits (and conditional compilation)
4259 As an example, consider a situation where a new feature in Ada 2005
4260 allows something to be done in a really nice way. But your code must be able
4261 to compile with an Ada 95 compiler. Conceptually you want to say:
4263 @example
4264 if Ada_2005 then
4265    ... neat Ada 2005 code
4266 else
4267    ... not quite as neat Ada 95 code
4268 end if;
4269 @end example
4271 where @code{Ada_2005} is a Boolean constant.
4273 But this won’t work when @code{Ada_2005} is set to @code{False},
4274 since the @code{then} clause will be illegal for an Ada 95 compiler.
4275 (Recall that although such unreachable code would eventually be deleted
4276 by the compiler, it still needs to be legal.  If it uses features
4277 introduced in Ada 2005, it will be illegal in Ada 95.)
4279 So instead we write
4281 @example
4282 procedure Insert is separate;
4283 @end example
4285 Then we have two files for the subunit @code{Insert}, with the two sets of
4286 code.
4287 If the package containing this is called @code{File_Queries}, then we might
4288 have two files
4291 @itemize *
4293 @item 
4294 @code{file_queries-insert-2005.adb}
4296 @item 
4297 @code{file_queries-insert-95.adb}
4298 @end itemize
4300 and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4302 This can also be done with project files’ naming schemes. For example:
4304 @example
4305 for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4306 @end example
4308 Note also that with project files it is desirable to use a different extension
4309 than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4310 conflict may arise through another commonly used feature: to declare as part
4311 of the project a set of directories containing all the sources obeying the
4312 default naming scheme.
4314 The use of alternative units is certainly feasible in all situations,
4315 and for example the Ada part of the GNAT run-time is conditionalized
4316 based on the target architecture using this approach. As a specific example,
4317 consider the implementation of the AST feature in VMS. There is one
4318 spec: @code{s-asthan.ads} which is the same for all architectures, and three
4319 bodies:
4322 @itemize *
4324 @item 
4326 @table @asis
4328 @item @code{s-asthan.adb}
4330 used for all non-VMS operating systems
4331 @end table
4333 @item 
4335 @table @asis
4337 @item @code{s-asthan-vms-alpha.adb}
4339 used for VMS on the Alpha
4340 @end table
4342 @item 
4344 @table @asis
4346 @item @code{s-asthan-vms-ia64.adb}
4348 used for VMS on the ia64
4349 @end table
4350 @end itemize
4352 The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4353 this operating system feature is not available, and the two remaining
4354 versions interface with the corresponding versions of VMS to provide
4355 VMS-compatible AST handling. The GNAT build script knows the architecture
4356 and operating system, and automatically selects the right version,
4357 renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4359 Another style for arranging alternative implementations is through Ada’s
4360 access-to-subprogram facility.
4361 In case some functionality is to be conditionally included,
4362 you can declare an access-to-procedure variable @code{Ref} that is initialized
4363 to designate a ‘do nothing’ procedure, and then invoke @code{Ref.all}
4364 when appropriate.
4365 In some library package, set @code{Ref} to @code{Proc'Access} for some
4366 procedure @code{Proc} that performs the relevant processing.
4367 The initialization only occurs if the library package is included in the
4368 program.
4369 The same idea can also be implemented using tagged types and dispatching
4370 calls.
4372 @node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4373 @anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{8d}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{8e}
4374 @subsubsection Preprocessing
4377 @geindex Preprocessing
4379 Although it is quite possible to conditionalize code without the use of
4380 C-style preprocessing, as described earlier in this section, it is
4381 nevertheless convenient in some cases to use the C approach. Moreover,
4382 older Ada compilers have often provided some preprocessing capability,
4383 so legacy code may depend on this approach, even though it is not
4384 standard.
4386 To accommodate such use, GNAT provides a preprocessor (modeled to a large
4387 extent on the various preprocessors that have been used
4388 with legacy code on other compilers, to enable easier transition).
4390 @geindex gnatprep
4392 The preprocessor may be used in two separate modes. It can be used quite
4393 separately from the compiler, to generate a separate output source file
4394 that is then fed to the compiler as a separate step. This is the
4395 @code{gnatprep} utility, whose use is fully described in
4396 @ref{8f,,Preprocessing with gnatprep}.
4398 The preprocessing language allows such constructs as
4400 @example
4401 #if DEBUG or else (PRIORITY > 4) then
4402    sequence of declarations
4403 #else
4404    completely different sequence of declarations
4405 #end if;
4406 @end example
4408 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
4409 defined either on the command line or in a separate file.
4411 The other way of running the preprocessor is even closer to the C style and
4412 often more convenient. In this approach the preprocessing is integrated into
4413 the compilation process. The compiler is given the preprocessor input which
4414 includes @code{#if} lines etc, and then the compiler carries out the
4415 preprocessing internally and processes the resulting output.
4416 For more details on this approach, see @ref{90,,Integrated Preprocessing}.
4418 @node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4419 @anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{91}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{8f}
4420 @subsection Preprocessing with @code{gnatprep}
4423 @geindex gnatprep
4425 @geindex Preprocessing (gnatprep)
4427 This section discusses how to use GNAT’s @code{gnatprep} utility for simple
4428 preprocessing.
4429 Although designed for use with GNAT, @code{gnatprep} does not depend on any
4430 special GNAT features.
4431 For further discussion of conditional compilation in general, see
4432 @ref{2b,,Conditional Compilation}.
4434 @menu
4435 * Preprocessing Symbols:: 
4436 * Using gnatprep:: 
4437 * Switches for gnatprep:: 
4438 * Form of Definitions File:: 
4439 * Form of Input Text for gnatprep:: 
4441 @end menu
4443 @node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4444 @anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{92}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{93}
4445 @subsubsection Preprocessing Symbols
4448 Preprocessing symbols are defined in @emph{definition files} and referenced in the
4449 sources to be preprocessed. A preprocessing symbol is an identifier, following
4450 normal Ada (case-insensitive) rules for its syntax, with the restriction that
4451 all characters need to be in the ASCII set (no accented letters).
4453 @node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4454 @anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{94}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{95}
4455 @subsubsection Using @code{gnatprep}
4458 To call @code{gnatprep} use:
4460 @example
4461 $ gnatprep [ switches ] infile outfile [ deffile ]
4462 @end example
4464 where
4467 @itemize *
4469 @item 
4471 @table @asis
4473 @item @emph{switches}
4475 is an optional sequence of switches as described in the next section.
4476 @end table
4478 @item 
4480 @table @asis
4482 @item @emph{infile}
4484 is the full name of the input file, which is an Ada source
4485 file containing preprocessor directives.
4486 @end table
4488 @item 
4490 @table @asis
4492 @item @emph{outfile}
4494 is the full name of the output file, which is an Ada source
4495 in standard Ada form. When used with GNAT, this file name will
4496 normally have an @code{ads} or @code{adb} suffix.
4497 @end table
4499 @item 
4501 @table @asis
4503 @item @code{deffile}
4505 is the full name of a text file containing definitions of
4506 preprocessing symbols to be referenced by the preprocessor. This argument is
4507 optional, and can be replaced by the use of the @code{-D} switch.
4508 @end table
4509 @end itemize
4511 @node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4512 @anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{96}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{97}
4513 @subsubsection Switches for @code{gnatprep}
4516 @geindex --version (gnatprep)
4519 @table @asis
4521 @item @code{--version}
4523 Display Copyright and version, then exit disregarding all other options.
4524 @end table
4526 @geindex --help (gnatprep)
4529 @table @asis
4531 @item @code{--help}
4533 If @code{--version} was not used, display usage and then exit disregarding
4534 all other options.
4535 @end table
4537 @geindex -b (gnatprep)
4540 @table @asis
4542 @item @code{-b}
4544 Causes both preprocessor lines and the lines deleted by
4545 preprocessing to be replaced by blank lines in the output source file,
4546 preserving line numbers in the output file.
4547 @end table
4549 @geindex -c (gnatprep)
4552 @table @asis
4554 @item @code{-c}
4556 Causes both preprocessor lines and the lines deleted
4557 by preprocessing to be retained in the output source as comments marked
4558 with the special string @code{"--! "}. This option will result in line numbers
4559 being preserved in the output file.
4560 @end table
4562 @geindex -C (gnatprep)
4565 @table @asis
4567 @item @code{-C}
4569 Causes comments to be scanned. Normally comments are ignored by gnatprep.
4570 If this option is specified, then comments are scanned and any $symbol
4571 substitutions performed as in program text. This is particularly useful
4572 when structured comments are used (e.g., for programs written in a
4573 pre-2014 version of the SPARK Ada subset). Note that this switch is not
4574 available when  doing integrated preprocessing (it would be useless in
4575 this context since comments are ignored by the compiler in any case).
4576 @end table
4578 @geindex -D (gnatprep)
4581 @table @asis
4583 @item @code{-D@emph{symbol}[=@emph{value}]}
4585 Defines a new preprocessing symbol with the specified value. If no value is given
4586 on the command line, then symbol is considered to be @code{True}. This switch
4587 can be used in place of a definition file.
4588 @end table
4590 @geindex -r (gnatprep)
4593 @table @asis
4595 @item @code{-r}
4597 Causes a @code{Source_Reference} pragma to be generated that
4598 references the original input file, so that error messages will use
4599 the file name of this original file. The use of this switch implies
4600 that preprocessor lines are not to be removed from the file, so its
4601 use will force @code{-b} mode if @code{-c}
4602 has not been specified explicitly.
4604 Note that if the file to be preprocessed contains multiple units, then
4605 it will be necessary to @code{gnatchop} the output file from
4606 @code{gnatprep}. If a @code{Source_Reference} pragma is present
4607 in the preprocessed file, it will be respected by
4608 @code{gnatchop -r}
4609 so that the final chopped files will correctly refer to the original
4610 input source file for @code{gnatprep}.
4611 @end table
4613 @geindex -s (gnatprep)
4616 @table @asis
4618 @item @code{-s}
4620 Causes a sorted list of symbol names and values to be
4621 listed on the standard output file.
4622 @end table
4624 @geindex -T (gnatprep)
4627 @table @asis
4629 @item @code{-T}
4631 Use LF as line terminators when writing files. By default the line terminator
4632 of the host (LF under unix, CR/LF under Windows) is used.
4633 @end table
4635 @geindex -u (gnatprep)
4638 @table @asis
4640 @item @code{-u}
4642 Causes undefined symbols to be treated as having the value FALSE in the context
4643 of a preprocessor test. In the absence of this option, an undefined symbol in
4644 a @code{#if} or @code{#elsif} test will be treated as an error.
4645 @end table
4647 @geindex -v (gnatprep)
4650 @table @asis
4652 @item @code{-v}
4654 Verbose mode: generates more output about work done.
4655 @end table
4657 Note: if neither @code{-b} nor @code{-c} is present,
4658 then preprocessor lines and
4659 deleted lines are completely removed from the output, unless -r is
4660 specified, in which case -b is assumed.
4662 @node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4663 @anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{98}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{99}
4664 @subsubsection Form of Definitions File
4667 The definitions file contains lines of the form:
4669 @example
4670 symbol := value
4671 @end example
4673 where @code{symbol} is a preprocessing symbol, and @code{value} is one of the following:
4676 @itemize *
4678 @item 
4679 Empty, corresponding to a null substitution,
4681 @item 
4682 A string literal using normal Ada syntax, or
4684 @item 
4685 Any sequence of characters from the set @{letters, digits, period, underline@}.
4686 @end itemize
4688 Comment lines may also appear in the definitions file, starting with
4689 the usual @code{--},
4690 and comments may be added to the definitions lines.
4692 @node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4693 @anchor{gnat_ugn/the_gnat_compilation_model form-of-input-text-for-gnatprep}@anchor{9a}@anchor{gnat_ugn/the_gnat_compilation_model id59}@anchor{9b}
4694 @subsubsection Form of Input Text for @code{gnatprep}
4697 The input text may contain preprocessor conditional inclusion lines,
4698 as well as general symbol substitution sequences.
4700 The preprocessor conditional inclusion commands have the form:
4702 @example
4703 #if <expression> [then]
4704    lines
4705 #elsif <expression> [then]
4706    lines
4707 #elsif <expression> [then]
4708    lines
4710 #else
4711    lines
4712 #end if;
4713 @end example
4715 In this example, <expression> is defined by the following grammar:
4717 @example
4718 <expression> ::=  <symbol>
4719 <expression> ::=  <symbol> = "<value>"
4720 <expression> ::=  <symbol> = <symbol>
4721 <expression> ::=  <symbol> = <integer>
4722 <expression> ::=  <symbol> > <integer>
4723 <expression> ::=  <symbol> >= <integer>
4724 <expression> ::=  <symbol> < <integer>
4725 <expression> ::=  <symbol> <= <integer>
4726 <expression> ::=  <symbol> 'Defined
4727 <expression> ::=  not <expression>
4728 <expression> ::=  <expression> and <expression>
4729 <expression> ::=  <expression> or <expression>
4730 <expression> ::=  <expression> and then <expression>
4731 <expression> ::=  <expression> or else <expression>
4732 <expression> ::=  ( <expression> )
4733 @end example
4735 Note the following restriction: it is not allowed to have “and” or “or”
4736 following “not” in the same expression without parentheses. For example, this
4737 is not allowed:
4739 @example
4740 not X or Y
4741 @end example
4743 This can be expressed instead as one of the following forms:
4745 @example
4746 (not X) or Y
4747 not (X or Y)
4748 @end example
4750 For the first test (<expression> ::= <symbol>) the symbol must have
4751 either the value true or false, that is to say the right-hand of the
4752 symbol definition must be one of the (case-insensitive) literals
4753 @code{True} or @code{False}. If the value is true, then the
4754 corresponding lines are included, and if the value is false, they are
4755 excluded.
4757 When comparing a symbol to an integer, the integer is any non negative
4758 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
4759 2#11#. The symbol value must also be a non negative integer. Integer values
4760 in the range 0 .. 2**31-1 are supported.
4762 The test (<expression> ::= <symbol>’Defined) is true only if
4763 the symbol has been defined in the definition file or by a @code{-D}
4764 switch on the command line. Otherwise, the test is false.
4766 The equality tests are case insensitive, as are all the preprocessor lines.
4768 If the symbol referenced is not defined in the symbol definitions file,
4769 then the effect depends on whether or not switch @code{-u}
4770 is specified. If so, then the symbol is treated as if it had the value
4771 false and the test fails. If this switch is not specified, then
4772 it is an error to reference an undefined symbol. It is also an error to
4773 reference a symbol that is defined with a value other than @code{True}
4774 or @code{False}.
4776 The use of the @code{not} operator inverts the sense of this logical test.
4777 The @code{not} operator cannot be combined with the @code{or} or @code{and}
4778 operators, without parentheses. For example, “if not X or Y then” is not
4779 allowed, but “if (not X) or Y then” and “if not (X or Y) then” are.
4781 The @code{then} keyword is optional as shown
4783 The @code{#} must be the first non-blank character on a line, but
4784 otherwise the format is free form. Spaces or tabs may appear between
4785 the @code{#} and the keyword. The keywords and the symbols are case
4786 insensitive as in normal Ada code. Comments may be used on a
4787 preprocessor line, but other than that, no other tokens may appear on a
4788 preprocessor line. Any number of @code{elsif} clauses can be present,
4789 including none at all. The @code{else} is optional, as in Ada.
4791 The @code{#} marking the start of a preprocessor line must be the first
4792 non-blank character on the line, i.e., it must be preceded only by
4793 spaces or horizontal tabs.
4795 Symbol substitution outside of preprocessor lines is obtained by using
4796 the sequence:
4798 @example
4799 $symbol
4800 @end example
4802 anywhere within a source line, except in a comment or within a
4803 string literal. The identifier
4804 following the @code{$} must match one of the symbols defined in the symbol
4805 definition file, and the result is to substitute the value of the
4806 symbol in place of @code{$symbol} in the output file.
4808 Note that although the substitution of strings within a string literal
4809 is not possible, it is possible to have a symbol whose defined value is
4810 a string literal. So instead of setting XYZ to @code{hello} and writing:
4812 @example
4813 Header : String := "$XYZ";
4814 @end example
4816 you should set XYZ to @code{"hello"} and write:
4818 @example
4819 Header : String := $XYZ;
4820 @end example
4822 and then the substitution will occur as desired.
4824 @node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
4825 @anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{9c}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{90}
4826 @subsection Integrated Preprocessing
4829 As noted above, a file to be preprocessed consists of Ada source code
4830 in which preprocessing lines have been inserted. However,
4831 instead of using @code{gnatprep} to explicitly preprocess a file as a separate
4832 step before compilation, you can carry out the preprocessing implicitly
4833 as part of compilation. Such @emph{integrated preprocessing}, which is the common
4834 style with C, is performed when either or both of the following switches
4835 are passed to the compiler:
4837 @quotation
4840 @itemize *
4842 @item 
4843 @code{-gnatep}, which specifies the @emph{preprocessor data file}.
4844 This file dictates how the source files will be preprocessed (e.g., which
4845 symbol definition files apply to which sources).
4847 @item 
4848 @code{-gnateD}, which defines values for preprocessing symbols.
4849 @end itemize
4850 @end quotation
4852 Integrated preprocessing applies only to Ada source files, it is
4853 not available for configuration pragma files.
4855 With integrated preprocessing, the output from the preprocessor is not,
4856 by default, written to any external file. Instead it is passed
4857 internally to the compiler. To preserve the result of
4858 preprocessing in a file, either run @code{gnatprep}
4859 in standalone mode or else supply the @code{-gnateG} switch
4860 (described below) to the compiler.
4862 When using project files:
4864 @quotation
4867 @itemize *
4869 @item 
4870 the builder switch @code{-x} should be used if any Ada source is
4871 compiled with @code{gnatep=}, so that the compiler finds the
4872 @emph{preprocessor data file}.
4874 @item 
4875 the preprocessing data file and the symbol definition files should be
4876 located in the source directories of the project.
4877 @end itemize
4878 @end quotation
4880 Note that the @code{gnatmake} switch @code{-m} will almost
4881 always trigger recompilation for sources that are preprocessed,
4882 because @code{gnatmake} cannot compute the checksum of the source after
4883 preprocessing.
4885 The actual preprocessing function is described in detail in
4886 @ref{8f,,Preprocessing with gnatprep}. This section explains the switches
4887 that relate to integrated preprocessing.
4889 @geindex -gnatep (gcc)
4892 @table @asis
4894 @item @code{-gnatep=@emph{preprocessor_data_file}}
4896 This switch specifies the file name (without directory
4897 information) of the preprocessor data file. Either place this file
4898 in one of the source directories, or, when using project
4899 files, reference the project file’s directory via the
4900 @code{project_name'Project_Dir} project attribute; e.g:
4902 @quotation
4904 @example
4905 project Prj is
4906    package Compiler is
4907       for Switches ("Ada") use
4908         ("-gnatep=" & Prj'Project_Dir & "prep.def");
4909    end Compiler;
4910 end Prj;
4911 @end example
4912 @end quotation
4914 A preprocessor data file is a text file that contains @emph{preprocessor
4915 control lines}.  A preprocessor control line directs the preprocessing of
4916 either a particular source file, or, analogous to @code{others} in Ada,
4917 all sources not specified elsewhere in  the preprocessor data file.
4918 A preprocessor control line
4919 can optionally identify a @emph{definition file} that assigns values to
4920 preprocessor symbols, as well as a list of switches that relate to
4921 preprocessing.
4922 Empty lines and comments (using Ada syntax) are also permitted, with no
4923 semantic effect.
4925 Here’s an example of a preprocessor data file:
4927 @quotation
4929 @example
4930 "toto.adb"  "prep.def" -u
4931 --  Preprocess toto.adb, using definition file prep.def
4932 --  Undefined symbols are treated as False
4934 * -c -DVERSION=V101
4935 --  Preprocess all other sources without using a definition file
4936 --  Suppressed lined are commented
4937 --  Symbol VERSION has the value V101
4939 "tata.adb" "prep2.def" -s
4940 --  Preprocess tata.adb, using definition file prep2.def
4941 --  List all symbols with their values
4942 @end example
4943 @end quotation
4945 A preprocessor control line has the following syntax:
4947 @quotation
4949 @example
4950 <preprocessor_control_line> ::=
4951    <preprocessor_input> [ <definition_file_name> ] @{ <switch> @}
4953 <preprocessor_input> ::= <source_file_name> | '*'
4955 <definition_file_name> ::= <string_literal>
4957 <source_file_name> := <string_literal>
4959 <switch> := (See below for list)
4960 @end example
4961 @end quotation
4963 Thus  each preprocessor control line starts with either a literal string or
4964 the character ‘*’:
4967 @itemize *
4969 @item 
4970 A literal string is the file name (without directory information) of the source
4971 file that will be input to the preprocessor.
4973 @item 
4974 The character ‘*’ is a wild-card indicator; the additional parameters on the line
4975 indicate the preprocessing for all the sources
4976 that are not specified explicitly on other lines (the order of the lines is not
4977 significant).
4978 @end itemize
4980 It is an error to have two lines with the same file name or two
4981 lines starting with the character ‘*’.
4983 After the file name or ‘*’, an optional literal string specifies the name of
4984 the definition file to be used for preprocessing
4985 (@ref{98,,Form of Definitions File}). The definition files are found by the
4986 compiler in one of the source directories. In some cases, when compiling
4987 a source in a directory other than the current directory, if the definition
4988 file is in the current directory, it may be necessary to add the current
4989 directory as a source directory through the @code{-I} switch; otherwise
4990 the compiler would not find the definition file.
4992 Finally, switches similar to those of @code{gnatprep} may optionally appear:
4995 @table @asis
4997 @item @code{-b}
4999 Causes both preprocessor lines and the lines deleted by
5000 preprocessing to be replaced by blank lines, preserving the line number.
5001 This switch is always implied; however, if specified after @code{-c}
5002 it cancels the effect of @code{-c}.
5004 @item @code{-c}
5006 Causes both preprocessor lines and the lines deleted
5007 by preprocessing to be retained as comments marked
5008 with the special string ‘@cite{–!}’.
5010 @item @code{-D@emph{symbol}=@emph{new_value}}
5012 Define or redefine @code{symbol} to have @code{new_value} as its value.
5013 The permitted form for @code{symbol} is either an Ada identifier, or any Ada reserved word
5014 aside from @code{if},
5015 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5016 The permitted form for @code{new_value} is a literal string, an Ada identifier or any Ada reserved
5017 word. A symbol declared with this switch replaces a symbol with the
5018 same name defined in a definition file.
5020 @item @code{-s}
5022 Causes a sorted list of symbol names and values to be
5023 listed on the standard output file.
5025 @item @code{-u}
5027 Causes undefined symbols to be treated as having the value @code{FALSE}
5028 in the context
5029 of a preprocessor test. In the absence of this option, an undefined symbol in
5030 a @code{#if} or @code{#elsif} test will be treated as an error.
5031 @end table
5032 @end table
5034 @geindex -gnateD (gcc)
5037 @table @asis
5039 @item @code{-gnateD@emph{symbol}[=@emph{new_value}]}
5041 Define or redefine @code{symbol} to have @code{new_value} as its value. If no value
5042 is supplied, then the value of @code{symbol} is @code{True}.
5043 The form of @code{symbol} is an identifier, following normal Ada (case-insensitive)
5044 rules for its syntax, and @code{new_value} is either an arbitrary string between double
5045 quotes or any sequence (including an empty sequence) of characters from the
5046 set (letters, digits, period, underline).
5047 Ada reserved words may be used as symbols, with the exceptions of @code{if},
5048 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5050 Examples:
5052 @quotation
5054 @example
5055 -gnateDToto=Tata
5056 -gnateDFoo
5057 -gnateDFoo=\"Foo-Bar\"
5058 @end example
5059 @end quotation
5061 A symbol declared with this switch on the command line replaces a
5062 symbol with the same name either in a definition file or specified with a
5063 switch @code{-D} in the preprocessor data file.
5065 This switch is similar to switch @code{-D} of @code{gnatprep}.
5067 @item @code{-gnateG}
5069 When integrated preprocessing is performed on source file @code{filename.extension},
5070 create or overwrite @code{filename.extension.prep} to contain
5071 the result of the preprocessing.
5072 For example if the source file is @code{foo.adb} then
5073 the output file will be @code{foo.adb.prep}.
5074 @end table
5076 @node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5077 @anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{9d}@anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{2c}
5078 @section Mixed Language Programming
5081 @geindex Mixed Language Programming
5083 This section describes how to develop a mixed-language program,
5084 with a focus on combining Ada with C or C++.
5086 @menu
5087 * Interfacing to C:: 
5088 * Calling Conventions:: 
5089 * Building Mixed Ada and C++ Programs:: 
5090 * Generating Ada Bindings for C and C++ headers:: 
5091 * Generating C Headers for Ada Specifications:: 
5093 @end menu
5095 @node Interfacing to C,Calling Conventions,,Mixed Language Programming
5096 @anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{9e}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{9f}
5097 @subsection Interfacing to C
5100 Interfacing Ada with a foreign language such as C involves using
5101 compiler directives to import and/or export entity definitions in each
5102 language – using @code{extern} statements in C, for instance, and the
5103 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
5104 A full treatment of these topics is provided in Appendix B, section 1
5105 of the Ada Reference Manual.
5107 There are two ways to build a program using GNAT that contains some Ada
5108 sources and some foreign language sources, depending on whether or not
5109 the main subprogram is written in Ada.  Here is a source example with
5110 the main subprogram in Ada:
5112 @example
5113 /* file1.c */
5114 #include <stdio.h>
5116 void print_num (int num)
5118   printf ("num is %d.\\n", num);
5119   return;
5121 @end example
5123 @example
5124 /* file2.c */
5126 /* num_from_Ada is declared in my_main.adb */
5127 extern int num_from_Ada;
5129 int get_num (void)
5131   return num_from_Ada;
5133 @end example
5135 @example
5136 --  my_main.adb
5137 procedure My_Main is
5139    --  Declare then export an Integer entity called num_from_Ada
5140    My_Num : Integer := 10;
5141    pragma Export (C, My_Num, "num_from_Ada");
5143    --  Declare an Ada function spec for Get_Num, then use
5144    --  C function get_num for the implementation.
5145    function Get_Num return Integer;
5146    pragma Import (C, Get_Num, "get_num");
5148    --  Declare an Ada procedure spec for Print_Num, then use
5149    --  C function print_num for the implementation.
5150    procedure Print_Num (Num : Integer);
5151    pragma Import (C, Print_Num, "print_num");
5153 begin
5154    Print_Num (Get_Num);
5155 end My_Main;
5156 @end example
5158 To build this example:
5161 @itemize *
5163 @item 
5164 First compile the foreign language files to
5165 generate object files:
5167 @example
5168 $ gcc -c file1.c
5169 $ gcc -c file2.c
5170 @end example
5172 @item 
5173 Then, compile the Ada units to produce a set of object files and ALI
5174 files:
5176 @example
5177 $ gnatmake -c my_main.adb
5178 @end example
5180 @item 
5181 Run the Ada binder on the Ada main program:
5183 @example
5184 $ gnatbind my_main.ali
5185 @end example
5187 @item 
5188 Link the Ada main program, the Ada objects and the other language
5189 objects:
5191 @example
5192 $ gnatlink my_main.ali file1.o file2.o
5193 @end example
5194 @end itemize
5196 The last three steps can be grouped in a single command:
5198 @example
5199 $ gnatmake my_main.adb -largs file1.o file2.o
5200 @end example
5202 @geindex Binder output file
5204 If the main program is in a language other than Ada, then you may have
5205 more than one entry point into the Ada subsystem. You must use a special
5206 binder option to generate callable routines that initialize and
5207 finalize the Ada units (@ref{a0,,Binding with Non-Ada Main Programs}).
5208 Calls to the initialization and finalization routines must be inserted
5209 in the main program, or some other appropriate point in the code. The
5210 call to initialize the Ada units must occur before the first Ada
5211 subprogram is called, and the call to finalize the Ada units must occur
5212 after the last Ada subprogram returns. The binder will place the
5213 initialization and finalization subprograms into the
5214 @code{b~xxx.adb} file where they can be accessed by your C
5215 sources.  To illustrate, we have the following example:
5217 @example
5218 /* main.c */
5219 extern void adainit (void);
5220 extern void adafinal (void);
5221 extern int add (int, int);
5222 extern int sub (int, int);
5224 int main (int argc, char *argv[])
5226    int a = 21, b = 7;
5228    adainit();
5230    /* Should print "21 + 7 = 28" */
5231    printf ("%d + %d = %d\\n", a, b, add (a, b));
5233    /* Should print "21 - 7 = 14" */
5234    printf ("%d - %d = %d\\n", a, b, sub (a, b));
5236    adafinal();
5238 @end example
5240 @example
5241 --  unit1.ads
5242 package Unit1 is
5243    function Add (A, B : Integer) return Integer;
5244    pragma Export (C, Add, "add");
5245 end Unit1;
5246 @end example
5248 @example
5249 --  unit1.adb
5250 package body Unit1 is
5251    function Add (A, B : Integer) return Integer is
5252    begin
5253       return A + B;
5254    end Add;
5255 end Unit1;
5256 @end example
5258 @example
5259 --  unit2.ads
5260 package Unit2 is
5261    function Sub (A, B : Integer) return Integer;
5262    pragma Export (C, Sub, "sub");
5263 end Unit2;
5264 @end example
5266 @example
5267 --  unit2.adb
5268 package body Unit2 is
5269    function Sub (A, B : Integer) return Integer is
5270    begin
5271       return A - B;
5272    end Sub;
5273 end Unit2;
5274 @end example
5276 The build procedure for this application is similar to the last
5277 example’s:
5280 @itemize *
5282 @item 
5283 First, compile the foreign language files to generate object files:
5285 @example
5286 $ gcc -c main.c
5287 @end example
5289 @item 
5290 Next, compile the Ada units to produce a set of object files and ALI
5291 files:
5293 @example
5294 $ gnatmake -c unit1.adb
5295 $ gnatmake -c unit2.adb
5296 @end example
5298 @item 
5299 Run the Ada binder on every generated ALI file.  Make sure to use the
5300 @code{-n} option to specify a foreign main program:
5302 @example
5303 $ gnatbind -n unit1.ali unit2.ali
5304 @end example
5306 @item 
5307 Link the Ada main program, the Ada objects and the foreign language
5308 objects. You need only list the last ALI file here:
5310 @example
5311 $ gnatlink unit2.ali main.o -o exec_file
5312 @end example
5314 This procedure yields a binary executable called @code{exec_file}.
5315 @end itemize
5317 Depending on the circumstances (for example when your non-Ada main object
5318 does not provide symbol @code{main}), you may also need to instruct the
5319 GNAT linker not to include the standard startup objects by passing the
5320 @code{-nostartfiles} switch to @code{gnatlink}.
5322 @node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5323 @anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{a2}
5324 @subsection Calling Conventions
5327 @geindex Foreign Languages
5329 @geindex Calling Conventions
5331 GNAT follows standard calling sequence conventions and will thus interface
5332 to any other language that also follows these conventions. The following
5333 Convention identifiers are recognized by GNAT:
5335 @geindex Interfacing to Ada
5337 @geindex Other Ada compilers
5339 @geindex Convention Ada
5342 @table @asis
5344 @item @code{Ada}
5346 This indicates that the standard Ada calling sequence will be
5347 used and all Ada data items may be passed without any limitations in the
5348 case where GNAT is used to generate both the caller and callee. It is also
5349 possible to mix GNAT generated code and code generated by another Ada
5350 compiler. In this case, the data types should be restricted to simple
5351 cases, including primitive types. Whether complex data types can be passed
5352 depends on the situation. Probably it is safe to pass simple arrays, such
5353 as arrays of integers or floats. Records may or may not work, depending
5354 on whether both compilers lay them out identically. Complex structures
5355 involving variant records, access parameters, tasks, or protected types,
5356 are unlikely to be able to be passed.
5358 Note that in the case of GNAT running
5359 on a platform that supports HP Ada 83, a higher degree of compatibility
5360 can be guaranteed, and in particular records are laid out in an identical
5361 manner in the two compilers. Note also that if output from two different
5362 compilers is mixed, the program is responsible for dealing with elaboration
5363 issues. Probably the safest approach is to write the main program in the
5364 version of Ada other than GNAT, so that it takes care of its own elaboration
5365 requirements, and then call the GNAT-generated adainit procedure to ensure
5366 elaboration of the GNAT components. Consult the documentation of the other
5367 Ada compiler for further details on elaboration.
5369 However, it is not possible to mix the tasking run time of GNAT and
5370 HP Ada 83, All the tasking operations must either be entirely within
5371 GNAT compiled sections of the program, or entirely within HP Ada 83
5372 compiled sections of the program.
5373 @end table
5375 @geindex Interfacing to Assembly
5377 @geindex Convention Assembler
5380 @table @asis
5382 @item @code{Assembler}
5384 Specifies assembler as the convention. In practice this has the
5385 same effect as convention Ada (but is not equivalent in the sense of being
5386 considered the same convention).
5387 @end table
5389 @geindex Convention Asm
5391 @geindex Asm
5394 @table @asis
5396 @item @code{Asm}
5398 Equivalent to Assembler.
5400 @geindex Interfacing to COBOL
5402 @geindex Convention COBOL
5403 @end table
5405 @geindex COBOL
5408 @table @asis
5410 @item @code{COBOL}
5412 Data will be passed according to the conventions described
5413 in section B.4 of the Ada Reference Manual.
5414 @end table
5416 @geindex C
5418 @geindex Interfacing to C
5420 @geindex Convention C
5423 @table @asis
5425 @item @code{C}
5427 Data will be passed according to the conventions described
5428 in section B.3 of the Ada Reference Manual.
5430 A note on interfacing to a C ‘varargs’ function:
5432 @quotation
5434 @geindex C varargs function
5436 @geindex Interfacing to C varargs function
5438 @geindex varargs function interfaces
5440 In C, @code{varargs} allows a function to take a variable number of
5441 arguments. There is no direct equivalent in this to Ada. One
5442 approach that can be used is to create a C wrapper for each
5443 different profile and then interface to this C wrapper. For
5444 example, to print an @code{int} value using @code{printf},
5445 create a C function @code{printfi} that takes two arguments, a
5446 pointer to a string and an int, and calls @code{printf}.
5447 Then in the Ada program, use pragma @code{Import} to
5448 interface to @code{printfi}.
5450 It may work on some platforms to directly interface to
5451 a @code{varargs} function by providing a specific Ada profile
5452 for a particular call. However, this does not work on
5453 all platforms, since there is no guarantee that the
5454 calling sequence for a two argument normal C function
5455 is the same as for calling a @code{varargs} C function with
5456 the same two arguments.
5457 @end quotation
5458 @end table
5460 @geindex Convention Default
5462 @geindex Default
5465 @table @asis
5467 @item @code{Default}
5469 Equivalent to C.
5470 @end table
5472 @geindex Convention External
5474 @geindex External
5477 @table @asis
5479 @item @code{External}
5481 Equivalent to C.
5482 @end table
5484 @geindex C++
5486 @geindex Interfacing to C++
5488 @geindex Convention C++
5491 @table @asis
5493 @item @code{C_Plus_Plus} (or @code{CPP})
5495 This stands for C++. For most purposes this is identical to C.
5496 See the separate description of the specialized GNAT pragmas relating to
5497 C++ interfacing for further details.
5498 @end table
5500 @geindex Fortran
5502 @geindex Interfacing to Fortran
5504 @geindex Convention Fortran
5507 @table @asis
5509 @item @code{Fortran}
5511 Data will be passed according to the conventions described
5512 in section B.5 of the Ada Reference Manual.
5514 @item @code{Intrinsic}
5516 This applies to an intrinsic operation, as defined in the Ada
5517 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5518 this means that the body of the subprogram is provided by the compiler itself,
5519 usually by means of an efficient code sequence, and that the user does not
5520 supply an explicit body for it. In an application program, the pragma may
5521 be applied to the following sets of names:
5524 @itemize *
5526 @item 
5527 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5528 The corresponding subprogram declaration must have
5529 two formal parameters. The
5530 first one must be a signed integer type or a modular type with a binary
5531 modulus, and the second parameter must be of type Natural.
5532 The return type must be the same as the type of the first argument. The size
5533 of this type can only be 8, 16, 32, or 64.
5535 @item 
5536 Binary arithmetic operators: ‘+’, ‘-‘, ‘*’, ‘/’.
5537 The corresponding operator declaration must have parameters and result type
5538 that have the same root numeric type (for example, all three are long_float
5539 types). This simplifies the definition of operations that use type checking
5540 to perform dimensional checks:
5541 @end itemize
5543 @example
5544   type Distance is new Long_Float;
5545   type Time     is new Long_Float;
5546   type Velocity is new Long_Float;
5547   function "/" (D : Distance; T : Time)
5548     return Velocity;
5549   pragma Import (Intrinsic, "/");
5551 This common idiom is often programmed with a generic definition and an
5552 explicit body. The pragma makes it simpler to introduce such declarations.
5553 It incurs no overhead in compilation time or code size, because it is
5554 implemented as a single machine instruction.
5555 @end example
5558 @itemize *
5560 @item 
5561 General subprogram entities. This is used  to bind an Ada subprogram
5562 declaration to
5563 a compiler builtin by name with back-ends where such interfaces are
5564 available. A typical example is the set of @code{__builtin} functions
5565 exposed by the GCC back-end, as in the following example:
5567 @example
5568 function builtin_sqrt (F : Float) return Float;
5569 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5570 @end example
5572 Most of the GCC builtins are accessible this way, and as for other
5573 import conventions (e.g. C), it is the user’s responsibility to ensure
5574 that the Ada subprogram profile matches the underlying builtin
5575 expectations.
5576 @end itemize
5577 @end table
5579 @geindex Stdcall
5581 @geindex Convention Stdcall
5584 @table @asis
5586 @item @code{Stdcall}
5588 This is relevant only to Windows implementations of GNAT,
5589 and specifies that the @code{Stdcall} calling sequence will be used,
5590 as defined by the NT API. Nevertheless, to ease building
5591 cross-platform bindings this convention will be handled as a @code{C} calling
5592 convention on non-Windows platforms.
5593 @end table
5595 @geindex DLL
5597 @geindex Convention DLL
5600 @table @asis
5602 @item @code{DLL}
5604 This is equivalent to @code{Stdcall}.
5605 @end table
5607 @geindex Win32
5609 @geindex Convention Win32
5612 @table @asis
5614 @item @code{Win32}
5616 This is equivalent to @code{Stdcall}.
5617 @end table
5619 @geindex Stubbed
5621 @geindex Convention Stubbed
5624 @table @asis
5626 @item @code{Stubbed}
5628 This is a special convention that indicates that the compiler
5629 should provide a stub body that raises @code{Program_Error}.
5630 @end table
5632 GNAT additionally provides a useful pragma @code{Convention_Identifier}
5633 that can be used to parameterize conventions and allow additional synonyms
5634 to be specified. For example if you have legacy code in which the convention
5635 identifier Fortran77 was used for Fortran, you can use the configuration
5636 pragma:
5638 @example
5639 pragma Convention_Identifier (Fortran77, Fortran);
5640 @end example
5642 And from now on the identifier Fortran77 may be used as a convention
5643 identifier (for example in an @code{Import} pragma) with the same
5644 meaning as Fortran.
5646 @node Building Mixed Ada and C++ Programs,Generating Ada Bindings for C and C++ headers,Calling Conventions,Mixed Language Programming
5647 @anchor{gnat_ugn/the_gnat_compilation_model building-mixed-ada-and-c-programs}@anchor{a3}@anchor{gnat_ugn/the_gnat_compilation_model id64}@anchor{a4}
5648 @subsection Building Mixed Ada and C++ Programs
5651 A programmer inexperienced with mixed-language development may find that
5652 building an application containing both Ada and C++ code can be a
5653 challenge.  This section gives a few hints that should make this task easier.
5655 @menu
5656 * Interfacing to C++:: 
5657 * Linking a Mixed C++ & Ada Program:: 
5658 * A Simple Example:: 
5659 * Interfacing with C++ constructors:: 
5660 * Interfacing with C++ at the Class Level:: 
5662 @end menu
5664 @node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5665 @anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{a6}
5666 @subsubsection Interfacing to C++
5669 GNAT supports interfacing with the G++ compiler (or any C++ compiler
5670 generating code that is compatible with the G++ Application Binary
5671 Interface —see @indicateurl{http://www.codesourcery.com/archives/cxx-abi}).
5673 Interfacing can be done at 3 levels: simple data, subprograms, and
5674 classes. In the first two cases, GNAT offers a specific @code{Convention C_Plus_Plus}
5675 (or @code{CPP}) that behaves exactly like @code{Convention C}.
5676 Usually, C++ mangles the names of subprograms. To generate proper mangled
5677 names automatically, see @ref{a7,,Generating Ada Bindings for C and C++ headers}).
5678 This problem can also be addressed manually in two ways:
5681 @itemize *
5683 @item 
5684 by modifying the C++ code in order to force a C convention using
5685 the @code{extern "C"} syntax.
5687 @item 
5688 by figuring out the mangled name (using e.g. @code{nm}) and using it as the
5689 Link_Name argument of the pragma import.
5690 @end itemize
5692 Interfacing at the class level can be achieved by using the GNAT specific
5693 pragmas such as @code{CPP_Constructor}.  See the @cite{GNAT_Reference_Manual} for additional information.
5695 @node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5696 @anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-ada-program}@anchor{a8}@anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-and-ada-program}@anchor{a9}
5697 @subsubsection Linking a Mixed C++ & Ada Program
5700 Usually the linker of the C++ development system must be used to link
5701 mixed applications because most C++ systems will resolve elaboration
5702 issues (such as calling constructors on global class instances)
5703 transparently during the link phase. GNAT has been adapted to ease the
5704 use of a foreign linker for the last phase. Three cases can be
5705 considered:
5708 @itemize *
5710 @item 
5711 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5712 The C++ linker can simply be called by using the C++ specific driver
5713 called @code{g++}.
5715 Note that if the C++ code uses inline functions, you will need to
5716 compile your C++ code with the @code{-fkeep-inline-functions} switch in
5717 order to provide an existing function implementation that the Ada code can
5718 link with.
5720 @example
5721 $ g++ -c -fkeep-inline-functions file1.C
5722 $ g++ -c -fkeep-inline-functions file2.C
5723 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5724 @end example
5726 @item 
5727 Using GNAT and G++ from two different GCC installations: If both
5728 compilers are on the :envvar`PATH`, the previous method may be used. It is
5729 important to note that environment variables such as
5730 @geindex C_INCLUDE_PATH
5731 @geindex environment variable; C_INCLUDE_PATH
5732 @code{C_INCLUDE_PATH}, 
5733 @geindex GCC_EXEC_PREFIX
5734 @geindex environment variable; GCC_EXEC_PREFIX
5735 @code{GCC_EXEC_PREFIX},
5736 @geindex BINUTILS_ROOT
5737 @geindex environment variable; BINUTILS_ROOT
5738 @code{BINUTILS_ROOT}, and
5739 @geindex GCC_ROOT
5740 @geindex environment variable; GCC_ROOT
5741 @code{GCC_ROOT} will affect both compilers
5742 at the same time and may make one of the two compilers operate
5743 improperly if set during invocation of the wrong compiler.  It is also
5744 very important that the linker uses the proper @code{libgcc.a} GCC
5745 library – that is, the one from the C++ compiler installation. The
5746 implicit link command as suggested in the @code{gnatmake} command
5747 from the former example can be replaced by an explicit link command with
5748 the full-verbosity option in order to verify which library is used:
5750 @example
5751 $ gnatbind ada_unit
5752 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5753 @end example
5755 If there is a problem due to interfering environment variables, it can
5756 be worked around by using an intermediate script. The following example
5757 shows the proper script to use when GNAT has not been installed at its
5758 default location and g++ has been installed at its default location:
5760 @example
5761 $ cat ./my_script
5762 #!/bin/sh
5763 unset BINUTILS_ROOT
5764 unset GCC_ROOT
5765 c++ $*
5766 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5767 @end example
5769 @item 
5770 Using a non-GNU C++ compiler: The commands previously described can be
5771 used to insure that the C++ linker is used. Nonetheless, you need to add
5772 a few more parameters to the link command line, depending on the exception
5773 mechanism used.
5775 If the @code{setjmp} / @code{longjmp} exception mechanism is used, only the paths
5776 to the @code{libgcc} libraries are required:
5778 @example
5779 $ cat ./my_script
5780 #!/bin/sh
5781 CC $* gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a
5782 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5783 @end example
5785 where CC is the name of the non-GNU C++ compiler.
5787 If the “zero cost” exception mechanism is used, and the platform
5788 supports automatic registration of exception tables (e.g., Solaris),
5789 paths to more objects are required:
5791 @example
5792 $ cat ./my_script
5793 #!/bin/sh
5794 CC gcc -print-file-name=crtbegin.o $* \\
5795 gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a \\
5796 gcc -print-file-name=crtend.o
5797 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5798 @end example
5800 If the “zero cost exception” mechanism is used, and the platform
5801 doesn’t support automatic registration of exception tables (e.g., HP-UX
5802 or AIX), the simple approach described above will not work and
5803 a pre-linking phase using GNAT will be necessary.
5804 @end itemize
5806 Another alternative is to use the @code{gprbuild} multi-language builder
5807 which has a large knowledge base and knows how to link Ada and C++ code
5808 together automatically in most cases.
5810 @node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
5811 @anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{aa}@anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{ab}
5812 @subsubsection A Simple Example
5815 The following example, provided as part of the GNAT examples, shows how
5816 to achieve procedural interfacing between Ada and C++ in both
5817 directions. The C++ class A has two methods. The first method is exported
5818 to Ada by the means of an extern C wrapper function. The second method
5819 calls an Ada subprogram. On the Ada side, the C++ calls are modelled by
5820 a limited record with a layout comparable to the C++ class. The Ada
5821 subprogram, in turn, calls the C++ method. So, starting from the C++
5822 main program, the process passes back and forth between the two
5823 languages.
5825 Here are the compilation commands:
5827 @example
5828 $ gnatmake -c simple_cpp_interface
5829 $ g++ -c cpp_main.C
5830 $ g++ -c ex7.C
5831 $ gnatbind -n simple_cpp_interface
5832 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
5833 @end example
5835 Here are the corresponding sources:
5837 @example
5838 //cpp_main.C
5840 #include "ex7.h"
5842 extern "C" @{
5843   void adainit (void);
5844   void adafinal (void);
5845   void method1 (A *t);
5848 void method1 (A *t)
5850   t->method1 ();
5853 int main ()
5855   A obj;
5856   adainit ();
5857   obj.method2 (3030);
5858   adafinal ();
5860 @end example
5862 @example
5863 //ex7.h
5865 class Origin @{
5866  public:
5867   int o_value;
5869 class A : public Origin @{
5870  public:
5871   void method1 (void);
5872   void method2 (int v);
5873   A();
5874   int   a_value;
5876 @end example
5878 @example
5879 //ex7.C
5881 #include "ex7.h"
5882 #include <stdio.h>
5884 extern "C" @{ void ada_method2 (A *t, int v);@}
5886 void A::method1 (void)
5888   a_value = 2020;
5889   printf ("in A::method1, a_value = %d \\n",a_value);
5892 void A::method2 (int v)
5894    ada_method2 (this, v);
5895    printf ("in A::method2, a_value = %d \\n",a_value);
5898 A::A(void)
5900    a_value = 1010;
5901   printf ("in A::A, a_value = %d \\n",a_value);
5903 @end example
5905 @example
5906 -- simple_cpp_interface.ads
5907 with System;
5908 package Simple_Cpp_Interface is
5909    type A is limited
5910       record
5911          Vptr    : System.Address;
5912          O_Value : Integer;
5913          A_Value : Integer;
5914       end record;
5915    pragma Convention (C, A);
5917    procedure Method1 (This : in out A);
5918    pragma Import (C, Method1);
5920    procedure Ada_Method2 (This : in out A; V : Integer);
5921    pragma Export (C, Ada_Method2);
5923 end Simple_Cpp_Interface;
5924 @end example
5926 @example
5927 -- simple_cpp_interface.adb
5928 package body Simple_Cpp_Interface is
5930    procedure Ada_Method2 (This : in out A; V : Integer) is
5931    begin
5932       Method1 (This);
5933       This.A_Value := V;
5934    end Ada_Method2;
5936 end Simple_Cpp_Interface;
5937 @end example
5939 @node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
5940 @anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{ad}
5941 @subsubsection Interfacing with C++ constructors
5944 In order to interface with C++ constructors GNAT provides the
5945 @code{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
5946 for additional information).
5947 In this section we present some common uses of C++ constructors
5948 in mixed-languages programs in GNAT.
5950 Let us assume that we need to interface with the following
5951 C++ class:
5953 @example
5954 class Root @{
5955 public:
5956   int  a_value;
5957   int  b_value;
5958   virtual int Get_Value ();
5959   Root();              // Default constructor
5960   Root(int v);         // 1st non-default constructor
5961   Root(int v, int w);  // 2nd non-default constructor
5963 @end example
5965 For this purpose we can write the following package spec (further
5966 information on how to build this spec is available in
5967 @ref{ae,,Interfacing with C++ at the Class Level} and
5968 @ref{a7,,Generating Ada Bindings for C and C++ headers}).
5970 @example
5971 with Interfaces.C; use Interfaces.C;
5972 package Pkg_Root is
5973   type Root is tagged limited record
5974      A_Value : int;
5975      B_Value : int;
5976   end record;
5977   pragma Import (CPP, Root);
5979   function Get_Value (Obj : Root) return int;
5980   pragma Import (CPP, Get_Value);
5982   function Constructor return Root;
5983   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
5985   function Constructor (v : Integer) return Root;
5986   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
5988   function Constructor (v, w : Integer) return Root;
5989   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
5990 end Pkg_Root;
5991 @end example
5993 On the Ada side the constructor is represented by a function (whose
5994 name is arbitrary) that returns the classwide type corresponding to
5995 the imported C++ class. Although the constructor is described as a
5996 function, it is typically a procedure with an extra implicit argument
5997 (the object being initialized) at the implementation level. GNAT
5998 issues the appropriate call, whatever it is, to get the object
5999 properly initialized.
6001 Constructors can only appear in the following contexts:
6004 @itemize *
6006 @item 
6007 On the right side of an initialization of an object of type @code{T}.
6009 @item 
6010 On the right side of an initialization of a record component of type @code{T}.
6012 @item 
6013 In an Ada 2005 limited aggregate.
6015 @item 
6016 In an Ada 2005 nested limited aggregate.
6018 @item 
6019 In an Ada 2005 limited aggregate that initializes an object built in
6020 place by an extended return statement.
6021 @end itemize
6023 In a declaration of an object whose type is a class imported from C++,
6024 either the default C++ constructor is implicitly called by GNAT, or
6025 else the required C++ constructor must be explicitly called in the
6026 expression that initializes the object. For example:
6028 @example
6029 Obj1 : Root;
6030 Obj2 : Root := Constructor;
6031 Obj3 : Root := Constructor (v => 10);
6032 Obj4 : Root := Constructor (30, 40);
6033 @end example
6035 The first two declarations are equivalent: in both cases the default C++
6036 constructor is invoked (in the former case the call to the constructor is
6037 implicit, and in the latter case the call is explicit in the object
6038 declaration). @code{Obj3} is initialized by the C++ non-default constructor
6039 that takes an integer argument, and @code{Obj4} is initialized by the
6040 non-default C++ constructor that takes two integers.
6042 Let us derive the imported C++ class in the Ada side. For example:
6044 @example
6045 type DT is new Root with record
6046    C_Value : Natural := 2009;
6047 end record;
6048 @end example
6050 In this case the components DT inherited from the C++ side must be
6051 initialized by a C++ constructor, and the additional Ada components
6052 of type DT are initialized by GNAT. The initialization of such an
6053 object is done either by default, or by means of a function returning
6054 an aggregate of type DT, or by means of an extension aggregate.
6056 @example
6057 Obj5 : DT;
6058 Obj6 : DT := Function_Returning_DT (50);
6059 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6060 @end example
6062 The declaration of @code{Obj5} invokes the default constructors: the
6063 C++ default constructor of the parent type takes care of the initialization
6064 of the components inherited from Root, and GNAT takes care of the default
6065 initialization of the additional Ada components of type DT (that is,
6066 @code{C_Value} is initialized to value 2009). The order of invocation of
6067 the constructors is consistent with the order of elaboration required by
6068 Ada and C++. That is, the constructor of the parent type is always called
6069 before the constructor of the derived type.
6071 Let us now consider a record that has components whose type is imported
6072 from C++. For example:
6074 @example
6075 type Rec1 is limited record
6076    Data1 : Root := Constructor (10);
6077    Value : Natural := 1000;
6078 end record;
6080 type Rec2 (D : Integer := 20) is limited record
6081    Rec   : Rec1;
6082    Data2 : Root := Constructor (D, 30);
6083 end record;
6084 @end example
6086 The initialization of an object of type @code{Rec2} will call the
6087 non-default C++ constructors specified for the imported components.
6088 For example:
6090 @example
6091 Obj8 : Rec2 (40);
6092 @end example
6094 Using Ada 2005 we can use limited aggregates to initialize an object
6095 invoking C++ constructors that differ from those specified in the type
6096 declarations. For example:
6098 @example
6099 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6100                         others => <>),
6101                 others => <>);
6102 @end example
6104 The above declaration uses an Ada 2005 limited aggregate to
6105 initialize @code{Obj9}, and the C++ constructor that has two integer
6106 arguments is invoked to initialize the @code{Data1} component instead
6107 of the constructor specified in the declaration of type @code{Rec1}. In
6108 Ada 2005 the box in the aggregate indicates that unspecified components
6109 are initialized using the expression (if any) available in the component
6110 declaration. That is, in this case discriminant @code{D} is initialized
6111 to value @code{20}, @code{Value} is initialized to value 1000, and the
6112 non-default C++ constructor that handles two integers takes care of
6113 initializing component @code{Data2} with values @code{20,30}.
6115 In Ada 2005 we can use the extended return statement to build the Ada
6116 equivalent to C++ non-default constructors. For example:
6118 @example
6119 function Constructor (V : Integer) return Rec2 is
6120 begin
6121    return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
6122                                  others => <>),
6123                          others => <>) do
6124       --  Further actions required for construction of
6125       --  objects of type Rec2
6126       ...
6127    end record;
6128 end Constructor;
6129 @end example
6131 In this example the extended return statement construct is used to
6132 build in place the returned object whose components are initialized
6133 by means of a limited aggregate. Any further action associated with
6134 the constructor can be placed inside the construct.
6136 @node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6137 @anchor{gnat_ugn/the_gnat_compilation_model id69}@anchor{af}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-at-the-class-level}@anchor{ae}
6138 @subsubsection Interfacing with C++ at the Class Level
6141 In this section we demonstrate the GNAT features for interfacing with
6142 C++ by means of an example making use of Ada 2005 abstract interface
6143 types. This example consists of a classification of animals; classes
6144 have been used to model our main classification of animals, and
6145 interfaces provide support for the management of secondary
6146 classifications. We first demonstrate a case in which the types and
6147 constructors are defined on the C++ side and imported from the Ada
6148 side, and latter the reverse case.
6150 The root of our derivation will be the @code{Animal} class, with a
6151 single private attribute (the @code{Age} of the animal), a constructor,
6152 and two public primitives to set and get the value of this attribute.
6154 @example
6155 class Animal @{
6156  public:
6157    virtual void Set_Age (int New_Age);
6158    virtual int Age ();
6159    Animal() @{Age_Count = 0;@};
6160  private:
6161    int Age_Count;
6163 @end example
6165 Abstract interface types are defined in C++ by means of classes with pure
6166 virtual functions and no data members. In our example we will use two
6167 interfaces that provide support for the common management of @code{Carnivore}
6168 and @code{Domestic} animals:
6170 @example
6171 class Carnivore @{
6172 public:
6173    virtual int Number_Of_Teeth () = 0;
6176 class Domestic @{
6177 public:
6178    virtual void Set_Owner (char* Name) = 0;
6180 @end example
6182 Using these declarations, we can now say that a @code{Dog} is an animal that is
6183 both Carnivore and Domestic, that is:
6185 @example
6186 class Dog : Animal, Carnivore, Domestic @{
6187  public:
6188    virtual int  Number_Of_Teeth ();
6189    virtual void Set_Owner (char* Name);
6191    Dog(); // Constructor
6192  private:
6193    int  Tooth_Count;
6194    char *Owner;
6196 @end example
6198 In the following examples we will assume that the previous declarations are
6199 located in a file named @code{animals.h}. The following package demonstrates
6200 how to import these C++ declarations from the Ada side:
6202 @example
6203 with Interfaces.C.Strings; use Interfaces.C.Strings;
6204 package Animals is
6205   type Carnivore is limited interface;
6206   pragma Convention (C_Plus_Plus, Carnivore);
6207   function Number_Of_Teeth (X : Carnivore)
6208      return Natural is abstract;
6210   type Domestic is limited interface;
6211   pragma Convention (C_Plus_Plus, Domestic);
6212   procedure Set_Owner
6213     (X    : in out Domestic;
6214      Name : Chars_Ptr) is abstract;
6216   type Animal is tagged limited record
6217     Age : Natural;
6218   end record;
6219   pragma Import (C_Plus_Plus, Animal);
6221   procedure Set_Age (X : in out Animal; Age : Integer);
6222   pragma Import (C_Plus_Plus, Set_Age);
6224   function Age (X : Animal) return Integer;
6225   pragma Import (C_Plus_Plus, Age);
6227   function New_Animal return Animal;
6228   pragma CPP_Constructor (New_Animal);
6229   pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6231   type Dog is new Animal and Carnivore and Domestic with record
6232     Tooth_Count : Natural;
6233     Owner       : Chars_Ptr;
6234   end record;
6235   pragma Import (C_Plus_Plus, Dog);
6237   function Number_Of_Teeth (A : Dog) return Natural;
6238   pragma Import (C_Plus_Plus, Number_Of_Teeth);
6240   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6241   pragma Import (C_Plus_Plus, Set_Owner);
6243   function New_Dog return Dog;
6244   pragma CPP_Constructor (New_Dog);
6245   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6246 end Animals;
6247 @end example
6249 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6250 interfacing with these C++ classes is easy. The only requirement is that all
6251 the primitives and components must be declared exactly in the same order in
6252 the two languages.
6254 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6255 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
6256 the arguments to the called primitives will be the same as for C++. For the
6257 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
6258 to indicate that they have been defined on the C++ side; this is required
6259 because the dispatch table associated with these tagged types will be built
6260 in the C++ side and therefore will not contain the predefined Ada primitives
6261 which Ada would otherwise expect.
6263 As the reader can see there is no need to indicate the C++ mangled names
6264 associated with each subprogram because it is assumed that all the calls to
6265 these primitives will be dispatching calls. The only exception is the
6266 constructor, which must be registered with the compiler by means of
6267 @code{pragma CPP_Constructor} and needs to provide its associated C++
6268 mangled name because the Ada compiler generates direct calls to it.
6270 With the above packages we can now declare objects of type Dog on the Ada side
6271 and dispatch calls to the corresponding subprograms on the C++ side. We can
6272 also extend the tagged type Dog with further fields and primitives, and
6273 override some of its C++ primitives on the Ada side. For example, here we have
6274 a type derivation defined on the Ada side that inherits all the dispatching
6275 primitives of the ancestor from the C++ side.
6277 @example
6278 with Animals; use Animals;
6279 package Vaccinated_Animals is
6280   type Vaccinated_Dog is new Dog with null record;
6281   function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6282 end Vaccinated_Animals;
6283 @end example
6285 It is important to note that, because of the ABI compatibility, the programmer
6286 does not need to add any further information to indicate either the object
6287 layout or the dispatch table entry associated with each dispatching operation.
6289 Now let us define all the types and constructors on the Ada side and export
6290 them to C++, using the same hierarchy of our previous example:
6292 @example
6293 with Interfaces.C.Strings;
6294 use Interfaces.C.Strings;
6295 package Animals is
6296   type Carnivore is limited interface;
6297   pragma Convention (C_Plus_Plus, Carnivore);
6298   function Number_Of_Teeth (X : Carnivore)
6299      return Natural is abstract;
6301   type Domestic is limited interface;
6302   pragma Convention (C_Plus_Plus, Domestic);
6303   procedure Set_Owner
6304     (X    : in out Domestic;
6305      Name : Chars_Ptr) is abstract;
6307   type Animal is tagged record
6308     Age : Natural;
6309   end record;
6310   pragma Convention (C_Plus_Plus, Animal);
6312   procedure Set_Age (X : in out Animal; Age : Integer);
6313   pragma Export (C_Plus_Plus, Set_Age);
6315   function Age (X : Animal) return Integer;
6316   pragma Export (C_Plus_Plus, Age);
6318   function New_Animal return Animal'Class;
6319   pragma Export (C_Plus_Plus, New_Animal);
6321   type Dog is new Animal and Carnivore and Domestic with record
6322     Tooth_Count : Natural;
6323     Owner       : String (1 .. 30);
6324   end record;
6325   pragma Convention (C_Plus_Plus, Dog);
6327   function Number_Of_Teeth (A : Dog) return Natural;
6328   pragma Export (C_Plus_Plus, Number_Of_Teeth);
6330   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6331   pragma Export (C_Plus_Plus, Set_Owner);
6333   function New_Dog return Dog'Class;
6334   pragma Export (C_Plus_Plus, New_Dog);
6335 end Animals;
6336 @end example
6338 Compared with our previous example the only differences are the use of
6339 @code{pragma Convention} (instead of @code{pragma Import}), and the use of
6340 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
6341 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6342 nothing else to be done; as explained above, the only requirement is that all
6343 the primitives and components are declared in exactly the same order.
6345 For completeness, let us see a brief C++ main program that uses the
6346 declarations available in @code{animals.h} (presented in our first example) to
6347 import and use the declarations from the Ada side, properly initializing and
6348 finalizing the Ada run-time system along the way:
6350 @example
6351 #include "animals.h"
6352 #include <iostream>
6353 using namespace std;
6355 void Check_Carnivore (Carnivore *obj) @{...@}
6356 void Check_Domestic (Domestic *obj)   @{...@}
6357 void Check_Animal (Animal *obj)       @{...@}
6358 void Check_Dog (Dog *obj)             @{...@}
6360 extern "C" @{
6361   void adainit (void);
6362   void adafinal (void);
6363   Dog* new_dog ();
6366 void test ()
6368   Dog *obj = new_dog();  // Ada constructor
6369   Check_Carnivore (obj); // Check secondary DT
6370   Check_Domestic (obj);  // Check secondary DT
6371   Check_Animal (obj);    // Check primary DT
6372   Check_Dog (obj);       // Check primary DT
6375 int main ()
6377   adainit ();  test();  adafinal ();
6378   return 0;
6380 @end example
6382 @node Generating Ada Bindings for C and C++ headers,Generating C Headers for Ada Specifications,Building Mixed Ada and C++ Programs,Mixed Language Programming
6383 @anchor{gnat_ugn/the_gnat_compilation_model generating-ada-bindings-for-c-and-c-headers}@anchor{a7}@anchor{gnat_ugn/the_gnat_compilation_model id70}@anchor{b0}
6384 @subsection Generating Ada Bindings for C and C++ headers
6387 @geindex Binding generation (for C and C++ headers)
6389 @geindex C headers (binding generation)
6391 @geindex C++ headers (binding generation)
6393 GNAT includes a binding generator for C and C++ headers which is
6394 intended to do 95% of the tedious work of generating Ada specs from C
6395 or C++ header files.
6397 Note that this capability is not intended to generate 100% correct Ada specs,
6398 and will is some cases require manual adjustments, although it can often
6399 be used out of the box in practice.
6401 Some of the known limitations include:
6404 @itemize *
6406 @item 
6407 only very simple character constant macros are translated into Ada
6408 constants. Function macros (macros with arguments) are partially translated
6409 as comments, to be completed manually if needed.
6411 @item 
6412 some extensions (e.g. vector types) are not supported
6414 @item 
6415 pointers to pointers are mapped to System.Address
6417 @item 
6418 identifiers with identical name (except casing) may generate compilation
6419 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
6420 @end itemize
6422 The code is generated using Ada 2012 syntax, which makes it easier to interface
6423 with other languages. In most cases you can still use the generated binding
6424 even if your code is compiled using earlier versions of Ada (e.g. @code{-gnat95}).
6426 @menu
6427 * Running the Binding Generator:: 
6428 * Generating Bindings for C++ Headers:: 
6429 * Switches:: 
6431 @end menu
6433 @node Running the Binding Generator,Generating Bindings for C++ Headers,,Generating Ada Bindings for C and C++ headers
6434 @anchor{gnat_ugn/the_gnat_compilation_model id71}@anchor{b1}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{b2}
6435 @subsubsection Running the Binding Generator
6438 The binding generator is part of the @code{gcc} compiler and can be
6439 invoked via the @code{-fdump-ada-spec} switch, which will generate Ada
6440 spec files for the header files specified on the command line, and all
6441 header files needed by these files transitively. For example:
6443 @example
6444 $ gcc -c -fdump-ada-spec -C /usr/include/time.h
6445 $ gcc -c *.ads
6446 @end example
6448 will generate, under GNU/Linux, the following files: @code{time_h.ads},
6449 @code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6450 correspond to the files @code{/usr/include/time.h},
6451 @code{/usr/include/bits/time.h}, etc…, and then compile these Ada specs.
6452 That is to say, the name of the Ada specs is in keeping with the relative path
6453 under @code{/usr/include/} of the header files. This behavior is specific to
6454 paths ending with @code{/include/}; in all the other cases, the name of the
6455 Ada specs is derived from the simple name of the header files instead.
6457 The @code{-C} switch tells @code{gcc} to extract comments from headers,
6458 and will attempt to generate corresponding Ada comments.
6460 If you want to generate a single Ada file and not the transitive closure, you
6461 can use instead the @code{-fdump-ada-spec-slim} switch.
6463 You can optionally specify a parent unit, of which all generated units will
6464 be children, using @code{-fada-spec-parent=@emph{unit}}.
6466 The simple @code{gcc}-based command works only for C headers. For C++ headers
6467 you need to use either the @code{g++} command or the combination @code{gcc -x c++}.
6469 In some cases, the generated bindings will be more complete or more meaningful
6470 when defining some macros, which you can do via the @code{-D} switch. This
6471 is for example the case with @code{Xlib.h} under GNU/Linux:
6473 @example
6474 $ gcc -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6475 @end example
6477 The above will generate more complete bindings than a straight call without
6478 the @code{-DXLIB_ILLEGAL_ACCESS} switch.
6480 In other cases, it is not possible to parse a header file in a stand-alone
6481 manner, because other include files need to be included first. In this
6482 case, the solution is to create a small header file including the needed
6483 @code{#include} and possible @code{#define} directives. For example, to
6484 generate Ada bindings for @code{readline/readline.h}, you need to first
6485 include @code{stdio.h}, so you can create a file with the following two
6486 lines in e.g. @code{readline1.h}:
6488 @example
6489 #include <stdio.h>
6490 #include <readline/readline.h>
6491 @end example
6493 and then generate Ada bindings from this file:
6495 @example
6496 $ gcc -c -fdump-ada-spec readline1.h
6497 @end example
6499 @node Generating Bindings for C++ Headers,Switches,Running the Binding Generator,Generating Ada Bindings for C and C++ headers
6500 @anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{b3}@anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{b4}
6501 @subsubsection Generating Bindings for C++ Headers
6504 Generating bindings for C++ headers is done using the same options, always
6505 with the @emph{g++} compiler. Note that generating Ada spec from C++ headers is a
6506 much more complex job and support for C++ headers is much more limited that
6507 support for C headers. As a result, you will need to modify the resulting
6508 bindings by hand more extensively when using C++ headers.
6510 In this mode, C++ classes will be mapped to Ada tagged types, constructors
6511 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
6512 multiple inheritance of abstract classes will be mapped to Ada interfaces
6513 (see the @emph{Interfacing to C++} section in the @cite{GNAT Reference Manual}
6514 for additional information on interfacing to C++).
6516 For example, given the following C++ header file:
6518 @example
6519 class Carnivore @{
6520 public:
6521    virtual int Number_Of_Teeth () = 0;
6524 class Domestic @{
6525 public:
6526    virtual void Set_Owner (char* Name) = 0;
6529 class Animal @{
6530 public:
6531   int Age_Count;
6532   virtual void Set_Age (int New_Age);
6535 class Dog : Animal, Carnivore, Domestic @{
6536  public:
6537   int  Tooth_Count;
6538   char *Owner;
6540   virtual int  Number_Of_Teeth ();
6541   virtual void Set_Owner (char* Name);
6543   Dog();
6545 @end example
6547 The corresponding Ada code is generated:
6549 @example
6550 package Class_Carnivore is
6551   type Carnivore is limited interface;
6552   pragma Import (CPP, Carnivore);
6554   function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6555 end;
6556 use Class_Carnivore;
6558 package Class_Domestic is
6559   type Domestic is limited interface;
6560   pragma Import (CPP, Domestic);
6562   procedure Set_Owner
6563     (this : access Domestic;
6564      Name : Interfaces.C.Strings.chars_ptr) is abstract;
6565 end;
6566 use Class_Domestic;
6568 package Class_Animal is
6569   type Animal is tagged limited record
6570     Age_Count : aliased int;
6571   end record;
6572   pragma Import (CPP, Animal);
6574   procedure Set_Age (this : access Animal; New_Age : int);
6575   pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6576 end;
6577 use Class_Animal;
6579 package Class_Dog is
6580   type Dog is new Animal and Carnivore and Domestic with record
6581     Tooth_Count : aliased int;
6582     Owner : Interfaces.C.Strings.chars_ptr;
6583   end record;
6584   pragma Import (CPP, Dog);
6586   function Number_Of_Teeth (this : access Dog) return int;
6587   pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6589   procedure Set_Owner
6590     (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6591   pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6593   function New_Dog return Dog;
6594   pragma CPP_Constructor (New_Dog);
6595   pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6596 end;
6597 use Class_Dog;
6598 @end example
6600 @node Switches,,Generating Bindings for C++ Headers,Generating Ada Bindings for C and C++ headers
6601 @anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{b5}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{b6}
6602 @subsubsection Switches
6605 @geindex -fdump-ada-spec (gcc)
6608 @table @asis
6610 @item @code{-fdump-ada-spec}
6612 Generate Ada spec files for the given header files transitively (including
6613 all header files that these headers depend upon).
6614 @end table
6616 @geindex -fdump-ada-spec-slim (gcc)
6619 @table @asis
6621 @item @code{-fdump-ada-spec-slim}
6623 Generate Ada spec files for the header files specified on the command line
6624 only.
6625 @end table
6627 @geindex -fada-spec-parent (gcc)
6630 @table @asis
6632 @item @code{-fada-spec-parent=@emph{unit}}
6634 Specifies that all files generated by @code{-fdump-ada-spec} are
6635 to be child units of the specified parent unit.
6636 @end table
6638 @geindex -C (gcc)
6641 @table @asis
6643 @item @code{-C}
6645 Extract comments from headers and generate Ada comments in the Ada spec files.
6646 @end table
6648 @node Generating C Headers for Ada Specifications,,Generating Ada Bindings for C and C++ headers,Mixed Language Programming
6649 @anchor{gnat_ugn/the_gnat_compilation_model generating-c-headers-for-ada-specifications}@anchor{b7}@anchor{gnat_ugn/the_gnat_compilation_model id73}@anchor{b8}
6650 @subsection Generating C Headers for Ada Specifications
6653 @geindex Binding generation (for Ada specs)
6655 @geindex C headers (binding generation)
6657 GNAT includes a C header generator for Ada specifications which supports
6658 Ada types that have a direct mapping to C types. This includes in particular
6659 support for:
6662 @itemize *
6664 @item 
6665 Scalar types
6667 @item 
6668 Constrained arrays
6670 @item 
6671 Records (untagged)
6673 @item 
6674 Composition of the above types
6676 @item 
6677 Constant declarations
6679 @item 
6680 Object declarations
6682 @item 
6683 Subprogram declarations
6684 @end itemize
6686 @menu
6687 * Running the C Header Generator:: 
6689 @end menu
6691 @node Running the C Header Generator,,,Generating C Headers for Ada Specifications
6692 @anchor{gnat_ugn/the_gnat_compilation_model running-the-c-header-generator}@anchor{b9}
6693 @subsubsection Running the C Header Generator
6696 The C header generator is part of the GNAT compiler and can be invoked via
6697 the @code{-gnatceg} combination of switches, which will generate a @code{.h}
6698 file corresponding to the given input file (Ada spec or body). Note that
6699 only spec files are processed in any case, so giving a spec or a body file
6700 as input is equivalent. For example:
6702 @example
6703 $ gcc -c -gnatceg pack1.ads
6704 @end example
6706 will generate a self-contained file called @code{pack1.h} including
6707 common definitions from the Ada Standard package, followed by the
6708 definitions included in @code{pack1.ads}, as well as all the other units
6709 withed by this file.
6711 For instance, given the following Ada files:
6713 @example
6714 package Pack2 is
6715    type Int is range 1 .. 10;
6716 end Pack2;
6717 @end example
6719 @example
6720 with Pack2;
6722 package Pack1 is
6723    type Rec is record
6724       Field1, Field2 : Pack2.Int;
6725    end record;
6727    Global : Rec := (1, 2);
6729    procedure Proc1 (R : Rec);
6730    procedure Proc2 (R : in out Rec);
6731 end Pack1;
6732 @end example
6734 The above @code{gcc} command will generate the following @code{pack1.h} file:
6736 @example
6737 /* Standard definitions skipped */
6738 #ifndef PACK2_ADS
6739 #define PACK2_ADS
6740 typedef short_short_integer pack2__TintB;
6741 typedef pack2__TintB pack2__int;
6742 #endif /* PACK2_ADS */
6744 #ifndef PACK1_ADS
6745 #define PACK1_ADS
6746 typedef struct _pack1__rec @{
6747   pack2__int field1;
6748   pack2__int field2;
6749 @} pack1__rec;
6750 extern pack1__rec pack1__global;
6751 extern void pack1__proc1(const pack1__rec r);
6752 extern void pack1__proc2(pack1__rec *r);
6753 #endif /* PACK1_ADS */
6754 @end example
6756 You can then @code{include} @code{pack1.h} from a C source file and use the types,
6757 call subprograms, reference objects, and constants.
6759 @node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
6760 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{2d}@anchor{gnat_ugn/the_gnat_compilation_model id74}@anchor{ba}
6761 @section GNAT and Other Compilation Models
6764 This section compares the GNAT model with the approaches taken in
6765 other environments, first the C/C++ model and then the mechanism that
6766 has been used in other Ada systems, in particular those traditionally
6767 used for Ada 83.
6769 @menu
6770 * Comparison between GNAT and C/C++ Compilation Models:: 
6771 * Comparison between GNAT and Conventional Ada Library Models:: 
6773 @end menu
6775 @node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
6776 @anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-c-c-compilation-models}@anchor{bb}@anchor{gnat_ugn/the_gnat_compilation_model id75}@anchor{bc}
6777 @subsection Comparison between GNAT and C/C++ Compilation Models
6780 The GNAT model of compilation is close to the C and C++ models. You can
6781 think of Ada specs as corresponding to header files in C. As in C, you
6782 don’t need to compile specs; they are compiled when they are used. The
6783 Ada @emph{with} is similar in effect to the @code{#include} of a C
6784 header.
6786 One notable difference is that, in Ada, you may compile specs separately
6787 to check them for semantic and syntactic accuracy. This is not always
6788 possible with C headers because they are fragments of programs that have
6789 less specific syntactic or semantic rules.
6791 The other major difference is the requirement for running the binder,
6792 which performs two important functions. First, it checks for
6793 consistency. In C or C++, the only defense against assembling
6794 inconsistent programs lies outside the compiler, in a makefile, for
6795 example. The binder satisfies the Ada requirement that it be impossible
6796 to construct an inconsistent program when the compiler is used in normal
6797 mode.
6799 @geindex Elaboration order control
6801 The other important function of the binder is to deal with elaboration
6802 issues. There are also elaboration issues in C++ that are handled
6803 automatically. This automatic handling has the advantage of being
6804 simpler to use, but the C++ programmer has no control over elaboration.
6805 Where @code{gnatbind} might complain there was no valid order of
6806 elaboration, a C++ compiler would simply construct a program that
6807 malfunctioned at run time.
6809 @node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
6810 @anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-conventional-ada-library-models}@anchor{bd}@anchor{gnat_ugn/the_gnat_compilation_model id76}@anchor{be}
6811 @subsection Comparison between GNAT and Conventional Ada Library Models
6814 This section is intended for Ada programmers who have
6815 used an Ada compiler implementing the traditional Ada library
6816 model, as described in the Ada Reference Manual.
6818 @geindex GNAT library
6820 In GNAT, there is no ‘library’ in the normal sense. Instead, the set of
6821 source files themselves acts as the library. Compiling Ada programs does
6822 not generate any centralized information, but rather an object file and
6823 a ALI file, which are of interest only to the binder and linker.
6824 In a traditional system, the compiler reads information not only from
6825 the source file being compiled, but also from the centralized library.
6826 This means that the effect of a compilation depends on what has been
6827 previously compiled. In particular:
6830 @itemize *
6832 @item 
6833 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
6834 to the version of the unit most recently compiled into the library.
6836 @item 
6837 Inlining is effective only if the necessary body has already been
6838 compiled into the library.
6840 @item 
6841 Compiling a unit may obsolete other units in the library.
6842 @end itemize
6844 In GNAT, compiling one unit never affects the compilation of any other
6845 units because the compiler reads only source files. Only changes to source
6846 files can affect the results of a compilation. In particular:
6849 @itemize *
6851 @item 
6852 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
6853 to the source version of the unit that is currently accessible to the
6854 compiler.
6856 @geindex Inlining
6858 @item 
6859 Inlining requires the appropriate source files for the package or
6860 subprogram bodies to be available to the compiler. Inlining is always
6861 effective, independent of the order in which units are compiled.
6863 @item 
6864 Compiling a unit never affects any other compilations. The editing of
6865 sources may cause previous compilations to be out of date if they
6866 depended on the source file being modified.
6867 @end itemize
6869 The most important result of these differences is that order of compilation
6870 is never significant in GNAT. There is no situation in which one is
6871 required to do one compilation before another. What shows up as order of
6872 compilation requirements in the traditional Ada library becomes, in
6873 GNAT, simple source dependencies; in other words, there is only a set
6874 of rules saying what source files must be present when a file is
6875 compiled.
6877 @node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
6878 @anchor{gnat_ugn/the_gnat_compilation_model id77}@anchor{bf}@anchor{gnat_ugn/the_gnat_compilation_model using-gnat-files-with-external-tools}@anchor{2e}
6879 @section Using GNAT Files with External Tools
6882 This section explains how files that are produced by GNAT may be
6883 used with tools designed for other languages.
6885 @menu
6886 * Using Other Utility Programs with GNAT:: 
6887 * The External Symbol Naming Scheme of GNAT:: 
6889 @end menu
6891 @node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
6892 @anchor{gnat_ugn/the_gnat_compilation_model id78}@anchor{c0}@anchor{gnat_ugn/the_gnat_compilation_model using-other-utility-programs-with-gnat}@anchor{c1}
6893 @subsection Using Other Utility Programs with GNAT
6896 The object files generated by GNAT are in standard system format and in
6897 particular the debugging information uses this format. This means
6898 programs generated by GNAT can be used with existing utilities that
6899 depend on these formats.
6901 In general, any utility program that works with C will also often work with
6902 Ada programs generated by GNAT. This includes software utilities such as
6903 gprof (a profiling program), gdb (the FSF debugger), and utilities such
6904 as Purify.
6906 @node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
6907 @anchor{gnat_ugn/the_gnat_compilation_model id79}@anchor{c2}@anchor{gnat_ugn/the_gnat_compilation_model the-external-symbol-naming-scheme-of-gnat}@anchor{c3}
6908 @subsection The External Symbol Naming Scheme of GNAT
6911 In order to interpret the output from GNAT, when using tools that are
6912 originally intended for use with other languages, it is useful to
6913 understand the conventions used to generate link names from the Ada
6914 entity names.
6916 All link names are in all lowercase letters. With the exception of library
6917 procedure names, the mechanism used is simply to use the full expanded
6918 Ada name with dots replaced by double underscores. For example, suppose
6919 we have the following package spec:
6921 @example
6922 package QRS is
6923    MN : Integer;
6924 end QRS;
6925 @end example
6927 @geindex pragma Export
6929 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
6930 the corresponding link name is @code{qrs__mn}.
6931 Of course if a @code{pragma Export} is used this may be overridden:
6933 @example
6934 package Exports is
6935    Var1 : Integer;
6936    pragma Export (Var1, C, External_Name => "var1_name");
6937    Var2 : Integer;
6938    pragma Export (Var2, C, Link_Name => "var2_link_name");
6939 end Exports;
6940 @end example
6942 In this case, the link name for @code{Var1} is whatever link name the
6943 C compiler would assign for the C function @code{var1_name}. This typically
6944 would be either @code{var1_name} or @code{_var1_name}, depending on operating
6945 system conventions, but other possibilities exist. The link name for
6946 @code{Var2} is @code{var2_link_name}, and this is not operating system
6947 dependent.
6949 One exception occurs for library level procedures. A potential ambiguity
6950 arises between the required name @code{_main} for the C main program,
6951 and the name we would otherwise assign to an Ada library level procedure
6952 called @code{Main} (which might well not be the main program).
6954 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
6955 names. So if we have a library level procedure such as:
6957 @example
6958 procedure Hello (S : String);
6959 @end example
6961 the external name of this procedure will be @code{_ada_hello}.
6963 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
6965 @node Building Executable Programs with GNAT,GNAT Utility Programs,The GNAT Compilation Model,Top
6966 @anchor{gnat_ugn/building_executable_programs_with_gnat doc}@anchor{c4}@anchor{gnat_ugn/building_executable_programs_with_gnat building-executable-programs-with-gnat}@anchor{a}@anchor{gnat_ugn/building_executable_programs_with_gnat id1}@anchor{c5}
6967 @chapter Building Executable Programs with GNAT
6970 This chapter describes first the gnatmake tool
6971 (@ref{c6,,Building with gnatmake}),
6972 which automatically determines the set of sources
6973 needed by an Ada compilation unit and executes the necessary
6974 (re)compilations, binding and linking.
6975 It also explains how to use each tool individually: the
6976 compiler (gcc, see @ref{c7,,Compiling with gcc}),
6977 binder (gnatbind, see @ref{c8,,Binding with gnatbind}),
6978 and linker (gnatlink, see @ref{c9,,Linking with gnatlink})
6979 to build executable programs.
6980 Finally, this chapter provides examples of
6981 how to make use of the general GNU make mechanism
6982 in a GNAT context (see @ref{70,,Using the GNU make Utility}).
6985 @menu
6986 * Building with gnatmake:: 
6987 * Compiling with gcc:: 
6988 * Compiler Switches:: 
6989 * Linker Switches:: 
6990 * Binding with gnatbind:: 
6991 * Linking with gnatlink:: 
6992 * Using the GNU make Utility:: 
6994 @end menu
6996 @node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
6997 @anchor{gnat_ugn/building_executable_programs_with_gnat building-with-gnatmake}@anchor{ca}@anchor{gnat_ugn/building_executable_programs_with_gnat the-gnat-make-program-gnatmake}@anchor{c6}
6998 @section Building with @code{gnatmake}
7001 @geindex gnatmake
7003 A typical development cycle when working on an Ada program consists of
7004 the following steps:
7007 @enumerate 
7009 @item 
7010 Edit some sources to fix bugs;
7012 @item 
7013 Add enhancements;
7015 @item 
7016 Compile all sources affected;
7018 @item 
7019 Rebind and relink; and
7021 @item 
7022 Test.
7023 @end enumerate
7025 @geindex Dependency rules (compilation)
7027 The third step in particular can be tricky, because not only do the modified
7028 files have to be compiled, but any files depending on these files must also be
7029 recompiled. The dependency rules in Ada can be quite complex, especially
7030 in the presence of overloading, @code{use} clauses, generics and inlined
7031 subprograms.
7033 @code{gnatmake} automatically takes care of the third and fourth steps
7034 of this process. It determines which sources need to be compiled,
7035 compiles them, and binds and links the resulting object files.
7037 Unlike some other Ada make programs, the dependencies are always
7038 accurately recomputed from the new sources. The source based approach of
7039 the GNAT compilation model makes this possible. This means that if
7040 changes to the source program cause corresponding changes in
7041 dependencies, they will always be tracked exactly correctly by
7042 @code{gnatmake}.
7044 Note that for advanced forms of project structure, we recommend creating
7045 a project file as explained in the @emph{GNAT_Project_Manager} chapter in the
7046 @emph{GPRbuild User’s Guide}, and using the
7047 @code{gprbuild} tool which supports building with project files and works similarly
7048 to @code{gnatmake}.
7050 @menu
7051 * Running gnatmake:: 
7052 * Switches for gnatmake:: 
7053 * Mode Switches for gnatmake:: 
7054 * Notes on the Command Line:: 
7055 * How gnatmake Works:: 
7056 * Examples of gnatmake Usage:: 
7058 @end menu
7060 @node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7061 @anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{cb}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{cc}
7062 @subsection Running @code{gnatmake}
7065 The usual form of the @code{gnatmake} command is
7067 @example
7068 $ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7069 @end example
7071 The only required argument is one @code{file_name}, which specifies
7072 a compilation unit that is a main program. Several @code{file_names} can be
7073 specified: this will result in several executables being built.
7074 If @code{switches} are present, they can be placed before the first
7075 @code{file_name}, between @code{file_names} or after the last @code{file_name}.
7076 If @code{mode_switches} are present, they must always be placed after
7077 the last @code{file_name} and all @code{switches}.
7079 If you are using standard file extensions (@code{.adb} and
7080 @code{.ads}), then the
7081 extension may be omitted from the @code{file_name} arguments. However, if
7082 you are using non-standard extensions, then it is required that the
7083 extension be given. A relative or absolute directory path can be
7084 specified in a @code{file_name}, in which case, the input source file will
7085 be searched for in the specified directory only. Otherwise, the input
7086 source file will first be searched in the directory where
7087 @code{gnatmake} was invoked and if it is not found, it will be search on
7088 the source path of the compiler as described in
7089 @ref{73,,Search Paths and the Run-Time Library (RTL)}.
7091 All @code{gnatmake} output (except when you specify @code{-M}) is sent to
7092 @code{stderr}. The output produced by the
7093 @code{-M} switch is sent to @code{stdout}.
7095 @node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7096 @anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{cd}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{ce}
7097 @subsection Switches for @code{gnatmake}
7100 You may specify any of the following switches to @code{gnatmake}:
7102 @geindex --version (gnatmake)
7105 @table @asis
7107 @item @code{--version}
7109 Display Copyright and version, then exit disregarding all other options.
7110 @end table
7112 @geindex --help (gnatmake)
7115 @table @asis
7117 @item @code{--help}
7119 If @code{--version} was not used, display usage, then exit disregarding
7120 all other options.
7121 @end table
7123 @geindex --GCC=compiler_name (gnatmake)
7126 @table @asis
7128 @item @code{--GCC=@emph{compiler_name}}
7130 Program used for compiling. The default is @code{gcc}. You need to use
7131 quotes around @code{compiler_name} if @code{compiler_name} contains
7132 spaces or other separator characters.
7133 As an example @code{--GCC="foo -x  -y"}
7134 will instruct @code{gnatmake} to use @code{foo -x -y} as your
7135 compiler. A limitation of this syntax is that the name and path name of
7136 the executable itself must not include any embedded spaces. Note that
7137 switch @code{-c} is always inserted after your command name. Thus in the
7138 above example the compiler command that will be used by @code{gnatmake}
7139 will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7140 used, only the last @code{compiler_name} is taken into account. However,
7141 all the additional switches are also taken into account. Thus,
7142 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7143 @code{--GCC="bar -x -y -z -t"}.
7144 @end table
7146 @geindex --GNATBIND=binder_name (gnatmake)
7149 @table @asis
7151 @item @code{--GNATBIND=@emph{binder_name}}
7153 Program used for binding. The default is @code{gnatbind}. You need to
7154 use quotes around @code{binder_name} if @code{binder_name} contains spaces
7155 or other separator characters.
7156 As an example @code{--GNATBIND="bar -x  -y"}
7157 will instruct @code{gnatmake} to use @code{bar -x -y} as your
7158 binder. Binder switches that are normally appended by @code{gnatmake}
7159 to @code{gnatbind} are now appended to the end of @code{bar -x -y}.
7160 A limitation of this syntax is that the name and path name of the executable
7161 itself must not include any embedded spaces.
7162 @end table
7164 @geindex --GNATLINK=linker_name (gnatmake)
7167 @table @asis
7169 @item @code{--GNATLINK=@emph{linker_name}}
7171 Program used for linking. The default is @code{gnatlink}. You need to
7172 use quotes around @code{linker_name} if @code{linker_name} contains spaces
7173 or other separator characters.
7174 As an example @code{--GNATLINK="lan -x  -y"}
7175 will instruct @code{gnatmake} to use @code{lan -x -y} as your
7176 linker. Linker switches that are normally appended by @code{gnatmake} to
7177 @code{gnatlink} are now appended to the end of @code{lan -x -y}.
7178 A limitation of this syntax is that the name and path name of the executable
7179 itself must not include any embedded spaces.
7181 @item @code{--create-map-file}
7183 When linking an executable, create a map file. The name of the map file
7184 has the same name as the executable with extension “.map”.
7186 @item @code{--create-map-file=@emph{mapfile}}
7188 When linking an executable, create a map file with the specified name.
7189 @end table
7191 @geindex --create-missing-dirs (gnatmake)
7194 @table @asis
7196 @item @code{--create-missing-dirs}
7198 When using project files (@code{-P@emph{project}}), automatically create
7199 missing object directories, library directories and exec
7200 directories.
7202 @item @code{--single-compile-per-obj-dir}
7204 Disallow simultaneous compilations in the same object directory when
7205 project files are used.
7207 @item @code{--subdirs=@emph{subdir}}
7209 Actual object directory of each project file is the subdirectory subdir of the
7210 object directory specified or defaulted in the project file.
7212 @item @code{--unchecked-shared-lib-imports}
7214 By default, shared library projects are not allowed to import static library
7215 projects. When this switch is used on the command line, this restriction is
7216 relaxed.
7218 @item @code{--source-info=@emph{source info file}}
7220 Specify a source info file. This switch is active only when project files
7221 are used. If the source info file is specified as a relative path, then it is
7222 relative to the object directory of the main project. If the source info file
7223 does not exist, then after the Project Manager has successfully parsed and
7224 processed the project files and found the sources, it creates the source info
7225 file. If the source info file already exists and can be read successfully,
7226 then the Project Manager will get all the needed information about the sources
7227 from the source info file and will not look for them. This reduces the time
7228 to process the project files, especially when looking for sources that take a
7229 long time. If the source info file exists but cannot be parsed successfully,
7230 the Project Manager will attempt to recreate it. If the Project Manager fails
7231 to create the source info file, a message is issued, but gnatmake does not
7232 fail. @code{gnatmake} “trusts” the source info file. This means that
7233 if the source files have changed (addition, deletion, moving to a different
7234 source directory), then the source info file need to be deleted and recreated.
7235 @end table
7237 @geindex -a (gnatmake)
7240 @table @asis
7242 @item @code{-a}
7244 Consider all files in the make process, even the GNAT internal system
7245 files (for example, the predefined Ada library files), as well as any
7246 locked files. Locked files are files whose ALI file is write-protected.
7247 By default,
7248 @code{gnatmake} does not check these files,
7249 because the assumption is that the GNAT internal files are properly up
7250 to date, and also that any write protected ALI files have been properly
7251 installed. Note that if there is an installation problem, such that one
7252 of these files is not up to date, it will be properly caught by the
7253 binder.
7254 You may have to specify this switch if you are working on GNAT
7255 itself. The switch @code{-a} is also useful
7256 in conjunction with @code{-f}
7257 if you need to recompile an entire application,
7258 including run-time files, using special configuration pragmas,
7259 such as a @code{Normalize_Scalars} pragma.
7261 By default
7262 @code{gnatmake -a} compiles all GNAT
7263 internal files with
7264 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7265 @end table
7267 @geindex -b (gnatmake)
7270 @table @asis
7272 @item @code{-b}
7274 Bind only. Can be combined with @code{-c} to do
7275 compilation and binding, but no link.
7276 Can be combined with @code{-l}
7277 to do binding and linking. When not combined with
7278 @code{-c}
7279 all the units in the closure of the main program must have been previously
7280 compiled and must be up to date. The root unit specified by @code{file_name}
7281 may be given without extension, with the source extension or, if no GNAT
7282 Project File is specified, with the ALI file extension.
7283 @end table
7285 @geindex -c (gnatmake)
7288 @table @asis
7290 @item @code{-c}
7292 Compile only. Do not perform binding, except when @code{-b}
7293 is also specified. Do not perform linking, except if both
7294 @code{-b} and
7295 @code{-l} are also specified.
7296 If the root unit specified by @code{file_name} is not a main unit, this is the
7297 default. Otherwise @code{gnatmake} will attempt binding and linking
7298 unless all objects are up to date and the executable is more recent than
7299 the objects.
7300 @end table
7302 @geindex -C (gnatmake)
7305 @table @asis
7307 @item @code{-C}
7309 Use a temporary mapping file. A mapping file is a way to communicate
7310 to the compiler two mappings: from unit names to file names (without
7311 any directory information) and from file names to path names (with
7312 full directory information). A mapping file can make the compiler’s
7313 file searches faster, especially if there are many source directories,
7314 or the sources are read over a slow network connection. If
7315 @code{-P} is used, a mapping file is always used, so
7316 @code{-C} is unnecessary; in this case the mapping file
7317 is initially populated based on the project file. If
7318 @code{-C} is used without
7319 @code{-P},
7320 the mapping file is initially empty. Each invocation of the compiler
7321 will add any newly accessed sources to the mapping file.
7322 @end table
7324 @geindex -C= (gnatmake)
7327 @table @asis
7329 @item @code{-C=@emph{file}}
7331 Use a specific mapping file. The file, specified as a path name (absolute or
7332 relative) by this switch, should already exist, otherwise the switch is
7333 ineffective. The specified mapping file will be communicated to the compiler.
7334 This switch is not compatible with a project file
7335 (-P`file`) or with multiple compiling processes
7336 (-jnnn, when nnn is greater than 1).
7337 @end table
7339 @geindex -d (gnatmake)
7342 @table @asis
7344 @item @code{-d}
7346 Display progress for each source, up to date or not, as a single line:
7348 @example
7349 completed x out of y (zz%)
7350 @end example
7352 If the file needs to be compiled this is displayed after the invocation of
7353 the compiler. These lines are displayed even in quiet output mode.
7354 @end table
7356 @geindex -D (gnatmake)
7359 @table @asis
7361 @item @code{-D @emph{dir}}
7363 Put all object files and ALI file in directory @code{dir}.
7364 If the @code{-D} switch is not used, all object files
7365 and ALI files go in the current working directory.
7367 This switch cannot be used when using a project file.
7368 @end table
7370 @geindex -eI (gnatmake)
7373 @table @asis
7375 @item @code{-eI@emph{nnn}}
7377 Indicates that the main source is a multi-unit source and the rank of the unit
7378 in the source file is nnn. nnn needs to be a positive number and a valid
7379 index in the source. This switch cannot be used when @code{gnatmake} is
7380 invoked for several mains.
7381 @end table
7383 @geindex -eL (gnatmake)
7385 @geindex symbolic links
7388 @table @asis
7390 @item @code{-eL}
7392 Follow all symbolic links when processing project files.
7393 This should be used if your project uses symbolic links for files or
7394 directories, but is not needed in other cases.
7396 @geindex naming scheme
7398 This also assumes that no directory matches the naming scheme for files (for
7399 instance that you do not have a directory called “sources.ads” when using the
7400 default GNAT naming scheme).
7402 When you do not have to use this switch (i.e., by default), gnatmake is able to
7403 save a lot of system calls (several per source file and object file), which
7404 can result in a significant speed up to load and manipulate a project file,
7405 especially when using source files from a remote system.
7406 @end table
7408 @geindex -eS (gnatmake)
7411 @table @asis
7413 @item @code{-eS}
7415 Output the commands for the compiler, the binder and the linker
7416 on standard output,
7417 instead of standard error.
7418 @end table
7420 @geindex -f (gnatmake)
7423 @table @asis
7425 @item @code{-f}
7427 Force recompilations. Recompile all sources, even though some object
7428 files may be up to date, but don’t recompile predefined or GNAT internal
7429 files or locked files (files with a write-protected ALI file),
7430 unless the @code{-a} switch is also specified.
7431 @end table
7433 @geindex -F (gnatmake)
7436 @table @asis
7438 @item @code{-F}
7440 When using project files, if some errors or warnings are detected during
7441 parsing and verbose mode is not in effect (no use of switch
7442 -v), then error lines start with the full path name of the project
7443 file, rather than its simple file name.
7444 @end table
7446 @geindex -g (gnatmake)
7449 @table @asis
7451 @item @code{-g}
7453 Enable debugging. This switch is simply passed to the compiler and to the
7454 linker.
7455 @end table
7457 @geindex -i (gnatmake)
7460 @table @asis
7462 @item @code{-i}
7464 In normal mode, @code{gnatmake} compiles all object files and ALI files
7465 into the current directory. If the @code{-i} switch is used,
7466 then instead object files and ALI files that already exist are overwritten
7467 in place. This means that once a large project is organized into separate
7468 directories in the desired manner, then @code{gnatmake} will automatically
7469 maintain and update this organization. If no ALI files are found on the
7470 Ada object path (see @ref{73,,Search Paths and the Run-Time Library (RTL)}),
7471 the new object and ALI files are created in the
7472 directory containing the source being compiled. If another organization
7473 is desired, where objects and sources are kept in different directories,
7474 a useful technique is to create dummy ALI files in the desired directories.
7475 When detecting such a dummy file, @code{gnatmake} will be forced to
7476 recompile the corresponding source file, and it will be put the resulting
7477 object and ALI files in the directory where it found the dummy file.
7478 @end table
7480 @geindex -j (gnatmake)
7482 @geindex Parallel make
7485 @table @asis
7487 @item @code{-j@emph{n}}
7489 Use @code{n} processes to carry out the (re)compilations. On a multiprocessor
7490 machine compilations will occur in parallel. If @code{n} is 0, then the
7491 maximum number of parallel compilations is the number of core processors
7492 on the platform. In the event of compilation errors, messages from various
7493 compilations might get interspersed (but @code{gnatmake} will give you the
7494 full ordered list of failing compiles at the end). If this is problematic,
7495 rerun the make process with n set to 1 to get a clean list of messages.
7496 @end table
7498 @geindex -k (gnatmake)
7501 @table @asis
7503 @item @code{-k}
7505 Keep going. Continue as much as possible after a compilation error. To
7506 ease the programmer’s task in case of compilation errors, the list of
7507 sources for which the compile fails is given when @code{gnatmake}
7508 terminates.
7510 If @code{gnatmake} is invoked with several @code{file_names} and with this
7511 switch, if there are compilation errors when building an executable,
7512 @code{gnatmake} will not attempt to build the following executables.
7513 @end table
7515 @geindex -l (gnatmake)
7518 @table @asis
7520 @item @code{-l}
7522 Link only. Can be combined with @code{-b} to binding
7523 and linking. Linking will not be performed if combined with
7524 @code{-c}
7525 but not with @code{-b}.
7526 When not combined with @code{-b}
7527 all the units in the closure of the main program must have been previously
7528 compiled and must be up to date, and the main program needs to have been bound.
7529 The root unit specified by @code{file_name}
7530 may be given without extension, with the source extension or, if no GNAT
7531 Project File is specified, with the ALI file extension.
7532 @end table
7534 @geindex -m (gnatmake)
7537 @table @asis
7539 @item @code{-m}
7541 Specify that the minimum necessary amount of recompilations
7542 be performed. In this mode @code{gnatmake} ignores time
7543 stamp differences when the only
7544 modifications to a source file consist in adding/removing comments,
7545 empty lines, spaces or tabs. This means that if you have changed the
7546 comments in a source file or have simply reformatted it, using this
7547 switch will tell @code{gnatmake} not to recompile files that depend on it
7548 (provided other sources on which these files depend have undergone no
7549 semantic modifications). Note that the debugging information may be
7550 out of date with respect to the sources if the @code{-m} switch causes
7551 a compilation to be switched, so the use of this switch represents a
7552 trade-off between compilation time and accurate debugging information.
7553 @end table
7555 @geindex Dependencies
7556 @geindex producing list
7558 @geindex -M (gnatmake)
7561 @table @asis
7563 @item @code{-M}
7565 Check if all objects are up to date. If they are, output the object
7566 dependences to @code{stdout} in a form that can be directly exploited in
7567 a @code{Makefile}. By default, each source file is prefixed with its
7568 (relative or absolute) directory name. This name is whatever you
7569 specified in the various @code{-aI}
7570 and @code{-I} switches. If you use
7571 @code{gnatmake -M}  @code{-q}
7572 (see below), only the source file names,
7573 without relative paths, are output. If you just specify the  @code{-M}
7574 switch, dependencies of the GNAT internal system files are omitted. This
7575 is typically what you want. If you also specify
7576 the @code{-a} switch,
7577 dependencies of the GNAT internal files are also listed. Note that
7578 dependencies of the objects in external Ada libraries (see
7579 switch  @code{-aL@emph{dir}} in the following list)
7580 are never reported.
7581 @end table
7583 @geindex -n (gnatmake)
7586 @table @asis
7588 @item @code{-n}
7590 Don’t compile, bind, or link. Checks if all objects are up to date.
7591 If they are not, the full name of the first file that needs to be
7592 recompiled is printed.
7593 Repeated use of this option, followed by compiling the indicated source
7594 file, will eventually result in recompiling all required units.
7595 @end table
7597 @geindex -o (gnatmake)
7600 @table @asis
7602 @item @code{-o @emph{exec_name}}
7604 Output executable name. The name of the final executable program will be
7605 @code{exec_name}. If the @code{-o} switch is omitted the default
7606 name for the executable will be the name of the input file in appropriate form
7607 for an executable file on the host system.
7609 This switch cannot be used when invoking @code{gnatmake} with several
7610 @code{file_names}.
7611 @end table
7613 @geindex -p (gnatmake)
7616 @table @asis
7618 @item @code{-p}
7620 Same as @code{--create-missing-dirs}
7621 @end table
7623 @geindex -P (gnatmake)
7626 @table @asis
7628 @item @code{-P@emph{project}}
7630 Use project file @code{project}. Only one such switch can be used.
7631 @end table
7633 @c -- Comment:
7634 @c :ref:`gnatmake_and_Project_Files`.
7636 @geindex -q (gnatmake)
7639 @table @asis
7641 @item @code{-q}
7643 Quiet. When this flag is not set, the commands carried out by
7644 @code{gnatmake} are displayed.
7645 @end table
7647 @geindex -s (gnatmake)
7650 @table @asis
7652 @item @code{-s}
7654 Recompile if compiler switches have changed since last compilation.
7655 All compiler switches but -I and -o are taken into account in the
7656 following way:
7657 orders between different ‘first letter’ switches are ignored, but
7658 orders between same switches are taken into account. For example,
7659 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O}
7660 is equivalent to @code{-O -g}.
7662 This switch is recommended when Integrated Preprocessing is used.
7663 @end table
7665 @geindex -u (gnatmake)
7668 @table @asis
7670 @item @code{-u}
7672 Unique. Recompile at most the main files. It implies -c. Combined with
7673 -f, it is equivalent to calling the compiler directly. Note that using
7674 -u with a project file and no main has a special meaning.
7675 @end table
7677 @c --Comment
7678 @c (See :ref:`Project_Files_and_Main_Subprograms`.)
7680 @geindex -U (gnatmake)
7683 @table @asis
7685 @item @code{-U}
7687 When used without a project file or with one or several mains on the command
7688 line, is equivalent to -u. When used with a project file and no main
7689 on the command line, all sources of all project files are checked and compiled
7690 if not up to date, and libraries are rebuilt, if necessary.
7691 @end table
7693 @geindex -v (gnatmake)
7696 @table @asis
7698 @item @code{-v}
7700 Verbose. Display the reason for all recompilations @code{gnatmake}
7701 decides are necessary, with the highest verbosity level.
7702 @end table
7704 @geindex -vl (gnatmake)
7707 @table @asis
7709 @item @code{-vl}
7711 Verbosity level Low. Display fewer lines than in verbosity Medium.
7712 @end table
7714 @geindex -vm (gnatmake)
7717 @table @asis
7719 @item @code{-vm}
7721 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7722 @end table
7724 @geindex -vm (gnatmake)
7727 @table @asis
7729 @item @code{-vh}
7731 Verbosity level High. Equivalent to -v.
7733 @item @code{-vP@emph{x}}
7735 Indicate the verbosity of the parsing of GNAT project files.
7736 See @ref{cf,,Switches Related to Project Files}.
7737 @end table
7739 @geindex -x (gnatmake)
7742 @table @asis
7744 @item @code{-x}
7746 Indicate that sources that are not part of any Project File may be compiled.
7747 Normally, when using Project Files, only sources that are part of a Project
7748 File may be compile. When this switch is used, a source outside of all Project
7749 Files may be compiled. The ALI file and the object file will be put in the
7750 object directory of the main Project. The compilation switches used will only
7751 be those specified on the command line. Even when
7752 @code{-x} is used, mains specified on the
7753 command line need to be sources of a project file.
7755 @item @code{-X@emph{name}=@emph{value}}
7757 Indicate that external variable @code{name} has the value @code{value}.
7758 The Project Manager will use this value for occurrences of
7759 @code{external(name)} when parsing the project file.
7760 @ref{cf,,Switches Related to Project Files}.
7761 @end table
7763 @geindex -z (gnatmake)
7766 @table @asis
7768 @item @code{-z}
7770 No main subprogram. Bind and link the program even if the unit name
7771 given on the command line is a package name. The resulting executable
7772 will execute the elaboration routines of the package and its closure,
7773 then the finalization routines.
7774 @end table
7776 @subsubheading GCC switches
7779 Any uppercase or multi-character switch that is not a @code{gnatmake} switch
7780 is passed to @code{gcc} (e.g., @code{-O}, @code{-gnato,} etc.)
7782 @subsubheading Source and library search path switches
7785 @geindex -aI (gnatmake)
7788 @table @asis
7790 @item @code{-aI@emph{dir}}
7792 When looking for source files also look in directory @code{dir}.
7793 The order in which source files search is undertaken is
7794 described in @ref{73,,Search Paths and the Run-Time Library (RTL)}.
7795 @end table
7797 @geindex -aL (gnatmake)
7800 @table @asis
7802 @item @code{-aL@emph{dir}}
7804 Consider @code{dir} as being an externally provided Ada library.
7805 Instructs @code{gnatmake} to skip compilation units whose @code{.ALI}
7806 files have been located in directory @code{dir}. This allows you to have
7807 missing bodies for the units in @code{dir} and to ignore out of date bodies
7808 for the same units. You still need to specify
7809 the location of the specs for these units by using the switches
7810 @code{-aI@emph{dir}}  or @code{-I@emph{dir}}.
7811 Note: this switch is provided for compatibility with previous versions
7812 of @code{gnatmake}. The easier method of causing standard libraries
7813 to be excluded from consideration is to write-protect the corresponding
7814 ALI files.
7815 @end table
7817 @geindex -aO (gnatmake)
7820 @table @asis
7822 @item @code{-aO@emph{dir}}
7824 When searching for library and object files, look in directory
7825 @code{dir}. The order in which library files are searched is described in
7826 @ref{76,,Search Paths for gnatbind}.
7827 @end table
7829 @geindex Search paths
7830 @geindex for gnatmake
7832 @geindex -A (gnatmake)
7835 @table @asis
7837 @item @code{-A@emph{dir}}
7839 Equivalent to @code{-aL@emph{dir}} @code{-aI@emph{dir}}.
7841 @geindex -I (gnatmake)
7843 @item @code{-I@emph{dir}}
7845 Equivalent to @code{-aO@emph{dir} -aI@emph{dir}}.
7846 @end table
7848 @geindex -I- (gnatmake)
7850 @geindex Source files
7851 @geindex suppressing search
7854 @table @asis
7856 @item @code{-I-}
7858 Do not look for source files in the directory containing the source
7859 file named in the command line.
7860 Do not look for ALI or object files in the directory
7861 where @code{gnatmake} was invoked.
7862 @end table
7864 @geindex -L (gnatmake)
7866 @geindex Linker libraries
7869 @table @asis
7871 @item @code{-L@emph{dir}}
7873 Add directory @code{dir} to the list of directories in which the linker
7874 will search for libraries. This is equivalent to
7875 @code{-largs} @code{-L@emph{dir}}.
7876 Furthermore, under Windows, the sources pointed to by the libraries path
7877 set in the registry are not searched for.
7878 @end table
7880 @geindex -nostdinc (gnatmake)
7883 @table @asis
7885 @item @code{-nostdinc}
7887 Do not look for source files in the system default directory.
7888 @end table
7890 @geindex -nostdlib (gnatmake)
7893 @table @asis
7895 @item @code{-nostdlib}
7897 Do not look for library files in the system default directory.
7898 @end table
7900 @geindex --RTS (gnatmake)
7903 @table @asis
7905 @item @code{--RTS=@emph{rts-path}}
7907 Specifies the default location of the run-time library. GNAT looks for the
7908 run-time
7909 in the following directories, and stops as soon as a valid run-time is found
7910 (@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
7911 @code{ada_object_path} present):
7914 @itemize *
7916 @item 
7917 @emph{<current directory>/$rts_path}
7919 @item 
7920 @emph{<default-search-dir>/$rts_path}
7922 @item 
7923 @emph{<default-search-dir>/rts-$rts_path}
7925 @item 
7926 The selected path is handled like a normal RTS path.
7927 @end itemize
7928 @end table
7930 @node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
7931 @anchor{gnat_ugn/building_executable_programs_with_gnat id4}@anchor{d0}@anchor{gnat_ugn/building_executable_programs_with_gnat mode-switches-for-gnatmake}@anchor{d1}
7932 @subsection Mode Switches for @code{gnatmake}
7935 The mode switches (referred to as @code{mode_switches}) allow the
7936 inclusion of switches that are to be passed to the compiler itself, the
7937 binder or the linker. The effect of a mode switch is to cause all
7938 subsequent switches up to the end of the switch list, or up to the next
7939 mode switch, to be interpreted as switches to be passed on to the
7940 designated component of GNAT.
7942 @geindex -cargs (gnatmake)
7945 @table @asis
7947 @item @code{-cargs @emph{switches}}
7949 Compiler switches. Here @code{switches} is a list of switches
7950 that are valid switches for @code{gcc}. They will be passed on to
7951 all compile steps performed by @code{gnatmake}.
7952 @end table
7954 @geindex -bargs (gnatmake)
7957 @table @asis
7959 @item @code{-bargs @emph{switches}}
7961 Binder switches. Here @code{switches} is a list of switches
7962 that are valid switches for @code{gnatbind}. They will be passed on to
7963 all bind steps performed by @code{gnatmake}.
7964 @end table
7966 @geindex -largs (gnatmake)
7969 @table @asis
7971 @item @code{-largs @emph{switches}}
7973 Linker switches. Here @code{switches} is a list of switches
7974 that are valid switches for @code{gnatlink}. They will be passed on to
7975 all link steps performed by @code{gnatmake}.
7976 @end table
7978 @geindex -margs (gnatmake)
7981 @table @asis
7983 @item @code{-margs @emph{switches}}
7985 Make switches. The switches are directly interpreted by @code{gnatmake},
7986 regardless of any previous occurrence of @code{-cargs}, @code{-bargs}
7987 or @code{-largs}.
7988 @end table
7990 @node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
7991 @anchor{gnat_ugn/building_executable_programs_with_gnat id5}@anchor{d2}@anchor{gnat_ugn/building_executable_programs_with_gnat notes-on-the-command-line}@anchor{d3}
7992 @subsection Notes on the Command Line
7995 This section contains some additional useful notes on the operation
7996 of the @code{gnatmake} command.
7998 @geindex Recompilation (by gnatmake)
8001 @itemize *
8003 @item 
8004 If @code{gnatmake} finds no ALI files, it recompiles the main program
8005 and all other units required by the main program.
8006 This means that @code{gnatmake}
8007 can be used for the initial compile, as well as during subsequent steps of
8008 the development cycle.
8010 @item 
8011 If you enter @code{gnatmake foo.adb}, where @code{foo}
8012 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8013 @code{foo.adb} (because it finds no ALI) and stops, issuing a
8014 warning.
8016 @item 
8017 In @code{gnatmake} the switch @code{-I}
8018 is used to specify both source and
8019 library file paths. Use @code{-aI}
8020 instead if you just want to specify
8021 source paths only and @code{-aO}
8022 if you want to specify library paths
8023 only.
8025 @item 
8026 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8027 This may conveniently be used to exclude standard libraries from
8028 consideration and in particular it means that the use of the
8029 @code{-f} switch will not recompile these files
8030 unless @code{-a} is also specified.
8032 @item 
8033 @code{gnatmake} has been designed to make the use of Ada libraries
8034 particularly convenient. Assume you have an Ada library organized
8035 as follows: @emph{obj-dir} contains the objects and ALI files for
8036 of your Ada compilation units,
8037 whereas @emph{include-dir} contains the
8038 specs of these units, but no bodies. Then to compile a unit
8039 stored in @code{main.adb}, which uses this Ada library you would just type:
8041 @example
8042 $ gnatmake -aI`include-dir`  -aL`obj-dir`  main
8043 @end example
8045 @item 
8046 Using @code{gnatmake} along with the @code{-m (minimal recompilation)}
8047 switch provides a mechanism for avoiding unnecessary recompilations. Using
8048 this switch,
8049 you can update the comments/format of your
8050 source files without having to recompile everything. Note, however, that
8051 adding or deleting lines in a source files may render its debugging
8052 info obsolete. If the file in question is a spec, the impact is rather
8053 limited, as that debugging info will only be useful during the
8054 elaboration phase of your program. For bodies the impact can be more
8055 significant. In all events, your debugger will warn you if a source file
8056 is more recent than the corresponding object, and alert you to the fact
8057 that the debugging information may be out of date.
8058 @end itemize
8060 @node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8061 @anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{d4}@anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{d5}
8062 @subsection How @code{gnatmake} Works
8065 Generally @code{gnatmake} automatically performs all necessary
8066 recompilations and you don’t need to worry about how it works. However,
8067 it may be useful to have some basic understanding of the @code{gnatmake}
8068 approach and in particular to understand how it uses the results of
8069 previous compilations without incorrectly depending on them.
8071 First a definition: an object file is considered @emph{up to date} if the
8072 corresponding ALI file exists and if all the source files listed in the
8073 dependency section of this ALI file have time stamps matching those in
8074 the ALI file. This means that neither the source file itself nor any
8075 files that it depends on have been modified, and hence there is no need
8076 to recompile this file.
8078 @code{gnatmake} works by first checking if the specified main unit is up
8079 to date. If so, no compilations are required for the main unit. If not,
8080 @code{gnatmake} compiles the main program to build a new ALI file that
8081 reflects the latest sources. Then the ALI file of the main unit is
8082 examined to find all the source files on which the main program depends,
8083 and @code{gnatmake} recursively applies the above procedure on all these
8084 files.
8086 This process ensures that @code{gnatmake} only trusts the dependencies
8087 in an existing ALI file if they are known to be correct. Otherwise it
8088 always recompiles to determine a new, guaranteed accurate set of
8089 dependencies. As a result the program is compiled ‘upside down’ from what may
8090 be more familiar as the required order of compilation in some other Ada
8091 systems. In particular, clients are compiled before the units on which
8092 they depend. The ability of GNAT to compile in any order is critical in
8093 allowing an order of compilation to be chosen that guarantees that
8094 @code{gnatmake} will recompute a correct set of new dependencies if
8095 necessary.
8097 When invoking @code{gnatmake} with several @code{file_names}, if a unit is
8098 imported by several of the executables, it will be recompiled at most once.
8100 Note: when using non-standard naming conventions
8101 (@ref{1c,,Using Other File Names}), changing through a configuration pragmas
8102 file the version of a source and invoking @code{gnatmake} to recompile may
8103 have no effect, if the previous version of the source is still accessible
8104 by @code{gnatmake}. It may be necessary to use the switch
8107 @node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8108 @anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatmake-usage}@anchor{d6}@anchor{gnat_ugn/building_executable_programs_with_gnat id7}@anchor{d7}
8109 @subsection Examples of @code{gnatmake} Usage
8113 @table @asis
8115 @item @emph{gnatmake hello.adb}
8117 Compile all files necessary to bind and link the main program
8118 @code{hello.adb} (containing unit @code{Hello}) and bind and link the
8119 resulting object files to generate an executable file @code{hello}.
8121 @item @emph{gnatmake main1 main2 main3}
8123 Compile all files necessary to bind and link the main programs
8124 @code{main1.adb} (containing unit @code{Main1}), @code{main2.adb}
8125 (containing unit @code{Main2}) and @code{main3.adb}
8126 (containing unit @code{Main3}) and bind and link the resulting object files
8127 to generate three executable files @code{main1},
8128 @code{main2}  and @code{main3}.
8130 @item @emph{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8132 Compile all files necessary to bind and link the main program unit
8133 @code{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8134 be done with optimization level 2 and the order of elaboration will be
8135 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8136 displaying commands it is executing.
8137 @end table
8139 @node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8140 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{c7}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{d8}
8141 @section Compiling with @code{gcc}
8144 This section discusses how to compile Ada programs using the @code{gcc}
8145 command. It also describes the set of switches
8146 that can be used to control the behavior of the compiler.
8148 @menu
8149 * Compiling Programs:: 
8150 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
8151 * Order of Compilation Issues:: 
8152 * Examples:: 
8154 @end menu
8156 @node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8157 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{d9}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{da}
8158 @subsection Compiling Programs
8161 The first step in creating an executable program is to compile the units
8162 of the program using the @code{gcc} command. You must compile the
8163 following files:
8166 @itemize *
8168 @item 
8169 the body file (@code{.adb}) for a library level subprogram or generic
8170 subprogram
8172 @item 
8173 the spec file (@code{.ads}) for a library level package or generic
8174 package that has no body
8176 @item 
8177 the body file (@code{.adb}) for a library level package
8178 or generic package that has a body
8179 @end itemize
8181 You need @emph{not} compile the following files
8184 @itemize *
8186 @item 
8187 the spec of a library unit which has a body
8189 @item 
8190 subunits
8191 @end itemize
8193 because they are compiled as part of compiling related units. GNAT
8194 package specs
8195 when the corresponding body is compiled, and subunits when the parent is
8196 compiled.
8198 @geindex cannot generate code
8200 If you attempt to compile any of these files, you will get one of the
8201 following error messages (where @code{fff} is the name of the file you
8202 compiled):
8204 @quotation
8206 @example
8207 cannot generate code for file `@w{`}fff`@w{`} (package spec)
8208 to check package spec, use -gnatc
8210 cannot generate code for file `@w{`}fff`@w{`} (missing subunits)
8211 to check parent unit, use -gnatc
8213 cannot generate code for file `@w{`}fff`@w{`} (subprogram spec)
8214 to check subprogram spec, use -gnatc
8216 cannot generate code for file `@w{`}fff`@w{`} (subunit)
8217 to check subunit, use -gnatc
8218 @end example
8219 @end quotation
8221 As indicated by the above error messages, if you want to submit
8222 one of these files to the compiler to check for correct semantics
8223 without generating code, then use the @code{-gnatc} switch.
8225 The basic command for compiling a file containing an Ada unit is:
8227 @example
8228 $ gcc -c [switches] <file name>
8229 @end example
8231 where @code{file name} is the name of the Ada file (usually
8232 having an extension @code{.ads} for a spec or @code{.adb} for a body).
8233 You specify the
8234 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
8235 The result of a successful compilation is an object file, which has the
8236 same name as the source file but an extension of @code{.o} and an Ada
8237 Library Information (ALI) file, which also has the same name as the
8238 source file, but with @code{.ali} as the extension. GNAT creates these
8239 two output files in the current directory, but you may specify a source
8240 file in any directory using an absolute or relative path specification
8241 containing the directory information.
8243 TESTING: the @code{--foobar@emph{NN}} switch
8245 @geindex gnat1
8247 @code{gcc} is actually a driver program that looks at the extensions of
8248 the file arguments and loads the appropriate compiler. For example, the
8249 GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8250 These programs are in directories known to the driver program (in some
8251 configurations via environment variables you set), but need not be in
8252 your path. The @code{gcc} driver also calls the assembler and any other
8253 utilities needed to complete the generation of the required object
8254 files.
8256 It is possible to supply several file names on the same @code{gcc}
8257 command. This causes @code{gcc} to call the appropriate compiler for
8258 each file. For example, the following command lists two separate
8259 files to be compiled:
8261 @example
8262 $ gcc -c x.adb y.adb
8263 @end example
8265 calls @code{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8266 @code{y.adb}.
8267 The compiler generates two object files @code{x.o} and @code{y.o}
8268 and the two ALI files @code{x.ali} and @code{y.ali}.
8270 Any switches apply to all the files listed, see @ref{db,,Compiler Switches} for a
8271 list of available @code{gcc} switches.
8273 @node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8274 @anchor{gnat_ugn/building_executable_programs_with_gnat id10}@anchor{dc}@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-and-the-run-time-library-rtl}@anchor{73}
8275 @subsection Search Paths and the Run-Time Library (RTL)
8278 With the GNAT source-based library system, the compiler must be able to
8279 find source files for units that are needed by the unit being compiled.
8280 Search paths are used to guide this process.
8282 The compiler compiles one source file whose name must be given
8283 explicitly on the command line. In other words, no searching is done
8284 for this file. To find all other source files that are needed (the most
8285 common being the specs of units), the compiler examines the following
8286 directories, in the following order:
8289 @itemize *
8291 @item 
8292 The directory containing the source file of the main unit being compiled
8293 (the file name on the command line).
8295 @item 
8296 Each directory named by an @code{-I} switch given on the @code{gcc}
8297 command line, in the order given.
8299 @geindex ADA_PRJ_INCLUDE_FILE
8301 @item 
8302 Each of the directories listed in the text file whose name is given
8303 by the 
8304 @geindex ADA_PRJ_INCLUDE_FILE
8305 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8306 @code{ADA_PRJ_INCLUDE_FILE} environment variable.
8307 @geindex ADA_PRJ_INCLUDE_FILE
8308 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8309 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8310 driver when project files are used. It should not normally be set
8311 by other means.
8313 @geindex ADA_INCLUDE_PATH
8315 @item 
8316 Each of the directories listed in the value of the
8317 @geindex ADA_INCLUDE_PATH
8318 @geindex environment variable; ADA_INCLUDE_PATH
8319 @code{ADA_INCLUDE_PATH} environment variable.
8320 Construct this value
8321 exactly as the 
8322 @geindex PATH
8323 @geindex environment variable; PATH
8324 @code{PATH} environment variable: a list of directory
8325 names separated by colons (semicolons when working with the NT version).
8327 @item 
8328 The content of the @code{ada_source_path} file which is part of the GNAT
8329 installation tree and is used to store standard libraries such as the
8330 GNAT Run Time Library (RTL) source files.
8331 @ref{72,,Installing a library}
8332 @end itemize
8334 Specifying the switch @code{-I-}
8335 inhibits the use of the directory
8336 containing the source file named in the command line. You can still
8337 have this directory on your search path, but in this case it must be
8338 explicitly requested with a @code{-I} switch.
8340 Specifying the switch @code{-nostdinc}
8341 inhibits the search of the default location for the GNAT Run Time
8342 Library (RTL) source files.
8344 The compiler outputs its object files and ALI files in the current
8345 working directory.
8346 Caution: The object file can be redirected with the @code{-o} switch;
8347 however, @code{gcc} and @code{gnat1} have not been coordinated on this
8348 so the @code{ALI} file will not go to the right place. Therefore, you should
8349 avoid using the @code{-o} switch.
8351 @geindex System.IO
8353 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8354 children make up the GNAT RTL, together with the simple @code{System.IO}
8355 package used in the @code{"Hello World"} example. The sources for these units
8356 are needed by the compiler and are kept together in one directory. Not
8357 all of the bodies are needed, but all of the sources are kept together
8358 anyway. In a normal installation, you need not specify these directory
8359 names when compiling or binding. Either the environment variables or
8360 the built-in defaults cause these files to be found.
8362 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8363 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8364 consisting of child units of @code{GNAT}. This is a collection of generally
8365 useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8366 for further details.
8368 Besides simplifying access to the RTL, a major use of search paths is
8369 in compiling sources from multiple directories. This can make
8370 development environments much more flexible.
8372 @node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8373 @anchor{gnat_ugn/building_executable_programs_with_gnat id11}@anchor{dd}@anchor{gnat_ugn/building_executable_programs_with_gnat order-of-compilation-issues}@anchor{de}
8374 @subsection Order of Compilation Issues
8377 If, in our earlier example, there was a spec for the @code{hello}
8378 procedure, it would be contained in the file @code{hello.ads}; yet this
8379 file would not have to be explicitly compiled. This is the result of the
8380 model we chose to implement library management. Some of the consequences
8381 of this model are as follows:
8384 @itemize *
8386 @item 
8387 There is no point in compiling specs (except for package
8388 specs with no bodies) because these are compiled as needed by clients. If
8389 you attempt a useless compilation, you will receive an error message.
8390 It is also useless to compile subunits because they are compiled as needed
8391 by the parent.
8393 @item 
8394 There are no order of compilation requirements: performing a
8395 compilation never obsoletes anything. The only way you can obsolete
8396 something and require recompilations is to modify one of the
8397 source files on which it depends.
8399 @item 
8400 There is no library as such, apart from the ALI files
8401 (@ref{28,,The Ada Library Information Files}, for information on the format
8402 of these files). For now we find it convenient to create separate ALI files,
8403 but eventually the information therein may be incorporated into the object
8404 file directly.
8406 @item 
8407 When you compile a unit, the source files for the specs of all units
8408 that it @emph{with}s, all its subunits, and the bodies of any generics it
8409 instantiates must be available (reachable by the search-paths mechanism
8410 described above), or you will receive a fatal error message.
8411 @end itemize
8413 @node Examples,,Order of Compilation Issues,Compiling with gcc
8414 @anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{df}@anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{e0}
8415 @subsection Examples
8418 The following are some typical Ada compilation command line examples:
8420 @example
8421 $ gcc -c xyz.adb
8422 @end example
8424 Compile body in file @code{xyz.adb} with all default options.
8426 @example
8427 $ gcc -c -O2 -gnata xyz-def.adb
8428 @end example
8430 Compile the child unit package in file @code{xyz-def.adb} with extensive
8431 optimizations, and pragma @code{Assert}/@cite{Debug} statements
8432 enabled.
8434 @example
8435 $ gcc -c -gnatc abc-def.adb
8436 @end example
8438 Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8439 mode.
8441 @node Compiler Switches,Linker Switches,Compiling with gcc,Building Executable Programs with GNAT
8442 @anchor{gnat_ugn/building_executable_programs_with_gnat compiler-switches}@anchor{e1}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gcc}@anchor{db}
8443 @section Compiler Switches
8446 The @code{gcc} command accepts switches that control the
8447 compilation process. These switches are fully described in this section:
8448 first an alphabetical listing of all switches with a brief description,
8449 and then functionally grouped sets of switches with more detailed
8450 information.
8452 More switches exist for GCC than those documented here, especially
8453 for specific targets. However, their use is not recommended as
8454 they may change code generation in ways that are incompatible with
8455 the Ada run-time library, or can cause inconsistencies between
8456 compilation units.
8458 @menu
8459 * Alphabetical List of All Switches:: 
8460 * Output and Error Message Control:: 
8461 * Warning Message Control:: 
8462 * Debugging and Assertion Control:: 
8463 * Validity Checking:: 
8464 * Style Checking:: 
8465 * Run-Time Checks:: 
8466 * Using gcc for Syntax Checking:: 
8467 * Using gcc for Semantic Checking:: 
8468 * Compiling Different Versions of Ada:: 
8469 * Character Set Control:: 
8470 * File Naming Control:: 
8471 * Subprogram Inlining Control:: 
8472 * Auxiliary Output Control:: 
8473 * Debugging Control:: 
8474 * Exception Handling Control:: 
8475 * Units to Sources Mapping Files:: 
8476 * Code Generation Control:: 
8478 @end menu
8480 @node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8481 @anchor{gnat_ugn/building_executable_programs_with_gnat alphabetical-list-of-all-switches}@anchor{e2}@anchor{gnat_ugn/building_executable_programs_with_gnat id13}@anchor{e3}
8482 @subsection Alphabetical List of All Switches
8485 @geindex -b (gcc)
8488 @table @asis
8490 @item @code{-b @emph{target}}
8492 Compile your program to run on @code{target}, which is the name of a
8493 system configuration. You must have a GNAT cross-compiler built if
8494 @code{target} is not the same as your host system.
8495 @end table
8497 @geindex -B (gcc)
8500 @table @asis
8502 @item @code{-B@emph{dir}}
8504 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8505 from @code{dir} instead of the default location. Only use this switch
8506 when multiple versions of the GNAT compiler are available.
8507 See the “Options for Directory Search” section in the
8508 @cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8509 You would normally use the @code{-b} or @code{-V} switch instead.
8510 @end table
8512 @geindex -c (gcc)
8515 @table @asis
8517 @item @code{-c}
8519 Compile. Always use this switch when compiling Ada programs.
8521 Note: for some other languages when using @code{gcc}, notably in
8522 the case of C and C++, it is possible to use
8523 use @code{gcc} without a @code{-c} switch to
8524 compile and link in one step. In the case of GNAT, you
8525 cannot use this approach, because the binder must be run
8526 and @code{gcc} cannot be used to run the GNAT binder.
8527 @end table
8529 @geindex -fcallgraph-info (gcc)
8532 @table @asis
8534 @item @code{-fcallgraph-info[=su,da]}
8536 Makes the compiler output callgraph information for the program, on a
8537 per-file basis. The information is generated in the VCG format.  It can
8538 be decorated with additional, per-node and/or per-edge information, if a
8539 list of comma-separated markers is additionally specified. When the
8540 @code{su} marker is specified, the callgraph is decorated with stack usage
8541 information; it is equivalent to @code{-fstack-usage}. When the @code{da}
8542 marker is specified, the callgraph is decorated with information about
8543 dynamically allocated objects.
8544 @end table
8546 @geindex -fdiagnostics-format (gcc)
8549 @table @asis
8551 @item @code{-fdiagnostics-format=json}
8553 Makes GNAT emit warning and error messages as JSON. Inhibits printing of
8554 text warning and errors messages except if @code{-gnatv} or
8555 @code{-gnatl} are present.
8556 @end table
8558 @geindex -fdump-scos (gcc)
8561 @table @asis
8563 @item @code{-fdump-scos}
8565 Generates SCO (Source Coverage Obligation) information in the ALI file.
8566 This information is used by advanced coverage tools. See unit @code{SCOs}
8567 in the compiler sources for details in files @code{scos.ads} and
8568 @code{scos.adb}.
8569 @end table
8571 @geindex -fgnat-encodings (gcc)
8574 @table @asis
8576 @item @code{-fgnat-encodings=[all|gdb|minimal]}
8578 This switch controls the balance between GNAT encodings and standard DWARF
8579 emitted in the debug information.
8580 @end table
8582 @geindex -flto (gcc)
8585 @table @asis
8587 @item @code{-flto[=@emph{n}]}
8589 Enables Link Time Optimization. This switch must be used in conjunction
8590 with the @code{-Ox} switches (but not with the @code{-gnatn} switch
8591 since it is a full replacement for the latter) and instructs the compiler
8592 to defer most optimizations until the link stage. The advantage of this
8593 approach is that the compiler can do a whole-program analysis and choose
8594 the best interprocedural optimization strategy based on a complete view
8595 of the program, instead of a fragmentary view with the usual approach.
8596 This can also speed up the compilation of big programs and reduce the
8597 size of the executable, compared with a traditional per-unit compilation
8598 with inlining across units enabled by the @code{-gnatn} switch.
8599 The drawback of this approach is that it may require more memory and that
8600 the debugging information generated by -g with it might be hardly usable.
8601 The switch, as well as the accompanying @code{-Ox} switches, must be
8602 specified both for the compilation and the link phases.
8603 If the @code{n} parameter is specified, the optimization and final code
8604 generation at link time are executed using @code{n} parallel jobs by
8605 means of an installed @code{make} program.
8606 @end table
8608 @geindex -fno-inline (gcc)
8611 @table @asis
8613 @item @code{-fno-inline}
8615 Suppresses all inlining, unless requested with pragma @code{Inline_Always}. The
8616 effect is enforced regardless of other optimization or inlining switches.
8617 Note that inlining can also be suppressed on a finer-grained basis with
8618 pragma @code{No_Inline}.
8619 @end table
8621 @geindex -fno-inline-functions (gcc)
8624 @table @asis
8626 @item @code{-fno-inline-functions}
8628 Suppresses automatic inlining of subprograms, which is enabled
8629 if @code{-O3} is used.
8630 @end table
8632 @geindex -fno-inline-small-functions (gcc)
8635 @table @asis
8637 @item @code{-fno-inline-small-functions}
8639 Suppresses automatic inlining of small subprograms, which is enabled
8640 if @code{-O2} is used.
8641 @end table
8643 @geindex -fno-inline-functions-called-once (gcc)
8646 @table @asis
8648 @item @code{-fno-inline-functions-called-once}
8650 Suppresses inlining of subprograms local to the unit and called once
8651 from within it, which is enabled if @code{-O1} is used.
8652 @end table
8654 @geindex -fno-ivopts (gcc)
8657 @table @asis
8659 @item @code{-fno-ivopts}
8661 Suppresses high-level loop induction variable optimizations, which are
8662 enabled if @code{-O1} is used. These optimizations are generally
8663 profitable but, for some specific cases of loops with numerous uses
8664 of the iteration variable that follow a common pattern, they may end
8665 up destroying the regularity that could be exploited at a lower level
8666 and thus producing inferior code.
8667 @end table
8669 @geindex -fno-strict-aliasing (gcc)
8672 @table @asis
8674 @item @code{-fno-strict-aliasing}
8676 Causes the compiler to avoid assumptions regarding non-aliasing
8677 of objects of different types. See
8678 @ref{e4,,Optimization and Strict Aliasing} for details.
8679 @end table
8681 @geindex -fno-strict-overflow (gcc)
8684 @table @asis
8686 @item @code{-fno-strict-overflow}
8688 Causes the compiler to avoid assumptions regarding the rules of signed
8689 integer overflow. These rules specify that signed integer overflow will
8690 result in a Constraint_Error exception at run time and are enforced in
8691 default mode by the compiler, so this switch should not be necessary in
8692 normal operating mode. It might be useful in conjunction with @code{-gnato0}
8693 for very peculiar cases of low-level programming.
8694 @end table
8696 @geindex -fstack-check (gcc)
8699 @table @asis
8701 @item @code{-fstack-check}
8703 Activates stack checking.
8704 See @ref{e5,,Stack Overflow Checking} for details.
8705 @end table
8707 @geindex -fstack-usage (gcc)
8710 @table @asis
8712 @item @code{-fstack-usage}
8714 Makes the compiler output stack usage information for the program, on a
8715 per-subprogram basis. See @ref{e6,,Static Stack Usage Analysis} for details.
8716 @end table
8718 @geindex -g (gcc)
8721 @table @asis
8723 @item @code{-g}
8725 Generate debugging information. This information is stored in the object
8726 file and copied from there to the final executable file by the linker,
8727 where it can be read by the debugger. You must use the
8728 @code{-g} switch if you plan on using the debugger.
8729 @end table
8731 @geindex -gnat05 (gcc)
8734 @table @asis
8736 @item @code{-gnat05}
8738 Allow full Ada 2005 features.
8739 @end table
8741 @geindex -gnat12 (gcc)
8744 @table @asis
8746 @item @code{-gnat12}
8748 Allow full Ada 2012 features.
8749 @end table
8751 @geindex -gnat83 (gcc)
8753 @geindex -gnat2005 (gcc)
8756 @table @asis
8758 @item @code{-gnat2005}
8760 Allow full Ada 2005 features (same as @code{-gnat05})
8761 @end table
8763 @geindex -gnat2012 (gcc)
8766 @table @asis
8768 @item @code{-gnat2012}
8770 Allow full Ada 2012 features (same as @code{-gnat12})
8771 @end table
8773 @geindex -gnat2022 (gcc)
8776 @table @asis
8778 @item @code{-gnat2022}
8780 Allow full Ada 2022 features
8782 @item @code{-gnat83}
8784 Enforce Ada 83 restrictions.
8785 @end table
8787 @geindex -gnat95 (gcc)
8790 @table @asis
8792 @item @code{-gnat95}
8794 Enforce Ada 95 restrictions.
8796 Note: for compatibility with some Ada 95 compilers which support only
8797 the @code{overriding} keyword of Ada 2005, the @code{-gnatd.D} switch can
8798 be used along with @code{-gnat95} to achieve a similar effect with GNAT.
8800 @code{-gnatd.D} instructs GNAT to consider @code{overriding} as a keyword
8801 and handle its associated semantic checks, even in Ada 95 mode.
8802 @end table
8804 @geindex -gnata (gcc)
8807 @table @asis
8809 @item @code{-gnata}
8811 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
8812 activated. Note that these pragmas can also be controlled using the
8813 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
8814 It also activates pragmas @code{Check}, @code{Precondition}, and
8815 @code{Postcondition}. Note that these pragmas can also be controlled
8816 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
8817 also activates all assertions defined in the RM as aspects: preconditions,
8818 postconditions, type invariants and (sub)type predicates. In all Ada modes,
8819 corresponding pragmas for type invariants and (sub)type predicates are
8820 also activated. The default is that all these assertions are disabled,
8821 and have no effect, other than being checked for syntactic validity, and
8822 in the case of subtype predicates, constructions such as membership tests
8823 still test predicates even if assertions are turned off.
8824 @end table
8826 @geindex -gnatA (gcc)
8829 @table @asis
8831 @item @code{-gnatA}
8833 Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
8834 it will be ignored.
8835 @end table
8837 @geindex -gnatb (gcc)
8840 @table @asis
8842 @item @code{-gnatb}
8844 Generate brief messages to @code{stderr} even if verbose mode set.
8845 @end table
8847 @geindex -gnatB (gcc)
8850 @table @asis
8852 @item @code{-gnatB}
8854 Assume no invalid (bad) values except for ‘Valid attribute use
8855 (@ref{e7,,Validity Checking}).
8856 @end table
8858 @geindex -gnatc (gcc)
8861 @table @asis
8863 @item @code{-gnatc}
8865 Check syntax and semantics only (no code generation attempted). When the
8866 compiler is invoked by @code{gnatmake}, if the switch @code{-gnatc} is
8867 only given to the compiler (after @code{-cargs} or in package Compiler of
8868 the project file), @code{gnatmake} will fail because it will not find the
8869 object file after compilation. If @code{gnatmake} is called with
8870 @code{-gnatc} as a builder switch (before @code{-cargs} or in package
8871 Builder of the project file) then @code{gnatmake} will not fail because
8872 it will not look for the object files after compilation, and it will not try
8873 to build and link.
8874 @end table
8876 @geindex -gnatC (gcc)
8879 @table @asis
8881 @item @code{-gnatC}
8883 Generate CodePeer intermediate format (no code generation attempted).
8884 This switch will generate an intermediate representation suitable for
8885 use by CodePeer (@code{.scil} files). This switch is not compatible with
8886 code generation (it will, among other things, disable some switches such
8887 as -gnatn, and enable others such as -gnata).
8888 @end table
8890 @geindex -gnatd (gcc)
8893 @table @asis
8895 @item @code{-gnatd}
8897 Specify debug options for the compiler. The string of characters after
8898 the @code{-gnatd} specifies the specific debug options. The possible
8899 characters are 0-9, a-z, A-Z, optionally preceded by a dot or underscore.
8900 See compiler source file @code{debug.adb} for details of the implemented
8901 debug options. Certain debug options are relevant to applications
8902 programmers, and these are documented at appropriate points in this
8903 users guide.
8904 @end table
8906 @geindex -gnatD[nn] (gcc)
8909 @table @asis
8911 @item @code{-gnatD}
8913 Create expanded source files for source level debugging. This switch
8914 also suppresses generation of cross-reference information
8915 (see @code{-gnatx}). Note that this switch is not allowed if a previous
8916 -gnatR switch has been given, since these two switches are not compatible.
8917 @end table
8919 @geindex -gnateA (gcc)
8922 @table @asis
8924 @item @code{-gnateA}
8926 Check that the actual parameters of a subprogram call are not aliases of one
8927 another. To qualify as aliasing, their memory locations must be identical or
8928 overlapping, at least one of the corresponding formal parameters must be of
8929 mode OUT or IN OUT, and at least one of the corresponding formal parameters
8930 must have its parameter passing mechanism not specified.
8932 @example
8933 type Rec_Typ is record
8934    Data : Integer := 0;
8935 end record;
8937 function Self (Val : Rec_Typ) return Rec_Typ is
8938 begin
8939    return Val;
8940 end Self;
8942 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
8943 begin
8944    null;
8945 end Detect_Aliasing;
8947 Obj : Rec_Typ;
8949 Detect_Aliasing (Obj, Obj);
8950 Detect_Aliasing (Obj, Self (Obj));
8951 @end example
8953 In the example above, the first call to @code{Detect_Aliasing} fails with a
8954 @code{Program_Error} at run time because the actuals for @code{Val_1} and
8955 @code{Val_2} denote the same object. The second call executes without raising
8956 an exception because @code{Self(Obj)} produces an anonymous object which does
8957 not share the memory location of @code{Obj}.
8958 @end table
8960 @geindex -gnateb (gcc)
8963 @table @asis
8965 @item @code{-gnateb}
8967 Store configuration files by their basename in ALI files. This switch is
8968 used for instance by gprbuild for distributed builds in order to prevent
8969 issues where machine-specific absolute paths could end up being stored in
8970 ALI files.
8971 @end table
8973 @geindex -gnatec (gcc)
8976 @table @asis
8978 @item @code{-gnatec=@emph{path}}
8980 Specify a configuration pragma file
8981 (the equal sign is optional)
8982 (@ref{63,,The Configuration Pragmas Files}).
8983 @end table
8985 @geindex -gnateC (gcc)
8988 @table @asis
8990 @item @code{-gnateC}
8992 Generate CodePeer messages in a compiler-like format. This switch is only
8993 effective if @code{-gnatcC} is also specified and requires an installation
8994 of CodePeer.
8995 @end table
8997 @geindex -gnated (gcc)
9000 @table @asis
9002 @item @code{-gnated}
9004 Disable atomic synchronization
9005 @end table
9007 @geindex -gnateD (gcc)
9010 @table @asis
9012 @item @code{-gnateDsymbol[=@emph{value}]}
9014 Defines a symbol, associated with @code{value}, for preprocessing.
9015 (@ref{90,,Integrated Preprocessing}).
9016 @end table
9018 @geindex -gnateE (gcc)
9021 @table @asis
9023 @item @code{-gnateE}
9025 Generate extra information in exception messages. In particular, display
9026 extra column information and the value and range associated with index and
9027 range check failures, and extra column information for access checks.
9028 In cases where the compiler is able to determine at compile time that
9029 a check will fail, it gives a warning, and the extra information is not
9030 produced at run time.
9031 @end table
9033 @geindex -gnatef (gcc)
9036 @table @asis
9038 @item @code{-gnatef}
9040 Display full source path name in brief error messages.
9041 @end table
9043 @geindex -gnateF (gcc)
9046 @table @asis
9048 @item @code{-gnateF}
9050 Check for overflow on all floating-point operations, including those
9051 for unconstrained predefined types. See description of pragma
9052 @code{Check_Float_Overflow} in GNAT RM.
9053 @end table
9055 @geindex -gnateg (gcc)
9057 @code{-gnateg}
9058 @code{-gnatceg}
9060 @quotation
9062 The @code{-gnatc} switch must always be specified before this switch, e.g.
9063 @code{-gnatceg}. Generate a C header from the Ada input file. See
9064 @ref{b7,,Generating C Headers for Ada Specifications} for more
9065 information.
9066 @end quotation
9068 @geindex -gnateG (gcc)
9071 @table @asis
9073 @item @code{-gnateG}
9075 Save result of preprocessing in a text file.
9076 @end table
9078 @geindex -gnatei (gcc)
9081 @table @asis
9083 @item @code{-gnatei@emph{nnn}}
9085 Set maximum number of instantiations during compilation of a single unit to
9086 @code{nnn}. This may be useful in increasing the default maximum of 8000 for
9087 the rare case when a single unit legitimately exceeds this limit.
9088 @end table
9090 @geindex -gnateI (gcc)
9093 @table @asis
9095 @item @code{-gnateI@emph{nnn}}
9097 Indicates that the source is a multi-unit source and that the index of the
9098 unit to compile is @code{nnn}. @code{nnn} needs to be a positive number and need
9099 to be a valid index in the multi-unit source.
9100 @end table
9102 @geindex -gnatel (gcc)
9105 @table @asis
9107 @item @code{-gnatel}
9109 This switch can be used with the static elaboration model to issue info
9110 messages showing
9111 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
9112 are generated. This is useful in diagnosing elaboration circularities
9113 caused by these implicit pragmas when using the static elaboration
9114 model. See See the section in this guide on elaboration checking for
9115 further details. These messages are not generated by default, and are
9116 intended only for temporary use when debugging circularity problems.
9117 @end table
9119 @geindex -gnatel (gcc)
9122 @table @asis
9124 @item @code{-gnateL}
9126 This switch turns off the info messages about implicit elaboration pragmas.
9127 @end table
9129 @geindex -gnatem (gcc)
9132 @table @asis
9134 @item @code{-gnatem=@emph{path}}
9136 Specify a mapping file
9137 (the equal sign is optional)
9138 (@ref{e8,,Units to Sources Mapping Files}).
9139 @end table
9141 @geindex -gnatep (gcc)
9144 @table @asis
9146 @item @code{-gnatep=@emph{file}}
9148 Specify a preprocessing data file
9149 (the equal sign is optional)
9150 (@ref{90,,Integrated Preprocessing}).
9151 @end table
9153 @geindex -gnateP (gcc)
9156 @table @asis
9158 @item @code{-gnateP}
9160 Turn categorization dependency errors into warnings.
9161 Ada requires that units that WITH one another have compatible categories, for
9162 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9163 these errors become warnings (which can be ignored, or suppressed in the usual
9164 manner). This can be useful in some specialized circumstances such as the
9165 temporary use of special test software.
9166 @end table
9168 @geindex -gnateS (gcc)
9171 @table @asis
9173 @item @code{-gnateS}
9175 Synonym of @code{-fdump-scos}, kept for backwards compatibility.
9176 @end table
9178 @geindex -gnatet=file (gcc)
9181 @table @asis
9183 @item @code{-gnatet=@emph{path}}
9185 Generate target dependent information. The format of the output file is
9186 described in the section about switch @code{-gnateT}.
9187 @end table
9189 @geindex -gnateT (gcc)
9192 @table @asis
9194 @item @code{-gnateT=@emph{path}}
9196 Read target dependent information, such as endianness or sizes and alignments
9197 of base type. If this switch is passed, the default target dependent
9198 information of the compiler is replaced by the one read from the input file.
9199 This is used by tools other than the compiler, e.g. to do
9200 semantic analysis of programs that will run on some other target than
9201 the machine on which the tool is run.
9203 The following target dependent values should be defined,
9204 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
9205 positive integer value, and fields marked with a question mark are
9206 boolean fields, where a value of 0 is False, and a value of 1 is True:
9208 @example
9209 Bits_BE                    : Nat; -- Bits stored big-endian?
9210 Bits_Per_Unit              : Pos; -- Bits in a storage unit
9211 Bits_Per_Word              : Pos; -- Bits in a word
9212 Bytes_BE                   : Nat; -- Bytes stored big-endian?
9213 Char_Size                  : Pos; -- Standard.Character'Size
9214 Double_Float_Alignment     : Nat; -- Alignment of double float
9215 Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
9216 Double_Size                : Pos; -- Standard.Long_Float'Size
9217 Float_Size                 : Pos; -- Standard.Float'Size
9218 Float_Words_BE             : Nat; -- Float words stored big-endian?
9219 Int_Size                   : Pos; -- Standard.Integer'Size
9220 Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
9221 Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
9222 Long_Size                  : Pos; -- Standard.Long_Integer'Size
9223 Maximum_Alignment          : Pos; -- Maximum permitted alignment
9224 Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
9225 Pointer_Size               : Pos; -- System.Address'Size
9226 Short_Enums                : Nat; -- Foreign enums use short size?
9227 Short_Size                 : Pos; -- Standard.Short_Integer'Size
9228 Strict_Alignment           : Nat; -- Strict alignment?
9229 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9230 Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
9231 Words_BE                   : Nat; -- Words stored big-endian?
9232 @end example
9234 @code{Bits_Per_Unit} is the number of bits in a storage unit, the equivalent of
9235 GCC macro @code{BITS_PER_UNIT} documented as follows: @cite{Define this macro to be the number of bits in an addressable storage unit (byte); normally 8.}
9237 @code{Bits_Per_Word} is the number of bits in a machine word, the equivalent of
9238 GCC macro @code{BITS_PER_WORD} documented as follows: @cite{Number of bits in a word; normally 32.}
9240 @code{Double_Float_Alignment}, if not zero, is the maximum alignment that the
9241 compiler can choose by default for a 64-bit floating-point type or object.
9243 @code{Double_Scalar_Alignment}, if not zero, is the maximum alignment that the
9244 compiler can choose by default for a 64-bit or larger scalar type or object.
9246 @code{Maximum_Alignment} is the maximum alignment that the compiler can choose
9247 by default for a type or object, which is also the maximum alignment that can
9248 be specified in GNAT. It is computed for GCC backends as @code{BIGGEST_ALIGNMENT
9249 / BITS_PER_UNIT} where GCC macro @code{BIGGEST_ALIGNMENT} is documented as
9250 follows: @cite{Biggest alignment that any data type can require on this machine@comma{} in bits.}
9252 @code{Max_Unaligned_Field} is the maximum size for unaligned bit field, which is
9253 64 for the majority of GCC targets (but can be different on some targets).
9255 @code{Strict_Alignment} is the equivalent of GCC macro @code{STRICT_ALIGNMENT}
9256 documented as follows: @cite{Define this macro to be the value 1 if instructions will fail to work if given data not on the nominal alignment. If instructions will merely go slower in that case@comma{} define this macro as 0.}
9258 @code{System_Allocator_Alignment} is the guaranteed alignment of data returned
9259 by calls to @code{malloc}.
9261 The format of the input file is as follows. First come the values of
9262 the variables defined above, with one line per value:
9264 @example
9265 name  value
9266 @end example
9268 where @code{name} is the name of the parameter, spelled out in full,
9269 and cased as in the above list, and @code{value} is an unsigned decimal
9270 integer. Two or more blanks separates the name from the value.
9272 All the variables must be present, in alphabetical order (i.e. the
9273 same order as the list above).
9275 Then there is a blank line to separate the two parts of the file. Then
9276 come the lines showing the floating-point types to be registered, with
9277 one line per registered mode:
9279 @example
9280 name  digs float_rep size alignment
9281 @end example
9283 where @code{name} is the string name of the type (which can have
9284 single spaces embedded in the name, e.g. long double), @code{digs} is
9285 the number of digits for the floating-point type, @code{float_rep} is
9286 the float representation (I for IEEE-754-Binary, which is
9287 the only one supported at this time),
9288 @code{size} is the size in bits, @code{alignment} is the
9289 alignment in bits. The name is followed by at least two blanks, fields
9290 are separated by at least one blank, and a LF character immediately
9291 follows the alignment field.
9293 Here is an example of a target parameterization file:
9295 @example
9296 Bits_BE                       0
9297 Bits_Per_Unit                 8
9298 Bits_Per_Word                64
9299 Bytes_BE                      0
9300 Char_Size                     8
9301 Double_Float_Alignment        0
9302 Double_Scalar_Alignment       0
9303 Double_Size                  64
9304 Float_Size                   32
9305 Float_Words_BE                0
9306 Int_Size                     64
9307 Long_Double_Size            128
9308 Long_Long_Size               64
9309 Long_Size                    64
9310 Maximum_Alignment            16
9311 Max_Unaligned_Field          64
9312 Pointer_Size                 64
9313 Short_Size                   16
9314 Strict_Alignment              0
9315 System_Allocator_Alignment   16
9316 Wchar_T_Size                 32
9317 Words_BE                      0
9319 float         15  I  64  64
9320 double        15  I  64  64
9321 long double   18  I  80 128
9322 TF            33  I 128 128
9323 @end example
9324 @end table
9326 @geindex -gnateu (gcc)
9329 @table @asis
9331 @item @code{-gnateu}
9333 Ignore unrecognized validity, warning, and style switches that
9334 appear after this switch is given. This may be useful when
9335 compiling sources developed on a later version of the compiler
9336 with an earlier version. Of course the earlier version must
9337 support this switch.
9338 @end table
9340 @geindex -gnateV (gcc)
9343 @table @asis
9345 @item @code{-gnateV}
9347 Check that all actual parameters of a subprogram call are valid according to
9348 the rules of validity checking (@ref{e7,,Validity Checking}).
9349 @end table
9351 @geindex -gnateY (gcc)
9354 @table @asis
9356 @item @code{-gnateY}
9358 Ignore all STYLE_CHECKS pragmas. Full legality checks
9359 are still carried out, but the pragmas have no effect
9360 on what style checks are active. This allows all style
9361 checking options to be controlled from the command line.
9362 @end table
9364 @geindex -gnatE (gcc)
9367 @table @asis
9369 @item @code{-gnatE}
9371 Dynamic elaboration checking mode enabled. For further details see
9372 @ref{f,,Elaboration Order Handling in GNAT}.
9373 @end table
9375 @geindex -gnatf (gcc)
9378 @table @asis
9380 @item @code{-gnatf}
9382 Full errors. Multiple errors per line, all undefined references, do not
9383 attempt to suppress cascaded errors.
9384 @end table
9386 @geindex -gnatF (gcc)
9389 @table @asis
9391 @item @code{-gnatF}
9393 Externals names are folded to all uppercase.
9394 @end table
9396 @geindex -gnatg (gcc)
9399 @table @asis
9401 @item @code{-gnatg}
9403 Internal GNAT implementation mode. This should not be used for applications
9404 programs, it is intended only for use by the compiler and its run-time
9405 library. For documentation, see the GNAT sources. Note that @code{-gnatg}
9406 implies @code{-gnatw.ge} and @code{-gnatyg} so that all standard
9407 warnings and all standard style options are turned on. All warnings and style
9408 messages are treated as errors.
9409 @end table
9411 @geindex -gnatG[nn] (gcc)
9414 @table @asis
9416 @item @code{-gnatG=nn}
9418 List generated expanded code in source form.
9419 @end table
9421 @geindex -gnath (gcc)
9424 @table @asis
9426 @item @code{-gnath}
9428 Output usage information. The output is written to @code{stdout}.
9429 @end table
9431 @geindex -gnatH (gcc)
9434 @table @asis
9436 @item @code{-gnatH}
9438 Legacy elaboration-checking mode enabled. When this switch is in effect,
9439 the pre-18.x access-before-elaboration model becomes the de facto model.
9440 For further details see @ref{f,,Elaboration Order Handling in GNAT}.
9441 @end table
9443 @geindex -gnati (gcc)
9446 @table @asis
9448 @item @code{-gnati@emph{c}}
9450 Identifier character set (@code{c} = 1/2/3/4/5/9/p/8/f/n/w).
9451 For details of the possible selections for @code{c},
9452 see @ref{31,,Character Set Control}.
9453 @end table
9455 @geindex -gnatI (gcc)
9458 @table @asis
9460 @item @code{-gnatI}
9462 Ignore representation clauses. When this switch is used,
9463 representation clauses are treated as comments. This is useful
9464 when initially porting code where you want to ignore rep clause
9465 problems, and also for compiling foreign code (particularly
9466 for use with ASIS). The representation clauses that are ignored
9467 are: enumeration_representation_clause, record_representation_clause,
9468 and attribute_definition_clause for the following attributes:
9469 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9470 Object_Size, Scalar_Storage_Order, Size, Small, Stream_Size,
9471 and Value_Size. Pragma Default_Scalar_Storage_Order is also ignored.
9472 Note that this option should be used only for compiling – the
9473 code is likely to malfunction at run time.
9474 @end table
9476 @geindex -gnatjnn (gcc)
9479 @table @asis
9481 @item @code{-gnatj@emph{nn}}
9483 Reformat error messages to fit on @code{nn} character lines
9484 @end table
9486 @geindex -gnatJ (gcc)
9489 @table @asis
9491 @item @code{-gnatJ}
9493 Permissive elaboration-checking mode enabled. When this switch is in effect,
9494 the post-18.x access-before-elaboration model ignores potential issues with:
9497 @itemize -
9499 @item 
9500 Accept statements
9502 @item 
9503 Activations of tasks defined in instances
9505 @item 
9506 Assertion pragmas
9508 @item 
9509 Calls from within an instance to its enclosing context
9511 @item 
9512 Calls through generic formal parameters
9514 @item 
9515 Calls to subprograms defined in instances
9517 @item 
9518 Entry calls
9520 @item 
9521 Indirect calls using ‘Access
9523 @item 
9524 Requeue statements
9526 @item 
9527 Select statements
9529 @item 
9530 Synchronous task suspension
9531 @end itemize
9533 and does not emit compile-time diagnostics or run-time checks. For further
9534 details see @ref{f,,Elaboration Order Handling in GNAT}.
9535 @end table
9537 @geindex -gnatk (gcc)
9540 @table @asis
9542 @item @code{-gnatk=@emph{n}}
9544 Limit file names to @code{n} (1-999) characters (@code{k} = krunch).
9545 @end table
9547 @geindex -gnatl (gcc)
9550 @table @asis
9552 @item @code{-gnatl}
9554 Output full source listing with embedded error messages.
9555 @end table
9557 @geindex -gnatL (gcc)
9560 @table @asis
9562 @item @code{-gnatL}
9564 Used in conjunction with -gnatG or -gnatD to intersperse original
9565 source lines (as comment lines with line numbers) in the expanded
9566 source output.
9567 @end table
9569 @geindex -gnatm (gcc)
9572 @table @asis
9574 @item @code{-gnatm=@emph{n}}
9576 Limit number of detected error or warning messages to @code{n}
9577 where @code{n} is in the range 1..999999. The default setting if
9578 no switch is given is 9999. If the number of warnings reaches this
9579 limit, then a message is output and further warnings are suppressed,
9580 but the compilation is continued. If the number of error messages
9581 reaches this limit, then a message is output and the compilation
9582 is abandoned. The equal sign here is optional. A value of zero
9583 means that no limit applies.
9584 @end table
9586 @geindex -gnatn (gcc)
9589 @table @asis
9591 @item @code{-gnatn[12]}
9593 Activate inlining across units for subprograms for which pragma @code{Inline}
9594 is specified. This inlining is performed by the GCC back-end. An optional
9595 digit sets the inlining level: 1 for moderate inlining across units
9596 or 2 for full inlining across units. If no inlining level is specified,
9597 the compiler will pick it based on the optimization level.
9598 @end table
9600 @geindex -gnatN (gcc)
9603 @table @asis
9605 @item @code{-gnatN}
9607 Activate front end inlining for subprograms for which
9608 pragma @code{Inline} is specified. This inlining is performed
9609 by the front end and will be visible in the
9610 @code{-gnatG} output.
9612 When using a gcc-based back end, then the use of
9613 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
9614 Historically front end inlining was more extensive than the gcc back end
9615 inlining, but that is no longer the case.
9616 @end table
9618 @geindex -gnato0 (gcc)
9621 @table @asis
9623 @item @code{-gnato0}
9625 Suppresses overflow checking. This causes the behavior of the compiler to
9626 match the default for older versions where overflow checking was suppressed
9627 by default. This is equivalent to having
9628 @code{pragma Suppress (Overflow_Check)} in a configuration pragma file.
9629 @end table
9631 @geindex -gnato?? (gcc)
9634 @table @asis
9636 @item @code{-gnato??}
9638 Set default mode for handling generation of code to avoid intermediate
9639 arithmetic overflow. Here @code{??} is two digits, a
9640 single digit, or nothing. Each digit is one of the digits @code{1}
9641 through @code{3}:
9644 @multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
9645 @item
9647 Digit
9649 @tab
9651 Interpretation
9653 @item
9655 @emph{1}
9657 @tab
9659 All intermediate overflows checked against base type (@code{STRICT})
9661 @item
9663 @emph{2}
9665 @tab
9667 Minimize intermediate overflows (@code{MINIMIZED})
9669 @item
9671 @emph{3}
9673 @tab
9675 Eliminate intermediate overflows (@code{ELIMINATED})
9677 @end multitable
9680 If only one digit appears, then it applies to all
9681 cases; if two digits are given, then the first applies outside
9682 assertions, pre/postconditions, and type invariants, and the second
9683 applies within assertions, pre/postconditions, and type invariants.
9685 If no digits follow the @code{-gnato}, then it is equivalent to
9686 @code{-gnato11},
9687 causing all intermediate overflows to be handled in strict
9688 mode.
9690 This switch also causes arithmetic overflow checking to be performed
9691 (as though @code{pragma Unsuppress (Overflow_Check)} had been specified).
9693 The default if no option @code{-gnato} is given is that overflow handling
9694 is in @code{STRICT} mode (computations done using the base type), and that
9695 overflow checking is enabled.
9697 Note that division by zero is a separate check that is not
9698 controlled by this switch (divide-by-zero checking is on by default).
9700 See also @ref{e9,,Specifying the Desired Mode}.
9701 @end table
9703 @geindex -gnatp (gcc)
9706 @table @asis
9708 @item @code{-gnatp}
9710 Suppress all checks. See @ref{ea,,Run-Time Checks} for details. This switch
9711 has no effect if cancelled by a subsequent @code{-gnat-p} switch.
9712 @end table
9714 @geindex -gnat-p (gcc)
9717 @table @asis
9719 @item @code{-gnat-p}
9721 Cancel effect of previous @code{-gnatp} switch.
9722 @end table
9724 @geindex -gnatq (gcc)
9727 @table @asis
9729 @item @code{-gnatq}
9731 Don’t quit. Try semantics, even if parse errors.
9732 @end table
9734 @geindex -gnatQ (gcc)
9737 @table @asis
9739 @item @code{-gnatQ}
9741 Don’t quit. Generate @code{ALI} and tree files even if illegalities.
9742 Note that code generation is still suppressed in the presence of any
9743 errors, so even with @code{-gnatQ} no object file is generated.
9744 @end table
9746 @geindex -gnatr (gcc)
9749 @table @asis
9751 @item @code{-gnatr}
9753 Treat pragma Restrictions as Restriction_Warnings.
9754 @end table
9756 @geindex -gnatR (gcc)
9759 @table @asis
9761 @item @code{-gnatR[0|1|2|3|4][e][j][m][s]}
9763 Output representation information for declared types, objects and
9764 subprograms. Note that this switch is not allowed if a previous
9765 @code{-gnatD} switch has been given, since these two switches
9766 are not compatible.
9767 @end table
9769 @geindex -gnats (gcc)
9772 @table @asis
9774 @item @code{-gnats}
9776 Syntax check only.
9777 @end table
9779 @geindex -gnatS (gcc)
9782 @table @asis
9784 @item @code{-gnatS}
9786 Print package Standard.
9787 @end table
9789 @geindex -gnatT (gcc)
9792 @table @asis
9794 @item @code{-gnatT@emph{nnn}}
9796 All compiler tables start at @code{nnn} times usual starting size.
9797 @end table
9799 @geindex -gnatu (gcc)
9802 @table @asis
9804 @item @code{-gnatu}
9806 List units for this compilation.
9807 @end table
9809 @geindex -gnatU (gcc)
9812 @table @asis
9814 @item @code{-gnatU}
9816 Tag all error messages with the unique string ‘error:’
9817 @end table
9819 @geindex -gnatv (gcc)
9822 @table @asis
9824 @item @code{-gnatv}
9826 Verbose mode. Full error output with source lines to @code{stdout}.
9827 @end table
9829 @geindex -gnatV (gcc)
9832 @table @asis
9834 @item @code{-gnatV}
9836 Control level of validity checking (@ref{e7,,Validity Checking}).
9837 @end table
9839 @geindex -gnatw (gcc)
9842 @table @asis
9844 @item @code{-gnatw@emph{xxx}}
9846 Warning mode where
9847 @code{xxx} is a string of option letters that denotes
9848 the exact warnings that
9849 are enabled or disabled (@ref{eb,,Warning Message Control}).
9850 @end table
9852 @geindex -gnatW (gcc)
9855 @table @asis
9857 @item @code{-gnatW@emph{e}}
9859 Wide character encoding method
9860 (@code{e}=n/h/u/s/e/8).
9861 @end table
9863 @geindex -gnatx (gcc)
9866 @table @asis
9868 @item @code{-gnatx}
9870 Suppress generation of cross-reference information.
9871 @end table
9873 @geindex -gnatX (gcc)
9876 @table @asis
9878 @item @code{-gnatX}
9880 Enable GNAT implementation extensions and latest Ada version.
9881 @end table
9883 @geindex -gnaty (gcc)
9886 @table @asis
9888 @item @code{-gnaty}
9890 Enable built-in style checks (@ref{ec,,Style Checking}).
9891 @end table
9893 @geindex -gnatz (gcc)
9896 @table @asis
9898 @item @code{-gnatz@emph{m}}
9900 Distribution stub generation and compilation
9901 (@code{m}=r/c for receiver/caller stubs).
9902 @end table
9904 @geindex -I (gcc)
9907 @table @asis
9909 @item @code{-I@emph{dir}}
9911 @geindex RTL
9913 Direct GNAT to search the @code{dir} directory for source files needed by
9914 the current compilation
9915 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
9916 @end table
9918 @geindex -I- (gcc)
9921 @table @asis
9923 @item @code{-I-}
9925 @geindex RTL
9927 Except for the source file named in the command line, do not look for source
9928 files in the directory containing the source file named in the command line
9929 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
9930 @end table
9932 @geindex -o (gcc)
9935 @table @asis
9937 @item @code{-o @emph{file}}
9939 This switch is used in @code{gcc} to redirect the generated object file
9940 and its associated ALI file. Beware of this switch with GNAT, because it may
9941 cause the object file and ALI file to have different names which in turn
9942 may confuse the binder and the linker.
9943 @end table
9945 @geindex -nostdinc (gcc)
9948 @table @asis
9950 @item @code{-nostdinc}
9952 Inhibit the search of the default location for the GNAT Run Time
9953 Library (RTL) source files.
9954 @end table
9956 @geindex -nostdlib (gcc)
9959 @table @asis
9961 @item @code{-nostdlib}
9963 Inhibit the search of the default location for the GNAT Run Time
9964 Library (RTL) ALI files.
9965 @end table
9967 @geindex -O (gcc)
9970 @table @asis
9972 @item @code{-O[@emph{n}]}
9974 @code{n} controls the optimization level:
9977 @multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
9978 @item
9980 @emph{n}
9982 @tab
9984 Effect
9986 @item
9988 @emph{0}
9990 @tab
9992 No optimization, the default setting if no @code{-O} appears
9994 @item
9996 @emph{1}
9998 @tab
10000 Normal optimization, the default if you specify @code{-O} without an
10001 operand. A good compromise between code quality and compilation
10002 time.
10004 @item
10006 @emph{2}
10008 @tab
10010 Extensive optimization, may improve execution time, possibly at
10011 the cost of substantially increased compilation time.
10013 @item
10015 @emph{3}
10017 @tab
10019 Same as @code{-O2}, and also includes inline expansion for small
10020 subprograms in the same unit.
10022 @item
10024 @emph{s}
10026 @tab
10028 Optimize space usage
10030 @end multitable
10033 See also @ref{ed,,Optimization Levels}.
10034 @end table
10036 @geindex -pass-exit-codes (gcc)
10039 @table @asis
10041 @item @code{-pass-exit-codes}
10043 Catch exit codes from the compiler and use the most meaningful as
10044 exit status.
10045 @end table
10047 @geindex --RTS (gcc)
10050 @table @asis
10052 @item @code{--RTS=@emph{rts-path}}
10054 Specifies the default location of the run-time library. Same meaning as the
10055 equivalent @code{gnatmake} flag (@ref{ce,,Switches for gnatmake}).
10056 @end table
10058 @geindex -S (gcc)
10061 @table @asis
10063 @item @code{-S}
10065 Used in place of @code{-c} to
10066 cause the assembler source file to be
10067 generated, using @code{.s} as the extension,
10068 instead of the object file.
10069 This may be useful if you need to examine the generated assembly code.
10070 @end table
10072 @geindex -fverbose-asm (gcc)
10075 @table @asis
10077 @item @code{-fverbose-asm}
10079 Used in conjunction with @code{-S}
10080 to cause the generated assembly code file to be annotated with variable
10081 names, making it significantly easier to follow.
10082 @end table
10084 @geindex -v (gcc)
10087 @table @asis
10089 @item @code{-v}
10091 Show commands generated by the @code{gcc} driver. Normally used only for
10092 debugging purposes or if you need to be sure what version of the
10093 compiler you are executing.
10094 @end table
10096 @geindex -V (gcc)
10099 @table @asis
10101 @item @code{-V @emph{ver}}
10103 Execute @code{ver} version of the compiler. This is the @code{gcc}
10104 version, not the GNAT version.
10105 @end table
10107 @geindex -w (gcc)
10110 @table @asis
10112 @item @code{-w}
10114 Turn off warnings generated by the back end of the compiler. Use of
10115 this switch also causes the default for front end warnings to be set
10116 to suppress (as though @code{-gnatws} had appeared at the start of
10117 the options).
10118 @end table
10120 @geindex Combining GNAT switches
10122 You may combine a sequence of GNAT switches into a single switch. For
10123 example, the combined switch
10125 @quotation
10127 @example
10128 -gnatofi3
10129 @end example
10130 @end quotation
10132 is equivalent to specifying the following sequence of switches:
10134 @quotation
10136 @example
10137 -gnato -gnatf -gnati3
10138 @end example
10139 @end quotation
10141 The following restrictions apply to the combination of switches
10142 in this manner:
10145 @itemize *
10147 @item 
10148 The switch @code{-gnatc} if combined with other switches must come
10149 first in the string.
10151 @item 
10152 The switch @code{-gnats} if combined with other switches must come
10153 first in the string.
10155 @item 
10156 The switches
10157 @code{-gnatzc} and @code{-gnatzr} may not be combined with any other
10158 switches, and only one of them may appear in the command line.
10160 @item 
10161 The switch @code{-gnat-p} may not be combined with any other switch.
10163 @item 
10164 Once a ‘y’ appears in the string (that is a use of the @code{-gnaty}
10165 switch), then all further characters in the switch are interpreted
10166 as style modifiers (see description of @code{-gnaty}).
10168 @item 
10169 Once a ‘d’ appears in the string (that is a use of the @code{-gnatd}
10170 switch), then all further characters in the switch are interpreted
10171 as debug flags (see description of @code{-gnatd}).
10173 @item 
10174 Once a ‘w’ appears in the string (that is a use of the @code{-gnatw}
10175 switch), then all further characters in the switch are interpreted
10176 as warning mode modifiers (see description of @code{-gnatw}).
10178 @item 
10179 Once a ‘V’ appears in the string (that is a use of the @code{-gnatV}
10180 switch), then all further characters in the switch are interpreted
10181 as validity checking options (@ref{e7,,Validity Checking}).
10183 @item 
10184 Option ‘em’, ‘ec’, ‘ep’, ‘l=’ and ‘R’ must be the last options in
10185 a combined list of options.
10186 @end itemize
10188 @node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10189 @anchor{gnat_ugn/building_executable_programs_with_gnat id14}@anchor{ee}@anchor{gnat_ugn/building_executable_programs_with_gnat output-and-error-message-control}@anchor{ef}
10190 @subsection Output and Error Message Control
10193 @geindex stderr
10195 The standard default format for error messages is called ‘brief format’.
10196 Brief format messages are written to @code{stderr} (the standard error
10197 file) and have the following form:
10199 @example
10200 e.adb:3:04: Incorrect spelling of keyword "function"
10201 e.adb:4:20: ";" should be "is"
10202 @end example
10204 The first integer after the file name is the line number in the file,
10205 and the second integer is the column number within the line.
10206 @code{GNAT Studio} can parse the error messages
10207 and point to the referenced character.
10208 The following switches provide control over the error message
10209 format:
10211 @geindex -gnatv (gcc)
10214 @table @asis
10216 @item @code{-gnatv}
10218 The @code{v} stands for verbose.
10219 The effect of this setting is to write long-format error
10220 messages to @code{stdout} (the standard output file).
10221 The same program compiled with the
10222 @code{-gnatv} switch would generate:
10224 @example
10225 3. funcion X (Q : Integer)
10226    |
10227 >>> Incorrect spelling of keyword "function"
10228 4. return Integer;
10229                  |
10230 >>> ";" should be "is"
10231 @end example
10233 The vertical bar indicates the location of the error, and the @code{>>>}
10234 prefix can be used to search for error messages. When this switch is
10235 used the only source lines output are those with errors.
10236 @end table
10238 @geindex -gnatl (gcc)
10241 @table @asis
10243 @item @code{-gnatl}
10245 The @code{l} stands for list.
10246 This switch causes a full listing of
10247 the file to be generated. In the case where a body is
10248 compiled, the corresponding spec is also listed, along
10249 with any subunits. Typical output from compiling a package
10250 body @code{p.adb} might look like:
10252 @example
10253 Compiling: p.adb
10255      1. package body p is
10256      2.    procedure a;
10257      3.    procedure a is separate;
10258      4. begin
10259      5.    null
10260                |
10261         >>> missing ";"
10263      6. end;
10265 Compiling: p.ads
10267      1. package p is
10268      2.    pragma Elaborate_Body
10269                                 |
10270         >>> missing ";"
10272      3. end p;
10274 Compiling: p-a.adb
10276      1. separate p
10277                 |
10278         >>> missing "("
10280      2. procedure a is
10281      3. begin
10282      4.    null
10283                |
10284         >>> missing ";"
10286      5. end;
10287 @end example
10289 When you specify the @code{-gnatv} or @code{-gnatl} switches and
10290 standard output is redirected, a brief summary is written to
10291 @code{stderr} (standard error) giving the number of error messages and
10292 warning messages generated.
10293 @end table
10295 @geindex -gnatl=fname (gcc)
10298 @table @asis
10300 @item @code{-gnatl=@emph{fname}}
10302 This has the same effect as @code{-gnatl} except that the output is
10303 written to a file instead of to standard output. If the given name
10304 @code{fname} does not start with a period, then it is the full name
10305 of the file to be written. If @code{fname} is an extension, it is
10306 appended to the name of the file being compiled. For example, if
10307 file @code{xyz.adb} is compiled with @code{-gnatl=.lst},
10308 then the output is written to file xyz.adb.lst.
10309 @end table
10311 @geindex -gnatU (gcc)
10314 @table @asis
10316 @item @code{-gnatU}
10318 This switch forces all error messages to be preceded by the unique
10319 string ‘error:’. This means that error messages take a few more
10320 characters in space, but allows easy searching for and identification
10321 of error messages.
10322 @end table
10324 @geindex -gnatb (gcc)
10327 @table @asis
10329 @item @code{-gnatb}
10331 The @code{b} stands for brief.
10332 This switch causes GNAT to generate the
10333 brief format error messages to @code{stderr} (the standard error
10334 file) as well as the verbose
10335 format message or full listing (which as usual is written to
10336 @code{stdout}, the standard output file).
10337 @end table
10339 @geindex -gnatm (gcc)
10342 @table @asis
10344 @item @code{-gnatm=@emph{n}}
10346 The @code{m} stands for maximum.
10347 @code{n} is a decimal integer in the
10348 range of 1 to 999999 and limits the number of error or warning
10349 messages to be generated. For example, using
10350 @code{-gnatm2} might yield
10352 @example
10353 e.adb:3:04: Incorrect spelling of keyword "function"
10354 e.adb:5:35: missing ".."
10355 fatal error: maximum number of errors detected
10356 compilation abandoned
10357 @end example
10359 The default setting if
10360 no switch is given is 9999. If the number of warnings reaches this
10361 limit, then a message is output and further warnings are suppressed,
10362 but the compilation is continued. If the number of error messages
10363 reaches this limit, then a message is output and the compilation
10364 is abandoned. A value of zero means that no limit applies.
10366 Note that the equal sign is optional, so the switches
10367 @code{-gnatm2} and @code{-gnatm=2} are equivalent.
10368 @end table
10370 @geindex -gnatf (gcc)
10373 @table @asis
10375 @item @code{-gnatf}
10377 @geindex Error messages
10378 @geindex suppressing
10380 The @code{f} stands for full.
10381 Normally, the compiler suppresses error messages that are likely to be
10382 redundant. This switch causes all error
10383 messages to be generated. In particular, in the case of
10384 references to undefined variables. If a given variable is referenced
10385 several times, the normal format of messages is
10387 @example
10388 e.adb:7:07: "V" is undefined (more references follow)
10389 @end example
10391 where the parenthetical comment warns that there are additional
10392 references to the variable @code{V}. Compiling the same program with the
10393 @code{-gnatf} switch yields
10395 @example
10396 e.adb:7:07: "V" is undefined
10397 e.adb:8:07: "V" is undefined
10398 e.adb:8:12: "V" is undefined
10399 e.adb:8:16: "V" is undefined
10400 e.adb:9:07: "V" is undefined
10401 e.adb:9:12: "V" is undefined
10402 @end example
10404 The @code{-gnatf} switch also generates additional information for
10405 some error messages.  Some examples are:
10408 @itemize *
10410 @item 
10411 Details on possibly non-portable unchecked conversion
10413 @item 
10414 List possible interpretations for ambiguous calls
10416 @item 
10417 Additional details on incorrect parameters
10418 @end itemize
10419 @end table
10421 @geindex -gnatjnn (gcc)
10424 @table @asis
10426 @item @code{-gnatjnn}
10428 In normal operation mode (or if @code{-gnatj0} is used), then error messages
10429 with continuation lines are treated as though the continuation lines were
10430 separate messages (and so a warning with two continuation lines counts as
10431 three warnings, and is listed as three separate messages).
10433 If the @code{-gnatjnn} switch is used with a positive value for nn, then
10434 messages are output in a different manner. A message and all its continuation
10435 lines are treated as a unit, and count as only one warning or message in the
10436 statistics totals. Furthermore, the message is reformatted so that no line
10437 is longer than nn characters.
10438 @end table
10440 @geindex -gnatq (gcc)
10443 @table @asis
10445 @item @code{-gnatq}
10447 The @code{q} stands for quit (really ‘don’t quit’).
10448 In normal operation mode, the compiler first parses the program and
10449 determines if there are any syntax errors. If there are, appropriate
10450 error messages are generated and compilation is immediately terminated.
10451 This switch tells
10452 GNAT to continue with semantic analysis even if syntax errors have been
10453 found. This may enable the detection of more errors in a single run. On
10454 the other hand, the semantic analyzer is more likely to encounter some
10455 internal fatal error when given a syntactically invalid tree.
10456 @end table
10458 @geindex -gnatQ (gcc)
10461 @table @asis
10463 @item @code{-gnatQ}
10465 In normal operation mode, the @code{ALI} file is not generated if any
10466 illegalities are detected in the program. The use of @code{-gnatQ} forces
10467 generation of the @code{ALI} file. This file is marked as being in
10468 error, so it cannot be used for binding purposes, but it does contain
10469 reasonably complete cross-reference information, and thus may be useful
10470 for use by tools (e.g., semantic browsing tools or integrated development
10471 environments) that are driven from the @code{ALI} file. This switch
10472 implies @code{-gnatq}, since the semantic phase must be run to get a
10473 meaningful ALI file.
10475 When @code{-gnatQ} is used and the generated @code{ALI} file is marked as
10476 being in error, @code{gnatmake} will attempt to recompile the source when it
10477 finds such an @code{ALI} file, including with switch @code{-gnatc}.
10479 Note that @code{-gnatQ} has no effect if @code{-gnats} is specified,
10480 since ALI files are never generated if @code{-gnats} is set.
10481 @end table
10483 @node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10484 @anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{f0}@anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{eb}
10485 @subsection Warning Message Control
10488 @geindex Warning messages
10490 In addition to error messages, which correspond to illegalities as defined
10491 in the Ada Reference Manual, the compiler detects two kinds of warning
10492 situations.
10494 First, the compiler considers some constructs suspicious and generates a
10495 warning message to alert you to a possible error. Second, if the
10496 compiler detects a situation that is sure to raise an exception at
10497 run time, it generates a warning message. The following shows an example
10498 of warning messages:
10500 @example
10501 e.adb:4:24: warning: creation of object may raise Storage_Error
10502 e.adb:10:17: warning: static value out of range
10503 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10504 @end example
10506 GNAT considers a large number of situations as appropriate
10507 for the generation of warning messages. As always, warnings are not
10508 definite indications of errors. For example, if you do an out-of-range
10509 assignment with the deliberate intention of raising a
10510 @code{Constraint_Error} exception, then the warning that may be
10511 issued does not indicate an error. Some of the situations for which GNAT
10512 issues warnings (at least some of the time) are given in the following
10513 list. This list is not complete, and new warnings are often added to
10514 subsequent versions of GNAT. The list is intended to give a general idea
10515 of the kinds of warnings that are generated.
10518 @itemize *
10520 @item 
10521 Possible infinitely recursive calls
10523 @item 
10524 Out-of-range values being assigned
10526 @item 
10527 Possible order of elaboration problems
10529 @item 
10530 Size not a multiple of alignment for a record type
10532 @item 
10533 Assertions (pragma Assert) that are sure to fail
10535 @item 
10536 Unreachable code
10538 @item 
10539 Address clauses with possibly unaligned values, or where an attempt is
10540 made to overlay a smaller variable with a larger one.
10542 @item 
10543 Fixed-point type declarations with a null range
10545 @item 
10546 Direct_IO or Sequential_IO instantiated with a type that has access values
10548 @item 
10549 Variables that are never assigned a value
10551 @item 
10552 Variables that are referenced before being initialized
10554 @item 
10555 Task entries with no corresponding @code{accept} statement
10557 @item 
10558 Duplicate accepts for the same task entry in a @code{select}
10560 @item 
10561 Objects that take too much storage
10563 @item 
10564 Unchecked conversion between types of differing sizes
10566 @item 
10567 Missing @code{return} statement along some execution path in a function
10569 @item 
10570 Incorrect (unrecognized) pragmas
10572 @item 
10573 Incorrect external names
10575 @item 
10576 Allocation from empty storage pool
10578 @item 
10579 Potentially blocking operation in protected type
10581 @item 
10582 Suspicious parenthesization of expressions
10584 @item 
10585 Mismatching bounds in an aggregate
10587 @item 
10588 Attempt to return local value by reference
10590 @item 
10591 Premature instantiation of a generic body
10593 @item 
10594 Attempt to pack aliased components
10596 @item 
10597 Out of bounds array subscripts
10599 @item 
10600 Wrong length on string assignment
10602 @item 
10603 Violations of style rules if style checking is enabled
10605 @item 
10606 Unused @emph{with} clauses
10608 @item 
10609 @code{Bit_Order} usage that does not have any effect
10611 @item 
10612 @code{Standard.Duration} used to resolve universal fixed expression
10614 @item 
10615 Dereference of possibly null value
10617 @item 
10618 Declaration that is likely to cause storage error
10620 @item 
10621 Internal GNAT unit @emph{with}ed by application unit
10623 @item 
10624 Values known to be out of range at compile time
10626 @item 
10627 Unreferenced or unmodified variables. Note that a special
10628 exemption applies to variables which contain any of the substrings
10629 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
10630 are considered likely to be intentionally used in a situation where
10631 otherwise a warning would be given, so warnings of this kind are
10632 always suppressed for such variables.
10634 @item 
10635 Address overlays that could clobber memory
10637 @item 
10638 Unexpected initialization when address clause present
10640 @item 
10641 Bad alignment for address clause
10643 @item 
10644 Useless type conversions
10646 @item 
10647 Redundant assignment statements and other redundant constructs
10649 @item 
10650 Useless exception handlers
10652 @item 
10653 Accidental hiding of name by child unit
10655 @item 
10656 Access before elaboration detected at compile time
10658 @item 
10659 A range in a @code{for} loop that is known to be null or might be null
10660 @end itemize
10662 The following section lists compiler switches that are available
10663 to control the handling of warning messages. It is also possible
10664 to exercise much finer control over what warnings are issued and
10665 suppressed using the GNAT pragma Warnings (see the description
10666 of the pragma in the @cite{GNAT_Reference_manual}).
10668 @geindex -gnatwa (gcc)
10671 @table @asis
10673 @item @code{-gnatwa}
10675 @emph{Activate most optional warnings.}
10677 This switch activates most optional warning messages. See the remaining list
10678 in this section for details on optional warning messages that can be
10679 individually controlled.  The warnings that are not turned on by this
10680 switch are:
10683 @itemize *
10685 @item 
10686 @code{-gnatwd} (implicit dereferencing)
10688 @item 
10689 @code{-gnatw.d} (tag warnings with -gnatw switch)
10691 @item 
10692 @code{-gnatwh} (hiding)
10694 @item 
10695 @code{-gnatw.h} (holes in record layouts)
10697 @item 
10698 @code{-gnatw.j} (late primitives of tagged types)
10700 @item 
10701 @code{-gnatw.k} (redefinition of names in standard)
10703 @item 
10704 @code{-gnatwl} (elaboration warnings)
10706 @item 
10707 @code{-gnatw.l} (inherited aspects)
10709 @item 
10710 @code{-gnatw.n} (atomic synchronization)
10712 @item 
10713 @code{-gnatwo} (address clause overlay)
10715 @item 
10716 @code{-gnatw.o} (values set by out parameters ignored)
10718 @item 
10719 @code{-gnatw.q} (questionable layout of record types)
10721 @item 
10722 @code{-gnatw_r} (out-of-order record representation clauses)
10724 @item 
10725 @code{-gnatw.s} (overridden size clause)
10727 @item 
10728 @code{-gnatwt} (tracking of deleted conditional code)
10730 @item 
10731 @code{-gnatw.u} (unordered enumeration)
10733 @item 
10734 @code{-gnatw.w} (use of Warnings Off)
10736 @item 
10737 @code{-gnatw.y} (reasons for package needing body)
10738 @end itemize
10740 All other optional warnings are turned on.
10741 @end table
10743 @geindex -gnatwA (gcc)
10746 @table @asis
10748 @item @code{-gnatwA}
10750 @emph{Suppress all optional errors.}
10752 This switch suppresses all optional warning messages, see remaining list
10753 in this section for details on optional warning messages that can be
10754 individually controlled. Note that unlike switch @code{-gnatws}, the
10755 use of switch @code{-gnatwA} does not suppress warnings that are
10756 normally given unconditionally and cannot be individually controlled
10757 (for example, the warning about a missing exit path in a function).
10758 Also, again unlike switch @code{-gnatws}, warnings suppressed by
10759 the use of switch @code{-gnatwA} can be individually turned back
10760 on. For example the use of switch @code{-gnatwA} followed by
10761 switch @code{-gnatwd} will suppress all optional warnings except
10762 the warnings for implicit dereferencing.
10763 @end table
10765 @geindex -gnatw.a (gcc)
10768 @table @asis
10770 @item @code{-gnatw.a}
10772 @emph{Activate warnings on failing assertions.}
10774 @geindex Assert failures
10776 This switch activates warnings for assertions where the compiler can tell at
10777 compile time that the assertion will fail. Note that this warning is given
10778 even if assertions are disabled. The default is that such warnings are
10779 generated.
10780 @end table
10782 @geindex -gnatw.A (gcc)
10785 @table @asis
10787 @item @code{-gnatw.A}
10789 @emph{Suppress warnings on failing assertions.}
10791 @geindex Assert failures
10793 This switch suppresses warnings for assertions where the compiler can tell at
10794 compile time that the assertion will fail.
10795 @end table
10797 @geindex -gnatw_a
10800 @table @asis
10802 @item @code{-gnatw_a}
10804 @emph{Activate warnings on anonymous allocators.}
10806 @geindex Anonymous allocators
10808 This switch activates warnings for allocators of anonymous access types,
10809 which can involve run-time accessibility checks and lead to unexpected
10810 accessibility violations. For more details on the rules involved, see
10811 RM 3.10.2 (14).
10812 @end table
10814 @geindex -gnatw_A
10817 @table @asis
10819 @item @code{-gnatw_A}
10821 @emph{Supress warnings on anonymous allocators.}
10823 @geindex Anonymous allocators
10825 This switch suppresses warnings for anonymous access type allocators.
10826 @end table
10828 @geindex -gnatwb (gcc)
10831 @table @asis
10833 @item @code{-gnatwb}
10835 @emph{Activate warnings on bad fixed values.}
10837 @geindex Bad fixed values
10839 @geindex Fixed-point Small value
10841 @geindex Small value
10843 This switch activates warnings for static fixed-point expressions whose
10844 value is not an exact multiple of Small. Such values are implementation
10845 dependent, since an implementation is free to choose either of the multiples
10846 that surround the value. GNAT always chooses the closer one, but this is not
10847 required behavior, and it is better to specify a value that is an exact
10848 multiple, ensuring predictable execution. The default is that such warnings
10849 are not generated.
10850 @end table
10852 @geindex -gnatwB (gcc)
10855 @table @asis
10857 @item @code{-gnatwB}
10859 @emph{Suppress warnings on bad fixed values.}
10861 This switch suppresses warnings for static fixed-point expressions whose
10862 value is not an exact multiple of Small.
10863 @end table
10865 @geindex -gnatw.b (gcc)
10868 @table @asis
10870 @item @code{-gnatw.b}
10872 @emph{Activate warnings on biased representation.}
10874 @geindex Biased representation
10876 This switch activates warnings when a size clause, value size clause, component
10877 clause, or component size clause forces the use of biased representation for an
10878 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
10879 to represent 10/11). The default is that such warnings are generated.
10880 @end table
10882 @geindex -gnatwB (gcc)
10885 @table @asis
10887 @item @code{-gnatw.B}
10889 @emph{Suppress warnings on biased representation.}
10891 This switch suppresses warnings for representation clauses that force the use
10892 of biased representation.
10893 @end table
10895 @geindex -gnatwc (gcc)
10898 @table @asis
10900 @item @code{-gnatwc}
10902 @emph{Activate warnings on conditionals.}
10904 @geindex Conditionals
10905 @geindex constant
10907 This switch activates warnings for conditional expressions used in
10908 tests that are known to be True or False at compile time. The default
10909 is that such warnings are not generated.
10910 Note that this warning does
10911 not get issued for the use of boolean variables or constants whose
10912 values are known at compile time, since this is a standard technique
10913 for conditional compilation in Ada, and this would generate too many
10914 false positive warnings.
10916 This warning option also activates a special test for comparisons using
10917 the operators ‘>=’ and’ <=’.
10918 If the compiler can tell that only the equality condition is possible,
10919 then it will warn that the ‘>’ or ‘<’ part of the test
10920 is useless and that the operator could be replaced by ‘=’.
10921 An example would be comparing a @code{Natural} variable <= 0.
10923 This warning option also generates warnings if
10924 one or both tests is optimized away in a membership test for integer
10925 values if the result can be determined at compile time. Range tests on
10926 enumeration types are not included, since it is common for such tests
10927 to include an end point.
10929 This warning can also be turned on using @code{-gnatwa}.
10930 @end table
10932 @geindex -gnatwC (gcc)
10935 @table @asis
10937 @item @code{-gnatwC}
10939 @emph{Suppress warnings on conditionals.}
10941 This switch suppresses warnings for conditional expressions used in
10942 tests that are known to be True or False at compile time.
10943 @end table
10945 @geindex -gnatw.c (gcc)
10948 @table @asis
10950 @item @code{-gnatw.c}
10952 @emph{Activate warnings on missing component clauses.}
10954 @geindex Component clause
10955 @geindex missing
10957 This switch activates warnings for record components where a record
10958 representation clause is present and has component clauses for the
10959 majority, but not all, of the components. A warning is given for each
10960 component for which no component clause is present.
10961 @end table
10963 @geindex -gnatw.C (gcc)
10966 @table @asis
10968 @item @code{-gnatw.C}
10970 @emph{Suppress warnings on missing component clauses.}
10972 This switch suppresses warnings for record components that are
10973 missing a component clause in the situation described above.
10974 @end table
10976 @geindex -gnatw_c (gcc)
10979 @table @asis
10981 @item @code{-gnatw_c}
10983 @emph{Activate warnings on unknown condition in Compile_Time_Warning.}
10985 @geindex Compile_Time_Warning
10987 @geindex Compile_Time_Error
10989 This switch activates warnings on a pragma Compile_Time_Warning
10990 or Compile_Time_Error whose condition has a value that is not
10991 known at compile time.
10992 The default is that such warnings are generated.
10993 @end table
10995 @geindex -gnatw_C (gcc)
10998 @table @asis
11000 @item @code{-gnatw_C}
11002 @emph{Suppress warnings on unknown condition in Compile_Time_Warning.}
11004 This switch supresses warnings on a pragma Compile_Time_Warning
11005 or Compile_Time_Error whose condition has a value that is not
11006 known at compile time.
11007 @end table
11009 @geindex -gnatwd (gcc)
11012 @table @asis
11014 @item @code{-gnatwd}
11016 @emph{Activate warnings on implicit dereferencing.}
11018 If this switch is set, then the use of a prefix of an access type
11019 in an indexed component, slice, or selected component without an
11020 explicit @code{.all} will generate a warning. With this warning
11021 enabled, access checks occur only at points where an explicit
11022 @code{.all} appears in the source code (assuming no warnings are
11023 generated as a result of this switch). The default is that such
11024 warnings are not generated.
11025 @end table
11027 @geindex -gnatwD (gcc)
11030 @table @asis
11032 @item @code{-gnatwD}
11034 @emph{Suppress warnings on implicit dereferencing.}
11036 @geindex Implicit dereferencing
11038 @geindex Dereferencing
11039 @geindex implicit
11041 This switch suppresses warnings for implicit dereferences in
11042 indexed components, slices, and selected components.
11043 @end table
11045 @geindex -gnatw.d (gcc)
11048 @table @asis
11050 @item @code{-gnatw.d}
11052 @emph{Activate tagging of warning and info messages.}
11054 If this switch is set, then warning messages are tagged, with one of the
11055 following strings:
11057 @quotation
11060 @itemize -
11062 @item 
11063 @emph{[-gnatw?]}
11064 Used to tag warnings controlled by the switch @code{-gnatwx} where x
11065 is a letter a-z.
11067 @item 
11068 @emph{[-gnatw.?]}
11069 Used to tag warnings controlled by the switch @code{-gnatw.x} where x
11070 is a letter a-z.
11072 @item 
11073 @emph{[-gnatel]}
11074 Used to tag elaboration information (info) messages generated when the
11075 static model of elaboration is used and the @code{-gnatel} switch is set.
11077 @item 
11078 @emph{[restriction warning]}
11079 Used to tag warning messages for restriction violations, activated by use
11080 of the pragma @code{Restriction_Warnings}.
11082 @item 
11083 @emph{[warning-as-error]}
11084 Used to tag warning messages that have been converted to error messages by
11085 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
11086 the string “error: ” rather than “warning: “.
11088 @item 
11089 @emph{[enabled by default]}
11090 Used to tag all other warnings that are always given by default, unless
11091 warnings are completely suppressed using pragma @emph{Warnings(Off)} or
11092 the switch @code{-gnatws}.
11093 @end itemize
11094 @end quotation
11095 @end table
11097 @geindex -gnatw.d (gcc)
11100 @table @asis
11102 @item @code{-gnatw.D}
11104 @emph{Deactivate tagging of warning and info messages messages.}
11106 If this switch is set, then warning messages return to the default
11107 mode in which warnings and info messages are not tagged as described above for
11108 @code{-gnatw.d}.
11109 @end table
11111 @geindex -gnatwe (gcc)
11113 @geindex Warnings
11114 @geindex treat as error
11117 @table @asis
11119 @item @code{-gnatwe}
11121 @emph{Treat warnings and style checks as errors.}
11123 This switch causes warning messages and style check messages to be
11124 treated as errors.
11125 The warning string still appears, but the warning messages are counted
11126 as errors, and prevent the generation of an object file. Note that this
11127 is the only -gnatw switch that affects the handling of style check messages.
11128 Note also that this switch has no effect on info (information) messages, which
11129 are not treated as errors if this switch is present.
11130 @end table
11132 @geindex -gnatw.e (gcc)
11135 @table @asis
11137 @item @code{-gnatw.e}
11139 @emph{Activate every optional warning.}
11141 @geindex Warnings
11142 @geindex activate every optional warning
11144 This switch activates all optional warnings, including those which
11145 are not activated by @code{-gnatwa}. The use of this switch is not
11146 recommended for normal use. If you turn this switch on, it is almost
11147 certain that you will get large numbers of useless warnings. The
11148 warnings that are excluded from @code{-gnatwa} are typically highly
11149 specialized warnings that are suitable for use only in code that has
11150 been specifically designed according to specialized coding rules.
11151 @end table
11153 @geindex -gnatwE (gcc)
11155 @geindex Warnings
11156 @geindex treat as error
11159 @table @asis
11161 @item @code{-gnatwE}
11163 @emph{Treat all run-time exception warnings as errors.}
11165 This switch causes warning messages regarding errors that will be raised
11166 during run-time execution to be treated as errors.
11167 @end table
11169 @geindex -gnatwf (gcc)
11172 @table @asis
11174 @item @code{-gnatwf}
11176 @emph{Activate warnings on unreferenced formals.}
11178 @geindex Formals
11179 @geindex unreferenced
11181 This switch causes a warning to be generated if a formal parameter
11182 is not referenced in the body of the subprogram. This warning can
11183 also be turned on using @code{-gnatwu}. The
11184 default is that these warnings are not generated.
11185 @end table
11187 @geindex -gnatwF (gcc)
11190 @table @asis
11192 @item @code{-gnatwF}
11194 @emph{Suppress warnings on unreferenced formals.}
11196 This switch suppresses warnings for unreferenced formal
11197 parameters. Note that the
11198 combination @code{-gnatwu} followed by @code{-gnatwF} has the
11199 effect of warning on unreferenced entities other than subprogram
11200 formals.
11201 @end table
11203 @geindex -gnatwg (gcc)
11206 @table @asis
11208 @item @code{-gnatwg}
11210 @emph{Activate warnings on unrecognized pragmas.}
11212 @geindex Pragmas
11213 @geindex unrecognized
11215 This switch causes a warning to be generated if an unrecognized
11216 pragma is encountered. Apart from issuing this warning, the
11217 pragma is ignored and has no effect. The default
11218 is that such warnings are issued (satisfying the Ada Reference
11219 Manual requirement that such warnings appear).
11220 @end table
11222 @geindex -gnatwG (gcc)
11225 @table @asis
11227 @item @code{-gnatwG}
11229 @emph{Suppress warnings on unrecognized pragmas.}
11231 This switch suppresses warnings for unrecognized pragmas.
11232 @end table
11234 @geindex -gnatw.g (gcc)
11237 @table @asis
11239 @item @code{-gnatw.g}
11241 @emph{Warnings used for GNAT sources.}
11243 This switch sets the warning categories that are used by the standard
11244 GNAT style. Currently this is equivalent to
11245 @code{-gnatwAao.q.s.CI.V.X.Z}
11246 but more warnings may be added in the future without advanced notice.
11247 @end table
11249 @geindex -gnatwh (gcc)
11252 @table @asis
11254 @item @code{-gnatwh}
11256 @emph{Activate warnings on hiding.}
11258 @geindex Hiding of Declarations
11260 This switch activates warnings on hiding declarations that are considered
11261 potentially confusing. Not all cases of hiding cause warnings; for example an
11262 overriding declaration hides an implicit declaration, which is just normal
11263 code. The default is that warnings on hiding are not generated.
11264 @end table
11266 @geindex -gnatwH (gcc)
11269 @table @asis
11271 @item @code{-gnatwH}
11273 @emph{Suppress warnings on hiding.}
11275 This switch suppresses warnings on hiding declarations.
11276 @end table
11278 @geindex -gnatw.h (gcc)
11281 @table @asis
11283 @item @code{-gnatw.h}
11285 @emph{Activate warnings on holes/gaps in records.}
11287 @geindex Record Representation (gaps)
11289 This switch activates warnings on component clauses in record
11290 representation clauses that leave holes (gaps) in the record layout.
11291 If this warning option is active, then record representation clauses
11292 should specify a contiguous layout, adding unused fill fields if needed.
11293 @end table
11295 @geindex -gnatw.H (gcc)
11298 @table @asis
11300 @item @code{-gnatw.H}
11302 @emph{Suppress warnings on holes/gaps in records.}
11304 This switch suppresses warnings on component clauses in record
11305 representation clauses that leave holes (haps) in the record layout.
11306 @end table
11308 @geindex -gnatwi (gcc)
11311 @table @asis
11313 @item @code{-gnatwi}
11315 @emph{Activate warnings on implementation units.}
11317 This switch activates warnings for a @emph{with} of an internal GNAT
11318 implementation unit, defined as any unit from the @code{Ada},
11319 @code{Interfaces}, @code{GNAT},
11320 or @code{System}
11321 hierarchies that is not
11322 documented in either the Ada Reference Manual or the GNAT
11323 Programmer’s Reference Manual. Such units are intended only
11324 for internal implementation purposes and should not be @emph{with}ed
11325 by user programs. The default is that such warnings are generated
11326 @end table
11328 @geindex -gnatwI (gcc)
11331 @table @asis
11333 @item @code{-gnatwI}
11335 @emph{Disable warnings on implementation units.}
11337 This switch disables warnings for a @emph{with} of an internal GNAT
11338 implementation unit.
11339 @end table
11341 @geindex -gnatw.i (gcc)
11344 @table @asis
11346 @item @code{-gnatw.i}
11348 @emph{Activate warnings on overlapping actuals.}
11350 This switch enables a warning on statically detectable overlapping actuals in
11351 a subprogram call, when one of the actuals is an in-out parameter, and the
11352 types of the actuals are not by-copy types. This warning is off by default.
11353 @end table
11355 @geindex -gnatw.I (gcc)
11358 @table @asis
11360 @item @code{-gnatw.I}
11362 @emph{Disable warnings on overlapping actuals.}
11364 This switch disables warnings on overlapping actuals in a call.
11365 @end table
11367 @geindex -gnatwj (gcc)
11370 @table @asis
11372 @item @code{-gnatwj}
11374 @emph{Activate warnings on obsolescent features (Annex J).}
11376 @geindex Features
11377 @geindex obsolescent
11379 @geindex Obsolescent features
11381 If this warning option is activated, then warnings are generated for
11382 calls to subprograms marked with @code{pragma Obsolescent} and
11383 for use of features in Annex J of the Ada Reference Manual. In the
11384 case of Annex J, not all features are flagged. In particular use
11385 of the renamed packages (like @code{Text_IO}) and use of package
11386 @code{ASCII} are not flagged, since these are very common and
11387 would generate many annoying positive warnings. The default is that
11388 such warnings are not generated.
11390 In addition to the above cases, warnings are also generated for
11391 GNAT features that have been provided in past versions but which
11392 have been superseded (typically by features in the new Ada standard).
11393 For example, @code{pragma Ravenscar} will be flagged since its
11394 function is replaced by @code{pragma Profile(Ravenscar)}, and
11395 @code{pragma Interface_Name} will be flagged since its function
11396 is replaced by @code{pragma Import}.
11398 Note that this warning option functions differently from the
11399 restriction @code{No_Obsolescent_Features} in two respects.
11400 First, the restriction applies only to annex J features.
11401 Second, the restriction does flag uses of package @code{ASCII}.
11402 @end table
11404 @geindex -gnatwJ (gcc)
11407 @table @asis
11409 @item @code{-gnatwJ}
11411 @emph{Suppress warnings on obsolescent features (Annex J).}
11413 This switch disables warnings on use of obsolescent features.
11414 @end table
11416 @geindex -gnatw.j (gcc)
11419 @table @asis
11421 @item @code{-gnatw.j}
11423 @emph{Activate warnings on late declarations of tagged type primitives.}
11425 This switch activates warnings on visible primitives added to a
11426 tagged type after deriving a private extension from it.
11427 @end table
11429 @geindex -gnatw.J (gcc)
11432 @table @asis
11434 @item @code{-gnatw.J}
11436 @emph{Suppress warnings on late declarations of tagged type primitives.}
11438 This switch suppresses warnings on visible primitives added to a
11439 tagged type after deriving a private extension from it.
11440 @end table
11442 @geindex -gnatwk (gcc)
11445 @table @asis
11447 @item @code{-gnatwk}
11449 @emph{Activate warnings on variables that could be constants.}
11451 This switch activates warnings for variables that are initialized but
11452 never modified, and then could be declared constants. The default is that
11453 such warnings are not given.
11454 @end table
11456 @geindex -gnatwK (gcc)
11459 @table @asis
11461 @item @code{-gnatwK}
11463 @emph{Suppress warnings on variables that could be constants.}
11465 This switch disables warnings on variables that could be declared constants.
11466 @end table
11468 @geindex -gnatw.k (gcc)
11471 @table @asis
11473 @item @code{-gnatw.k}
11475 @emph{Activate warnings on redefinition of names in standard.}
11477 This switch activates warnings for declarations that declare a name that
11478 is defined in package Standard. Such declarations can be confusing,
11479 especially since the names in package Standard continue to be directly
11480 visible, meaning that use visibiliy on such redeclared names does not
11481 work as expected. Names of discriminants and components in records are
11482 not included in this check.
11483 @end table
11485 @geindex -gnatwK (gcc)
11488 @table @asis
11490 @item @code{-gnatw.K}
11492 @emph{Suppress warnings on redefinition of names in standard.}
11494 This switch disables warnings for declarations that declare a name that
11495 is defined in package Standard.
11496 @end table
11498 @geindex -gnatwl (gcc)
11501 @table @asis
11503 @item @code{-gnatwl}
11505 @emph{Activate warnings for elaboration pragmas.}
11507 @geindex Elaboration
11508 @geindex warnings
11510 This switch activates warnings for possible elaboration problems,
11511 including suspicious use
11512 of @code{Elaborate} pragmas, when using the static elaboration model, and
11513 possible situations that may raise @code{Program_Error} when using the
11514 dynamic elaboration model.
11515 See the section in this guide on elaboration checking for further details.
11516 The default is that such warnings
11517 are not generated.
11518 @end table
11520 @geindex -gnatwL (gcc)
11523 @table @asis
11525 @item @code{-gnatwL}
11527 @emph{Suppress warnings for elaboration pragmas.}
11529 This switch suppresses warnings for possible elaboration problems.
11530 @end table
11532 @geindex -gnatw.l (gcc)
11535 @table @asis
11537 @item @code{-gnatw.l}
11539 @emph{List inherited aspects.}
11541 This switch causes the compiler to list inherited invariants,
11542 preconditions, and postconditions from Type_Invariant’Class, Invariant’Class,
11543 Pre’Class, and Post’Class aspects. Also list inherited subtype predicates.
11544 @end table
11546 @geindex -gnatw.L (gcc)
11549 @table @asis
11551 @item @code{-gnatw.L}
11553 @emph{Suppress listing of inherited aspects.}
11555 This switch suppresses listing of inherited aspects.
11556 @end table
11558 @geindex -gnatwm (gcc)
11561 @table @asis
11563 @item @code{-gnatwm}
11565 @emph{Activate warnings on modified but unreferenced variables.}
11567 This switch activates warnings for variables that are assigned (using
11568 an initialization value or with one or more assignment statements) but
11569 whose value is never read. The warning is suppressed for volatile
11570 variables and also for variables that are renamings of other variables
11571 or for which an address clause is given.
11572 The default is that these warnings are not given.
11573 @end table
11575 @geindex -gnatwM (gcc)
11578 @table @asis
11580 @item @code{-gnatwM}
11582 @emph{Disable warnings on modified but unreferenced variables.}
11584 This switch disables warnings for variables that are assigned or
11585 initialized, but never read.
11586 @end table
11588 @geindex -gnatw.m (gcc)
11591 @table @asis
11593 @item @code{-gnatw.m}
11595 @emph{Activate warnings on suspicious modulus values.}
11597 This switch activates warnings for modulus values that seem suspicious.
11598 The cases caught are where the size is the same as the modulus (e.g.
11599 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11600 with no size clause. The guess in both cases is that 2**x was intended
11601 rather than x. In addition expressions of the form 2*x for small x
11602 generate a warning (the almost certainly accurate guess being that
11603 2**x was intended). This switch also activates warnings for negative
11604 literal values of a modular type, which are interpreted as large positive
11605 integers after wrap-around. The default is that these warnings are given.
11606 @end table
11608 @geindex -gnatw.M (gcc)
11611 @table @asis
11613 @item @code{-gnatw.M}
11615 @emph{Disable warnings on suspicious modulus values.}
11617 This switch disables warnings for suspicious modulus values.
11618 @end table
11620 @geindex -gnatwn (gcc)
11623 @table @asis
11625 @item @code{-gnatwn}
11627 @emph{Set normal warnings mode.}
11629 This switch sets normal warning mode, in which enabled warnings are
11630 issued and treated as warnings rather than errors. This is the default
11631 mode. the switch @code{-gnatwn} can be used to cancel the effect of
11632 an explicit @code{-gnatws} or
11633 @code{-gnatwe}. It also cancels the effect of the
11634 implicit @code{-gnatwe} that is activated by the
11635 use of @code{-gnatg}.
11636 @end table
11638 @geindex -gnatw.n (gcc)
11640 @geindex Atomic Synchronization
11641 @geindex warnings
11644 @table @asis
11646 @item @code{-gnatw.n}
11648 @emph{Activate warnings on atomic synchronization.}
11650 This switch actives warnings when an access to an atomic variable
11651 requires the generation of atomic synchronization code. These
11652 warnings are off by default.
11653 @end table
11655 @geindex -gnatw.N (gcc)
11658 @table @asis
11660 @item @code{-gnatw.N}
11662 @emph{Suppress warnings on atomic synchronization.}
11664 @geindex Atomic Synchronization
11665 @geindex warnings
11667 This switch suppresses warnings when an access to an atomic variable
11668 requires the generation of atomic synchronization code.
11669 @end table
11671 @geindex -gnatwo (gcc)
11673 @geindex Address Clauses
11674 @geindex warnings
11677 @table @asis
11679 @item @code{-gnatwo}
11681 @emph{Activate warnings on address clause overlays.}
11683 This switch activates warnings for possibly unintended initialization
11684 effects of defining address clauses that cause one variable to overlap
11685 another. The default is that such warnings are generated.
11686 @end table
11688 @geindex -gnatwO (gcc)
11691 @table @asis
11693 @item @code{-gnatwO}
11695 @emph{Suppress warnings on address clause overlays.}
11697 This switch suppresses warnings on possibly unintended initialization
11698 effects of defining address clauses that cause one variable to overlap
11699 another.
11700 @end table
11702 @geindex -gnatw.o (gcc)
11705 @table @asis
11707 @item @code{-gnatw.o}
11709 @emph{Activate warnings on modified but unreferenced out parameters.}
11711 This switch activates warnings for variables that are modified by using
11712 them as actuals for a call to a procedure with an out mode formal, where
11713 the resulting assigned value is never read. It is applicable in the case
11714 where there is more than one out mode formal. If there is only one out
11715 mode formal, the warning is issued by default (controlled by -gnatwu).
11716 The warning is suppressed for volatile
11717 variables and also for variables that are renamings of other variables
11718 or for which an address clause is given.
11719 The default is that these warnings are not given.
11720 @end table
11722 @geindex -gnatw.O (gcc)
11725 @table @asis
11727 @item @code{-gnatw.O}
11729 @emph{Disable warnings on modified but unreferenced out parameters.}
11731 This switch suppresses warnings for variables that are modified by using
11732 them as actuals for a call to a procedure with an out mode formal, where
11733 the resulting assigned value is never read.
11734 @end table
11736 @geindex -gnatwp (gcc)
11738 @geindex Inlining
11739 @geindex warnings
11742 @table @asis
11744 @item @code{-gnatwp}
11746 @emph{Activate warnings on ineffective pragma Inlines.}
11748 This switch activates warnings for failure of front end inlining
11749 (activated by @code{-gnatN}) to inline a particular call. There are
11750 many reasons for not being able to inline a call, including most
11751 commonly that the call is too complex to inline. The default is
11752 that such warnings are not given.
11753 Warnings on ineffective inlining by the gcc back-end can be activated
11754 separately, using the gcc switch -Winline.
11755 @end table
11757 @geindex -gnatwP (gcc)
11760 @table @asis
11762 @item @code{-gnatwP}
11764 @emph{Suppress warnings on ineffective pragma Inlines.}
11766 This switch suppresses warnings on ineffective pragma Inlines. If the
11767 inlining mechanism cannot inline a call, it will simply ignore the
11768 request silently.
11769 @end table
11771 @geindex -gnatw.p (gcc)
11773 @geindex Parameter order
11774 @geindex warnings
11777 @table @asis
11779 @item @code{-gnatw.p}
11781 @emph{Activate warnings on parameter ordering.}
11783 This switch activates warnings for cases of suspicious parameter
11784 ordering when the list of arguments are all simple identifiers that
11785 match the names of the formals, but are in a different order. The
11786 warning is suppressed if any use of named parameter notation is used,
11787 so this is the appropriate way to suppress a false positive (and
11788 serves to emphasize that the “misordering” is deliberate). The
11789 default is that such warnings are not given.
11790 @end table
11792 @geindex -gnatw.P (gcc)
11795 @table @asis
11797 @item @code{-gnatw.P}
11799 @emph{Suppress warnings on parameter ordering.}
11801 This switch suppresses warnings on cases of suspicious parameter
11802 ordering.
11803 @end table
11805 @geindex -gnatw_p (gcc)
11808 @table @asis
11810 @item @code{-gnatw_p}
11812 @emph{Activate warnings for pedantic checks.}
11814 This switch activates warnings for the failure of certain pedantic checks.
11815 The only case currently supported is a check that the subtype_marks given
11816 for corresponding formal parameter and function results in a subprogram
11817 declaration and its body denote the same subtype declaration. The default
11818 is that such warnings are not given.
11819 @end table
11821 @geindex -gnatw_P (gcc)
11824 @table @asis
11826 @item @code{-gnatw_P}
11828 @emph{Suppress warnings for pedantic checks.}
11830 This switch suppresses warnings on violations of pedantic checks.
11831 @end table
11833 @geindex -gnatwq (gcc)
11835 @geindex Parentheses
11836 @geindex warnings
11839 @table @asis
11841 @item @code{-gnatwq}
11843 @emph{Activate warnings on questionable missing parentheses.}
11845 This switch activates warnings for cases where parentheses are not used and
11846 the result is potential ambiguity from a readers point of view. For example
11847 (not a > b) when a and b are modular means ((not a) > b) and very likely the
11848 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11849 quite likely ((-x) mod 5) was intended. In such situations it seems best to
11850 follow the rule of always parenthesizing to make the association clear, and
11851 this warning switch warns if such parentheses are not present. The default
11852 is that these warnings are given.
11853 @end table
11855 @geindex -gnatwQ (gcc)
11858 @table @asis
11860 @item @code{-gnatwQ}
11862 @emph{Suppress warnings on questionable missing parentheses.}
11864 This switch suppresses warnings for cases where the association is not
11865 clear and the use of parentheses is preferred.
11866 @end table
11868 @geindex -gnatw.q (gcc)
11870 @geindex Layout
11871 @geindex warnings
11874 @table @asis
11876 @item @code{-gnatw.q}
11878 @emph{Activate warnings on questionable layout of record types.}
11880 This switch activates warnings for cases where the default layout of
11881 a record type, that is to say the layout of its components in textual
11882 order of the source code, would very likely cause inefficiencies in
11883 the code generated by the compiler, both in terms of space and speed
11884 during execution. One warning is issued for each problematic component
11885 without representation clause in the nonvariant part and then in each
11886 variant recursively, if any.
11888 The purpose of these warnings is neither to prescribe an optimal layout
11889 nor to force the use of representation clauses, but rather to get rid of
11890 the most blatant inefficiencies in the layout. Therefore, the default
11891 layout is matched against the following synthetic ordered layout and
11892 the deviations are flagged on a component-by-component basis:
11895 @itemize *
11897 @item 
11898 first all components or groups of components whose length is fixed
11899 and a multiple of the storage unit,
11901 @item 
11902 then the remaining components whose length is fixed and not a multiple
11903 of the storage unit,
11905 @item 
11906 then the remaining components whose length doesn’t depend on discriminants
11907 (that is to say, with variable but uniform length for all objects),
11909 @item 
11910 then all components whose length depends on discriminants,
11912 @item 
11913 finally the variant part (if any),
11914 @end itemize
11916 for the nonvariant part and for each variant recursively, if any.
11918 The exact wording of the warning depends on whether the compiler is allowed
11919 to reorder the components in the record type or precluded from doing it by
11920 means of pragma @code{No_Component_Reordering}.
11922 The default is that these warnings are not given.
11923 @end table
11925 @geindex -gnatw.Q (gcc)
11928 @table @asis
11930 @item @code{-gnatw.Q}
11932 @emph{Suppress warnings on questionable layout of record types.}
11934 This switch suppresses warnings for cases where the default layout of
11935 a record type would very likely cause inefficiencies.
11936 @end table
11938 @geindex -gnatwr (gcc)
11941 @table @asis
11943 @item @code{-gnatwr}
11945 @emph{Activate warnings on redundant constructs.}
11947 This switch activates warnings for redundant constructs. The following
11948 is the current list of constructs regarded as redundant:
11951 @itemize *
11953 @item 
11954 Assignment of an item to itself.
11956 @item 
11957 Type conversion that converts an expression to its own type.
11959 @item 
11960 Use of the attribute @code{Base} where @code{typ'Base} is the same
11961 as @code{typ}.
11963 @item 
11964 Use of pragma @code{Pack} when all components are placed by a record
11965 representation clause.
11967 @item 
11968 Exception handler containing only a reraise statement (raise with no
11969 operand) which has no effect.
11971 @item 
11972 Use of the operator abs on an operand that is known at compile time
11973 to be non-negative
11975 @item 
11976 Comparison of an object or (unary or binary) operation of boolean type to
11977 an explicit True value.
11979 @item 
11980 Import of parent package.
11981 @end itemize
11983 The default is that warnings for redundant constructs are not given.
11984 @end table
11986 @geindex -gnatwR (gcc)
11989 @table @asis
11991 @item @code{-gnatwR}
11993 @emph{Suppress warnings on redundant constructs.}
11995 This switch suppresses warnings for redundant constructs.
11996 @end table
11998 @geindex -gnatw.r (gcc)
12001 @table @asis
12003 @item @code{-gnatw.r}
12005 @emph{Activate warnings for object renaming function.}
12007 This switch activates warnings for an object renaming that renames a
12008 function call, which is equivalent to a constant declaration (as
12009 opposed to renaming the function itself).  The default is that these
12010 warnings are given.
12011 @end table
12013 @geindex -gnatw.R (gcc)
12016 @table @asis
12018 @item @code{-gnatw.R}
12020 @emph{Suppress warnings for object renaming function.}
12022 This switch suppresses warnings for object renaming function.
12023 @end table
12025 @geindex -gnatw_r (gcc)
12028 @table @asis
12030 @item @code{-gnatw_r}
12032 @emph{Activate warnings for out-of-order record representation clauses.}
12034 This switch activates warnings for record representation clauses,
12035 if the order of component declarations, component clauses,
12036 and bit-level layout do not all agree.
12037 The default is that these warnings are not given.
12038 @end table
12040 @geindex -gnatw_R (gcc)
12043 @table @asis
12045 @item @code{-gnatw_R}
12047 @emph{Suppress warnings for out-of-order record representation clauses.}
12048 @end table
12050 @geindex -gnatws (gcc)
12053 @table @asis
12055 @item @code{-gnatws}
12057 @emph{Suppress all warnings.}
12059 This switch completely suppresses the
12060 output of all warning messages from the GNAT front end, including
12061 both warnings that can be controlled by switches described in this
12062 section, and those that are normally given unconditionally. The
12063 effect of this suppress action can only be cancelled by a subsequent
12064 use of the switch @code{-gnatwn}.
12066 Note that switch @code{-gnatws} does not suppress
12067 warnings from the @code{gcc} back end.
12068 To suppress these back end warnings as well, use the switch @code{-w}
12069 in addition to @code{-gnatws}. Also this switch has no effect on the
12070 handling of style check messages.
12071 @end table
12073 @geindex -gnatw.s (gcc)
12075 @geindex Record Representation (component sizes)
12078 @table @asis
12080 @item @code{-gnatw.s}
12082 @emph{Activate warnings on overridden size clauses.}
12084 This switch activates warnings on component clauses in record
12085 representation clauses where the length given overrides that
12086 specified by an explicit size clause for the component type. A
12087 warning is similarly given in the array case if a specified
12088 component size overrides an explicit size clause for the array
12089 component type.
12090 @end table
12092 @geindex -gnatw.S (gcc)
12095 @table @asis
12097 @item @code{-gnatw.S}
12099 @emph{Suppress warnings on overridden size clauses.}
12101 This switch suppresses warnings on component clauses in record
12102 representation clauses that override size clauses, and similar
12103 warnings when an array component size overrides a size clause.
12104 @end table
12106 @geindex -gnatwt (gcc)
12108 @geindex Deactivated code
12109 @geindex warnings
12111 @geindex Deleted code
12112 @geindex warnings
12115 @table @asis
12117 @item @code{-gnatwt}
12119 @emph{Activate warnings for tracking of deleted conditional code.}
12121 This switch activates warnings for tracking of code in conditionals (IF and
12122 CASE statements) that is detected to be dead code which cannot be executed, and
12123 which is removed by the front end. This warning is off by default. This may be
12124 useful for detecting deactivated code in certified applications.
12125 @end table
12127 @geindex -gnatwT (gcc)
12130 @table @asis
12132 @item @code{-gnatwT}
12134 @emph{Suppress warnings for tracking of deleted conditional code.}
12136 This switch suppresses warnings for tracking of deleted conditional code.
12137 @end table
12139 @geindex -gnatw.t (gcc)
12142 @table @asis
12144 @item @code{-gnatw.t}
12146 @emph{Activate warnings on suspicious contracts.}
12148 This switch activates warnings on suspicious contracts. This includes
12149 warnings on suspicious postconditions (whether a pragma @code{Postcondition} or a
12150 @code{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
12151 @code{Contract_Cases}). A function postcondition or contract case is suspicious
12152 when no postcondition or contract case for this function mentions the result
12153 of the function.  A procedure postcondition or contract case is suspicious
12154 when it only refers to the pre-state of the procedure, because in that case
12155 it should rather be expressed as a precondition. This switch also controls
12156 warnings on suspicious cases of expressions typically found in contracts like
12157 quantified expressions and uses of Update attribute. The default is that such
12158 warnings are generated.
12159 @end table
12161 @geindex -gnatw.T (gcc)
12164 @table @asis
12166 @item @code{-gnatw.T}
12168 @emph{Suppress warnings on suspicious contracts.}
12170 This switch suppresses warnings on suspicious contracts.
12171 @end table
12173 @geindex -gnatwu (gcc)
12176 @table @asis
12178 @item @code{-gnatwu}
12180 @emph{Activate warnings on unused entities.}
12182 This switch activates warnings to be generated for entities that
12183 are declared but not referenced, and for units that are @emph{with}ed
12184 and not
12185 referenced. In the case of packages, a warning is also generated if
12186 no entities in the package are referenced. This means that if a with’ed
12187 package is referenced but the only references are in @code{use}
12188 clauses or @code{renames}
12189 declarations, a warning is still generated. A warning is also generated
12190 for a generic package that is @emph{with}ed but never instantiated.
12191 In the case where a package or subprogram body is compiled, and there
12192 is a @emph{with} on the corresponding spec
12193 that is only referenced in the body,
12194 a warning is also generated, noting that the
12195 @emph{with} can be moved to the body. The default is that
12196 such warnings are not generated.
12197 This switch also activates warnings on unreferenced formals
12198 (it includes the effect of @code{-gnatwf}).
12199 @end table
12201 @geindex -gnatwU (gcc)
12204 @table @asis
12206 @item @code{-gnatwU}
12208 @emph{Suppress warnings on unused entities.}
12210 This switch suppresses warnings for unused entities and packages.
12211 It also turns off warnings on unreferenced formals (and thus includes
12212 the effect of @code{-gnatwF}).
12213 @end table
12215 @geindex -gnatw.u (gcc)
12218 @table @asis
12220 @item @code{-gnatw.u}
12222 @emph{Activate warnings on unordered enumeration types.}
12224 This switch causes enumeration types to be considered as conceptually
12225 unordered, unless an explicit pragma @code{Ordered} is given for the type.
12226 The effect is to generate warnings in clients that use explicit comparisons
12227 or subranges, since these constructs both treat objects of the type as
12228 ordered. (A @emph{client} is defined as a unit that is other than the unit in
12229 which the type is declared, or its body or subunits.) Please refer to
12230 the description of pragma @code{Ordered} in the
12231 @cite{GNAT Reference Manual} for further details.
12232 The default is that such warnings are not generated.
12233 @end table
12235 @geindex -gnatw.U (gcc)
12238 @table @asis
12240 @item @code{-gnatw.U}
12242 @emph{Deactivate warnings on unordered enumeration types.}
12244 This switch causes all enumeration types to be considered as ordered, so
12245 that no warnings are given for comparisons or subranges for any type.
12246 @end table
12248 @geindex -gnatwv (gcc)
12250 @geindex Unassigned variable warnings
12253 @table @asis
12255 @item @code{-gnatwv}
12257 @emph{Activate warnings on unassigned variables.}
12259 This switch activates warnings for access to variables which
12260 may not be properly initialized. The default is that
12261 such warnings are generated. This switch will also be emitted when
12262 initializing an array or record object via the following aggregate:
12264 @example
12265 Array_Or_Record : XXX := (others => <>);
12266 @end example
12268 unless the relevant type fully initializes all components.
12269 @end table
12271 @geindex -gnatwV (gcc)
12274 @table @asis
12276 @item @code{-gnatwV}
12278 @emph{Suppress warnings on unassigned variables.}
12280 This switch suppresses warnings for access to variables which
12281 may not be properly initialized.
12282 @end table
12284 @geindex -gnatw.v (gcc)
12286 @geindex bit order warnings
12289 @table @asis
12291 @item @code{-gnatw.v}
12293 @emph{Activate info messages for non-default bit order.}
12295 This switch activates messages (labeled “info”, they are not warnings,
12296 just informational messages) about the effects of non-default bit-order
12297 on records to which a component clause is applied. The effect of specifying
12298 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12299 these messages, which are given by default, are useful in understanding the
12300 exact consequences of using this feature.
12301 @end table
12303 @geindex -gnatw.V (gcc)
12306 @table @asis
12308 @item @code{-gnatw.V}
12310 @emph{Suppress info messages for non-default bit order.}
12312 This switch suppresses information messages for the effects of specifying
12313 non-default bit order on record components with component clauses.
12314 @end table
12316 @geindex -gnatww (gcc)
12318 @geindex String indexing warnings
12321 @table @asis
12323 @item @code{-gnatww}
12325 @emph{Activate warnings on wrong low bound assumption.}
12327 This switch activates warnings for indexing an unconstrained string parameter
12328 with a literal or S’Length. This is a case where the code is assuming that the
12329 low bound is one, which is in general not true (for example when a slice is
12330 passed). The default is that such warnings are generated.
12331 @end table
12333 @geindex -gnatwW (gcc)
12336 @table @asis
12338 @item @code{-gnatwW}
12340 @emph{Suppress warnings on wrong low bound assumption.}
12342 This switch suppresses warnings for indexing an unconstrained string parameter
12343 with a literal or S’Length. Note that this warning can also be suppressed
12344 in a particular case by adding an assertion that the lower bound is 1,
12345 as shown in the following example:
12347 @example
12348 procedure K (S : String) is
12349    pragma Assert (S'First = 1);
12350    ...
12351 @end example
12352 @end table
12354 @geindex -gnatw.w (gcc)
12356 @geindex Warnings Off control
12359 @table @asis
12361 @item @code{-gnatw.w}
12363 @emph{Activate warnings on Warnings Off pragmas.}
12365 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
12366 where either the pragma is entirely useless (because it suppresses no
12367 warnings), or it could be replaced by @code{pragma Unreferenced} or
12368 @code{pragma Unmodified}.
12369 Also activates warnings for the case of
12370 Warnings (Off, String), where either there is no matching
12371 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12372 The default is that these warnings are not given.
12373 @end table
12375 @geindex -gnatw.W (gcc)
12378 @table @asis
12380 @item @code{-gnatw.W}
12382 @emph{Suppress warnings on unnecessary Warnings Off pragmas.}
12384 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
12385 @end table
12387 @geindex -gnatwx (gcc)
12389 @geindex Export/Import pragma warnings
12392 @table @asis
12394 @item @code{-gnatwx}
12396 @emph{Activate warnings on Export/Import pragmas.}
12398 This switch activates warnings on Export/Import pragmas when
12399 the compiler detects a possible conflict between the Ada and
12400 foreign language calling sequences. For example, the use of
12401 default parameters in a convention C procedure is dubious
12402 because the C compiler cannot supply the proper default, so
12403 a warning is issued. The default is that such warnings are
12404 generated.
12405 @end table
12407 @geindex -gnatwX (gcc)
12410 @table @asis
12412 @item @code{-gnatwX}
12414 @emph{Suppress warnings on Export/Import pragmas.}
12416 This switch suppresses warnings on Export/Import pragmas.
12417 The sense of this is that you are telling the compiler that
12418 you know what you are doing in writing the pragma, and it
12419 should not complain at you.
12420 @end table
12422 @geindex -gnatwm (gcc)
12425 @table @asis
12427 @item @code{-gnatw.x}
12429 @emph{Activate warnings for No_Exception_Propagation mode.}
12431 This switch activates warnings for exception usage when pragma Restrictions
12432 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
12433 explicit exception raises which are not covered by a local handler, and for
12434 exception handlers which do not cover a local raise. The default is that
12435 these warnings are given for units that contain exception handlers.
12437 @item @code{-gnatw.X}
12439 @emph{Disable warnings for No_Exception_Propagation mode.}
12441 This switch disables warnings for exception usage when pragma Restrictions
12442 (No_Exception_Propagation) is in effect.
12443 @end table
12445 @geindex -gnatwy (gcc)
12447 @geindex Ada compatibility issues warnings
12450 @table @asis
12452 @item @code{-gnatwy}
12454 @emph{Activate warnings for Ada compatibility issues.}
12456 For the most part, newer versions of Ada are upwards compatible
12457 with older versions. For example, Ada 2005 programs will almost
12458 always work when compiled as Ada 2012.
12459 However there are some exceptions (for example the fact that
12460 @code{some} is now a reserved word in Ada 2012). This
12461 switch activates several warnings to help in identifying
12462 and correcting such incompatibilities. The default is that
12463 these warnings are generated. Note that at one point Ada 2005
12464 was called Ada 0Y, hence the choice of character.
12465 @end table
12467 @geindex -gnatwY (gcc)
12469 @geindex Ada compatibility issues warnings
12472 @table @asis
12474 @item @code{-gnatwY}
12476 @emph{Disable warnings for Ada compatibility issues.}
12478 This switch suppresses the warnings intended to help in identifying
12479 incompatibilities between Ada language versions.
12480 @end table
12482 @geindex -gnatw.y (gcc)
12484 @geindex Package spec needing body
12487 @table @asis
12489 @item @code{-gnatw.y}
12491 @emph{Activate information messages for why package spec needs body.}
12493 There are a number of cases in which a package spec needs a body.
12494 For example, the use of pragma Elaborate_Body, or the declaration
12495 of a procedure specification requiring a completion. This switch
12496 causes information messages to be output showing why a package
12497 specification requires a body. This can be useful in the case of
12498 a large package specification which is unexpectedly requiring a
12499 body. The default is that such information messages are not output.
12500 @end table
12502 @geindex -gnatw.Y (gcc)
12504 @geindex No information messages for why package spec needs body
12507 @table @asis
12509 @item @code{-gnatw.Y}
12511 @emph{Disable information messages for why package spec needs body.}
12513 This switch suppresses the output of information messages showing why
12514 a package specification needs a body.
12515 @end table
12517 @geindex -gnatwz (gcc)
12519 @geindex Unchecked_Conversion warnings
12522 @table @asis
12524 @item @code{-gnatwz}
12526 @emph{Activate warnings on unchecked conversions.}
12528 This switch activates warnings for unchecked conversions
12529 where the types are known at compile time to have different
12530 sizes. The default is that such warnings are generated. Warnings are also
12531 generated for subprogram pointers with different conventions.
12532 @end table
12534 @geindex -gnatwZ (gcc)
12537 @table @asis
12539 @item @code{-gnatwZ}
12541 @emph{Suppress warnings on unchecked conversions.}
12543 This switch suppresses warnings for unchecked conversions
12544 where the types are known at compile time to have different
12545 sizes or conventions.
12546 @end table
12548 @geindex -gnatw.z (gcc)
12550 @geindex Size/Alignment warnings
12553 @table @asis
12555 @item @code{-gnatw.z}
12557 @emph{Activate warnings for size not a multiple of alignment.}
12559 This switch activates warnings for cases of array and record types
12560 with specified @code{Size} and @code{Alignment} attributes where the
12561 size is not a multiple of the alignment, resulting in an object
12562 size that is greater than the specified size. The default
12563 is that such warnings are generated.
12564 @end table
12566 @geindex -gnatw.Z (gcc)
12568 @geindex Size/Alignment warnings
12571 @table @asis
12573 @item @code{-gnatw.Z}
12575 @emph{Suppress warnings for size not a multiple of alignment.}
12577 This switch suppresses warnings for cases of array and record types
12578 with specified @code{Size} and @code{Alignment} attributes where the
12579 size is not a multiple of the alignment, resulting in an object
12580 size that is greater than the specified size. The warning can also
12581 be suppressed by giving an explicit @code{Object_Size} value.
12582 @end table
12584 @geindex -Wunused (gcc)
12587 @table @asis
12589 @item @code{-Wunused}
12591 The warnings controlled by the @code{-gnatw} switch are generated by
12592 the front end of the compiler. The GCC back end can provide
12593 additional warnings and they are controlled by the @code{-W} switch.
12594 For example, @code{-Wunused} activates back end
12595 warnings for entities that are declared but not referenced.
12596 @end table
12598 @geindex -Wuninitialized (gcc)
12601 @table @asis
12603 @item @code{-Wuninitialized}
12605 Similarly, @code{-Wuninitialized} activates
12606 the back end warning for uninitialized variables. This switch must be
12607 used in conjunction with an optimization level greater than zero.
12608 @end table
12610 @geindex -Wstack-usage (gcc)
12613 @table @asis
12615 @item @code{-Wstack-usage=@emph{len}}
12617 Warn if the stack usage of a subprogram might be larger than @code{len} bytes.
12618 See @ref{e6,,Static Stack Usage Analysis} for details.
12619 @end table
12621 @geindex -Wall (gcc)
12624 @table @asis
12626 @item @code{-Wall}
12628 This switch enables most warnings from the GCC back end.
12629 The code generator detects a number of warning situations that are missed
12630 by the GNAT front end, and this switch can be used to activate them.
12631 The use of this switch also sets the default front-end warning mode to
12632 @code{-gnatwa}, that is, most front-end warnings are activated as well.
12633 @end table
12635 @geindex -w (gcc)
12638 @table @asis
12640 @item @code{-w}
12642 Conversely, this switch suppresses warnings from the GCC back end.
12643 The use of this switch also sets the default front-end warning mode to
12644 @code{-gnatws}, that is, front-end warnings are suppressed as well.
12645 @end table
12647 @geindex -Werror (gcc)
12650 @table @asis
12652 @item @code{-Werror}
12654 This switch causes warnings from the GCC back end to be treated as
12655 errors.  The warning string still appears, but the warning messages are
12656 counted as errors, and prevent the generation of an object file.
12657 The use of this switch also sets the default front-end warning mode to
12658 @code{-gnatwe}, that is, front-end warning messages and style check
12659 messages are treated as errors as well.
12660 @end table
12662 A string of warning parameters can be used in the same parameter. For example:
12664 @example
12665 -gnatwaGe
12666 @end example
12668 will turn on all optional warnings except for unrecognized pragma warnings,
12669 and also specify that warnings should be treated as errors.
12671 When no switch @code{-gnatw} is used, this is equivalent to:
12673 @quotation
12676 @itemize *
12678 @item 
12679 @code{-gnatw.a}
12681 @item 
12682 @code{-gnatwB}
12684 @item 
12685 @code{-gnatw.b}
12687 @item 
12688 @code{-gnatwC}
12690 @item 
12691 @code{-gnatw.C}
12693 @item 
12694 @code{-gnatwD}
12696 @item 
12697 @code{-gnatw.D}
12699 @item 
12700 @code{-gnatwF}
12702 @item 
12703 @code{-gnatw.F}
12705 @item 
12706 @code{-gnatwg}
12708 @item 
12709 @code{-gnatwH}
12711 @item 
12712 @code{-gnatw.H}
12714 @item 
12715 @code{-gnatwi}
12717 @item 
12718 @code{-gnatwJ}
12720 @item 
12721 @code{-gnatw.J}
12723 @item 
12724 @code{-gnatwK}
12726 @item 
12727 @code{-gnatw.K}
12729 @item 
12730 @code{-gnatwL}
12732 @item 
12733 @code{-gnatw.L}
12735 @item 
12736 @code{-gnatwM}
12738 @item 
12739 @code{-gnatw.m}
12741 @item 
12742 @code{-gnatwn}
12744 @item 
12745 @code{-gnatw.N}
12747 @item 
12748 @code{-gnatwo}
12750 @item 
12751 @code{-gnatw.O}
12753 @item 
12754 @code{-gnatwP}
12756 @item 
12757 @code{-gnatw.P}
12759 @item 
12760 @code{-gnatwq}
12762 @item 
12763 @code{-gnatw.Q}
12765 @item 
12766 @code{-gnatwR}
12768 @item 
12769 @code{-gnatw.R}
12771 @item 
12772 @code{-gnatw.S}
12774 @item 
12775 @code{-gnatwT}
12777 @item 
12778 @code{-gnatw.t}
12780 @item 
12781 @code{-gnatwU}
12783 @item 
12784 @code{-gnatw.U}
12786 @item 
12787 @code{-gnatwv}
12789 @item 
12790 @code{-gnatw.v}
12792 @item 
12793 @code{-gnatww}
12795 @item 
12796 @code{-gnatw.W}
12798 @item 
12799 @code{-gnatwx}
12801 @item 
12802 @code{-gnatw.X}
12804 @item 
12805 @code{-gnatwy}
12807 @item 
12808 @code{-gnatw.Y}
12810 @item 
12811 @code{-gnatwz}
12813 @item 
12814 @code{-gnatw.z}
12815 @end itemize
12816 @end quotation
12818 @node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12819 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-and-assertion-control}@anchor{f1}@anchor{gnat_ugn/building_executable_programs_with_gnat id16}@anchor{f2}
12820 @subsection Debugging and Assertion Control
12823 @geindex -gnata (gcc)
12826 @table @asis
12828 @item @code{-gnata}
12830 @geindex Assert
12832 @geindex Debug
12834 @geindex Assertions
12836 @geindex Precondition
12838 @geindex Postcondition
12840 @geindex Type invariants
12842 @geindex Subtype predicates
12844 The @code{-gnata} option is equivalent to the following @code{Assertion_Policy} pragma:
12846 @example
12847 pragma Assertion_Policy (Check);
12848 @end example
12850 Which is a shorthand for:
12852 @example
12853 pragma Assertion_Policy
12854   (Assert               => Check,
12855    Static_Predicate     => Check,
12856    Dynamic_Predicate    => Check,
12857    Pre                  => Check,
12858    Pre'Class            => Check,
12859    Post                 => Check,
12860    Post'Class           => Check,
12861    Type_Invariant       => Check,
12862    Type_Invariant'Class => Check);
12863 @end example
12865 The pragmas @code{Assert} and @code{Debug} normally have no effect and
12866 are ignored. This switch, where @code{a} stands for ‘assert’, causes
12867 pragmas @code{Assert} and @code{Debug} to be activated. This switch also
12868 causes preconditions, postconditions, subtype predicates, and
12869 type invariants to be activated.
12871 The pragmas have the form:
12873 @example
12874 pragma Assert (<Boolean-expression> [, <static-string-expression>])
12875 pragma Debug (<procedure call>)
12876 pragma Type_Invariant (<type-local-name>, <Boolean-expression>)
12877 pragma Predicate (<type-local-name>, <Boolean-expression>)
12878 pragma Precondition (<Boolean-expression>, <string-expression>)
12879 pragma Postcondition (<Boolean-expression>, <string-expression>)
12880 @end example
12882 The aspects have the form:
12884 @example
12885 with [Pre|Post|Type_Invariant|Dynamic_Predicate|Static_Predicate]
12886   => <Boolean-expression>;
12887 @end example
12889 The @code{Assert} pragma causes @code{Boolean-expression} to be tested.
12890 If the result is @code{True}, the pragma has no effect (other than
12891 possible side effects from evaluating the expression). If the result is
12892 @code{False}, the exception @code{Assert_Failure} declared in the package
12893 @code{System.Assertions} is raised (passing @code{static-string-expression}, if
12894 present, as the message associated with the exception). If no string
12895 expression is given, the default is a string containing the file name and
12896 line number of the pragma.
12898 The @code{Debug} pragma causes @code{procedure} to be called. Note that
12899 @code{pragma Debug} may appear within a declaration sequence, allowing
12900 debugging procedures to be called between declarations.
12902 For the aspect specification, the @code{Boolean-expression} is evaluated.
12903 If the result is @code{True}, the aspect has no effect. If the result
12904 is @code{False}, the exception @code{Assert_Failure} is raised.
12905 @end table
12907 @node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
12908 @anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{f3}@anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{e7}
12909 @subsection Validity Checking
12912 @geindex Validity Checking
12914 The Ada Reference Manual defines the concept of invalid values (see
12915 RM 13.9.1). The primary source of invalid values is uninitialized
12916 variables. A scalar variable that is left uninitialized may contain
12917 an invalid value; the concept of invalid does not apply to access or
12918 composite types.
12920 It is an error to read an invalid value, but the RM does not require
12921 run-time checks to detect such errors, except for some minimal
12922 checking to prevent erroneous execution (i.e. unpredictable
12923 behavior). This corresponds to the @code{-gnatVd} switch below,
12924 which is the default. For example, by default, if the expression of a
12925 case statement is invalid, it will raise Constraint_Error rather than
12926 causing a wild jump, and if an array index on the left-hand side of an
12927 assignment is invalid, it will raise Constraint_Error rather than
12928 overwriting an arbitrary memory location.
12930 The @code{-gnatVa} may be used to enable additional validity checks,
12931 which are not required by the RM. These checks are often very
12932 expensive (which is why the RM does not require them). These checks
12933 are useful in tracking down uninitialized variables, but they are
12934 not usually recommended for production builds, and in particular
12935 we do not recommend using these extra validity checking options in
12936 combination with optimization, since this can confuse the optimizer.
12937 If performance is a consideration, leading to the need to optimize,
12938 then the validity checking options should not be used.
12940 The other @code{-gnatV@emph{x}} switches below allow finer-grained
12941 control; you can enable whichever validity checks you desire. However,
12942 for most debugging purposes, @code{-gnatVa} is sufficient, and the
12943 default @code{-gnatVd} (i.e. standard Ada behavior) is usually
12944 sufficient for non-debugging use.
12946 The @code{-gnatB} switch tells the compiler to assume that all
12947 values are valid (that is, within their declared subtype range)
12948 except in the context of a use of the Valid attribute. This means
12949 the compiler can generate more efficient code, since the range
12950 of values is better known at compile time. However, an uninitialized
12951 variable can cause wild jumps and memory corruption in this mode.
12953 The @code{-gnatV@emph{x}} switch allows control over the validity
12954 checking mode as described below.
12955 The @code{x} argument is a string of letters that
12956 indicate validity checks that are performed or not performed in addition
12957 to the default checks required by Ada as described above.
12959 @geindex -gnatVa (gcc)
12962 @table @asis
12964 @item @code{-gnatVa}
12966 @emph{All validity checks.}
12968 All validity checks are turned on.
12969 That is, @code{-gnatVa} is
12970 equivalent to @code{gnatVcdfimoprst}.
12971 @end table
12973 @geindex -gnatVc (gcc)
12976 @table @asis
12978 @item @code{-gnatVc}
12980 @emph{Validity checks for copies.}
12982 The right hand side of assignments, and the initializing values of
12983 object declarations are validity checked.
12984 @end table
12986 @geindex -gnatVd (gcc)
12989 @table @asis
12991 @item @code{-gnatVd}
12993 @emph{Default (RM) validity checks.}
12995 Some validity checks are done by default following normal Ada semantics
12996 (RM 13.9.1 (9-11)).
12997 A check is done in case statements that the expression is within the range
12998 of the subtype. If it is not, Constraint_Error is raised.
12999 For assignments to array components, a check is done that the expression used
13000 as index is within the range. If it is not, Constraint_Error is raised.
13001 Both these validity checks may be turned off using switch @code{-gnatVD}.
13002 They are turned on by default. If @code{-gnatVD} is specified, a subsequent
13003 switch @code{-gnatVd} will leave the checks turned on.
13004 Switch @code{-gnatVD} should be used only if you are sure that all such
13005 expressions have valid values. If you use this switch and invalid values
13006 are present, then the program is erroneous, and wild jumps or memory
13007 overwriting may occur.
13008 @end table
13010 @geindex -gnatVe (gcc)
13013 @table @asis
13015 @item @code{-gnatVe}
13017 @emph{Validity checks for elementary components.}
13019 In the absence of this switch, assignments to record or array components are
13020 not validity checked, even if validity checks for assignments generally
13021 (@code{-gnatVc}) are turned on. In Ada, assignment of composite values do not
13022 require valid data, but assignment of individual components does. So for
13023 example, there is a difference between copying the elements of an array with a
13024 slice assignment, compared to assigning element by element in a loop. This
13025 switch allows you to turn off validity checking for components, even when they
13026 are assigned component by component.
13027 @end table
13029 @geindex -gnatVf (gcc)
13032 @table @asis
13034 @item @code{-gnatVf}
13036 @emph{Validity checks for floating-point values.}
13038 In the absence of this switch, validity checking occurs only for discrete
13039 values. If @code{-gnatVf} is specified, then validity checking also applies
13040 for floating-point values, and NaNs and infinities are considered invalid,
13041 as well as out of range values for constrained types. Note that this means
13042 that standard IEEE infinity mode is not allowed. The exact contexts
13043 in which floating-point values are checked depends on the setting of other
13044 options. For example, @code{-gnatVif} or @code{-gnatVfi}
13045 (the order does not matter) specifies that floating-point parameters of mode
13046 @code{in} should be validity checked.
13047 @end table
13049 @geindex -gnatVi (gcc)
13052 @table @asis
13054 @item @code{-gnatVi}
13056 @emph{Validity checks for `@w{`}in`@w{`} mode parameters.}
13058 Arguments for parameters of mode @code{in} are validity checked in function
13059 and procedure calls at the point of call.
13060 @end table
13062 @geindex -gnatVm (gcc)
13065 @table @asis
13067 @item @code{-gnatVm}
13069 @emph{Validity checks for `@w{`}in out`@w{`} mode parameters.}
13071 Arguments for parameters of mode @code{in out} are validity checked in
13072 procedure calls at the point of call. The @code{'m'} here stands for
13073 modify, since this concerns parameters that can be modified by the call.
13074 Note that there is no specific option to test @code{out} parameters,
13075 but any reference within the subprogram will be tested in the usual
13076 manner, and if an invalid value is copied back, any reference to it
13077 will be subject to validity checking.
13078 @end table
13080 @geindex -gnatVn (gcc)
13083 @table @asis
13085 @item @code{-gnatVn}
13087 @emph{No validity checks.}
13089 This switch turns off all validity checking, including the default checking
13090 for case statements and left hand side subscripts. Note that the use of
13091 the switch @code{-gnatp} suppresses all run-time checks, including
13092 validity checks, and thus implies @code{-gnatVn}. When this switch
13093 is used, it cancels any other @code{-gnatV} previously issued.
13094 @end table
13096 @geindex -gnatVo (gcc)
13099 @table @asis
13101 @item @code{-gnatVo}
13103 @emph{Validity checks for operator and attribute operands.}
13105 Arguments for predefined operators and attributes are validity checked.
13106 This includes all operators in package @code{Standard},
13107 the shift operators defined as intrinsic in package @code{Interfaces}
13108 and operands for attributes such as @code{Pos}. Checks are also made
13109 on individual component values for composite comparisons, and on the
13110 expressions in type conversions and qualified expressions. Checks are
13111 also made on explicit ranges using @code{..} (e.g., slices, loops etc).
13112 @end table
13114 @geindex -gnatVp (gcc)
13117 @table @asis
13119 @item @code{-gnatVp}
13121 @emph{Validity checks for parameters.}
13123 This controls the treatment of parameters within a subprogram (as opposed
13124 to @code{-gnatVi} and @code{-gnatVm} which control validity testing
13125 of parameters on a call. If either of these call options is used, then
13126 normally an assumption is made within a subprogram that the input arguments
13127 have been validity checking at the point of call, and do not need checking
13128 again within a subprogram). If @code{-gnatVp} is set, then this assumption
13129 is not made, and parameters are not assumed to be valid, so their validity
13130 will be checked (or rechecked) within the subprogram.
13131 @end table
13133 @geindex -gnatVr (gcc)
13136 @table @asis
13138 @item @code{-gnatVr}
13140 @emph{Validity checks for function returns.}
13142 The expression in @code{return} statements in functions is validity
13143 checked.
13144 @end table
13146 @geindex -gnatVs (gcc)
13149 @table @asis
13151 @item @code{-gnatVs}
13153 @emph{Validity checks for subscripts.}
13155 All subscripts expressions are checked for validity, whether they appear
13156 on the right side or left side (in default mode only left side subscripts
13157 are validity checked).
13158 @end table
13160 @geindex -gnatVt (gcc)
13163 @table @asis
13165 @item @code{-gnatVt}
13167 @emph{Validity checks for tests.}
13169 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
13170 statements are checked, as well as guard expressions in entry calls.
13171 @end table
13173 The @code{-gnatV} switch may be followed by a string of letters
13174 to turn on a series of validity checking options.
13175 For example, @code{-gnatVcr}
13176 specifies that in addition to the default validity checking, copies and
13177 function return expressions are to be validity checked.
13178 In order to make it easier to specify the desired combination of effects,
13179 the upper case letters @code{CDFIMORST} may
13180 be used to turn off the corresponding lower case option.
13181 Thus @code{-gnatVaM} turns on all validity checking options except for
13182 checking of @code{in out} parameters.
13184 The specification of additional validity checking generates extra code (and
13185 in the case of @code{-gnatVa} the code expansion can be substantial).
13186 However, these additional checks can be very useful in detecting
13187 uninitialized variables, incorrect use of unchecked conversion, and other
13188 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
13189 is useful in conjunction with the extra validity checking, since this
13190 ensures that wherever possible uninitialized variables have invalid values.
13192 See also the pragma @code{Validity_Checks} which allows modification of
13193 the validity checking mode at the program source level, and also allows for
13194 temporary disabling of validity checks.
13196 @node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
13197 @anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{f4}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{ec}
13198 @subsection Style Checking
13201 @geindex Style checking
13203 @geindex -gnaty (gcc)
13205 The @code{-gnatyx} switch causes the compiler to
13206 enforce specified style rules. A limited set of style rules has been used
13207 in writing the GNAT sources themselves. This switch allows user programs
13208 to activate all or some of these checks. If the source program fails a
13209 specified style check, an appropriate message is given, preceded by
13210 the character sequence ‘(style)’. This message does not prevent
13211 successful compilation (unless the @code{-gnatwe} switch is used).
13213 Note that this is by no means intended to be a general facility for
13214 checking arbitrary coding standards. It is simply an embedding of the
13215 style rules we have chosen for the GNAT sources. If you are starting
13216 a project which does not have established style standards, you may
13217 find it useful to adopt the entire set of GNAT coding standards, or
13218 some subset of them.
13221 The string @code{x} is a sequence of letters or digits
13222 indicating the particular style
13223 checks to be performed. The following checks are defined:
13225 @geindex -gnaty[0-9] (gcc)
13228 @table @asis
13230 @item @code{-gnaty0}
13232 @emph{Specify indentation level.}
13234 If a digit from 1-9 appears
13235 in the string after @code{-gnaty}
13236 then proper indentation is checked, with the digit indicating the
13237 indentation level required. A value of zero turns off this style check.
13238 The rule checks that the following constructs start on a column that is
13239 a multiple of the alignment level:
13242 @itemize *
13244 @item 
13245 beginnings of declarations (except record component declarations)
13246 and statements;
13248 @item 
13249 beginnings of the structural components of compound statements;
13251 @item 
13252 @code{end} keyword that completes the declaration of a program unit declaration
13253 or body or that completes a compound statement.
13254 @end itemize
13256 Full line comments must be
13257 aligned with the @code{--} starting on a column that is a multiple of
13258 the alignment level, or they may be aligned the same way as the following
13259 non-blank line (this is useful when full line comments appear in the middle
13260 of a statement, or they may be aligned with the source line on the previous
13261 non-blank line.
13262 @end table
13264 @geindex -gnatya (gcc)
13267 @table @asis
13269 @item @code{-gnatya}
13271 @emph{Check attribute casing.}
13273 Attribute names, including the case of keywords such as @code{digits}
13274 used as attributes names, must be written in mixed case, that is, the
13275 initial letter and any letter following an underscore must be uppercase.
13276 All other letters must be lowercase.
13277 @end table
13279 @geindex -gnatyA (gcc)
13282 @table @asis
13284 @item @code{-gnatyA}
13286 @emph{Use of array index numbers in array attributes.}
13288 When using the array attributes First, Last, Range,
13289 or Length, the index number must be omitted for one-dimensional arrays
13290 and is required for multi-dimensional arrays.
13291 @end table
13293 @geindex -gnatyb (gcc)
13296 @table @asis
13298 @item @code{-gnatyb}
13300 @emph{Blanks not allowed at statement end.}
13302 Trailing blanks are not allowed at the end of statements. The purpose of this
13303 rule, together with h (no horizontal tabs), is to enforce a canonical format
13304 for the use of blanks to separate source tokens.
13305 @end table
13307 @geindex -gnatyB (gcc)
13310 @table @asis
13312 @item @code{-gnatyB}
13314 @emph{Check Boolean operators.}
13316 The use of AND/OR operators is not permitted except in the cases of modular
13317 operands, array operands, and simple stand-alone boolean variables or
13318 boolean constants. In all other cases @code{and then}/@cite{or else} are
13319 required.
13320 @end table
13322 @geindex -gnatyc (gcc)
13325 @table @asis
13327 @item @code{-gnatyc}
13329 @emph{Check comments, double space.}
13331 Comments must meet the following set of rules:
13334 @itemize *
13336 @item 
13337 The @code{--} that starts the column must either start in column one,
13338 or else at least one blank must precede this sequence.
13340 @item 
13341 Comments that follow other tokens on a line must have at least one blank
13342 following the @code{--} at the start of the comment.
13344 @item 
13345 Full line comments must have at least two blanks following the
13346 @code{--} that starts the comment, with the following exceptions.
13348 @item 
13349 A line consisting only of the @code{--} characters, possibly preceded
13350 by blanks is permitted.
13352 @item 
13353 A comment starting with @code{--x} where @code{x} is a special character
13354 is permitted.
13355 This allows proper processing of the output from specialized tools
13356 such as @code{gnatprep} (where @code{--!} is used) and in earlier versions of the SPARK
13357 annotation
13358 language (where @code{--#} is used). For the purposes of this rule, a
13359 special character is defined as being in one of the ASCII ranges
13360 @code{16#21#...16#2F#} or @code{16#3A#...16#3F#}.
13361 Note that this usage is not permitted
13362 in GNAT implementation units (i.e., when @code{-gnatg} is used).
13364 @item 
13365 A line consisting entirely of minus signs, possibly preceded by blanks, is
13366 permitted. This allows the construction of box comments where lines of minus
13367 signs are used to form the top and bottom of the box.
13369 @item 
13370 A comment that starts and ends with @code{--} is permitted as long as at
13371 least one blank follows the initial @code{--}. Together with the preceding
13372 rule, this allows the construction of box comments, as shown in the following
13373 example:
13375 @example
13376 ---------------------------
13377 -- This is a box comment --
13378 -- with two text lines.  --
13379 ---------------------------
13380 @end example
13381 @end itemize
13382 @end table
13384 @geindex -gnatyC (gcc)
13387 @table @asis
13389 @item @code{-gnatyC}
13391 @emph{Check comments, single space.}
13393 This is identical to @code{c} except that only one space
13394 is required following the @code{--} of a comment instead of two.
13395 @end table
13397 @geindex -gnatyd (gcc)
13400 @table @asis
13402 @item @code{-gnatyd}
13404 @emph{Check no DOS line terminators present.}
13406 All lines must be terminated by a single ASCII.LF
13407 character (in particular the DOS line terminator sequence CR/LF is not
13408 allowed).
13409 @end table
13411 @geindex -gnatyD (gcc)
13414 @table @asis
13416 @item @code{-gnatyD}
13418 @emph{Check declared identifiers in mixed case.}
13420 Declared identifiers must be in mixed case, as in
13421 This_Is_An_Identifier. Use -gnatyr in addition to ensure
13422 that references match declarations.
13423 @end table
13425 @geindex -gnatye (gcc)
13428 @table @asis
13430 @item @code{-gnatye}
13432 @emph{Check end/exit labels.}
13434 Optional labels on @code{end} statements ending subprograms and on
13435 @code{exit} statements exiting named loops, are required to be present.
13436 @end table
13438 @geindex -gnatyf (gcc)
13441 @table @asis
13443 @item @code{-gnatyf}
13445 @emph{No form feeds or vertical tabs.}
13447 Neither form feeds nor vertical tab characters are permitted
13448 in the source text.
13449 @end table
13451 @geindex -gnatyg (gcc)
13454 @table @asis
13456 @item @code{-gnatyg}
13458 @emph{GNAT style mode.}
13460 The set of style check switches is set to match that used by the GNAT sources.
13461 This may be useful when developing code that is eventually intended to be
13462 incorporated into GNAT. Currently this is equivalent to @code{-gnatyydISux})
13463 but additional style switches may be added to this set in the future without
13464 advance notice.
13465 @end table
13467 @geindex -gnatyh (gcc)
13470 @table @asis
13472 @item @code{-gnatyh}
13474 @emph{No horizontal tabs.}
13476 Horizontal tab characters are not permitted in the source text.
13477 Together with the b (no blanks at end of line) check, this
13478 enforces a canonical form for the use of blanks to separate
13479 source tokens.
13480 @end table
13482 @geindex -gnatyi (gcc)
13485 @table @asis
13487 @item @code{-gnatyi}
13489 @emph{Check if-then layout.}
13491 The keyword @code{then} must appear either on the same
13492 line as corresponding @code{if}, or on a line on its own, lined
13493 up under the @code{if}.
13494 @end table
13496 @geindex -gnatyI (gcc)
13499 @table @asis
13501 @item @code{-gnatyI}
13503 @emph{check mode IN keywords.}
13505 Mode @code{in} (the default mode) is not
13506 allowed to be given explicitly. @code{in out} is fine,
13507 but not @code{in} on its own.
13508 @end table
13510 @geindex -gnatyk (gcc)
13513 @table @asis
13515 @item @code{-gnatyk}
13517 @emph{Check keyword casing.}
13519 All keywords must be in lower case (with the exception of keywords
13520 such as @code{digits} used as attribute names to which this check
13521 does not apply). A single error is reported for each line breaking
13522 this rule even if multiple casing issues exist on a same line.
13523 @end table
13525 @geindex -gnatyl (gcc)
13528 @table @asis
13530 @item @code{-gnatyl}
13532 @emph{Check layout.}
13534 Layout of statement and declaration constructs must follow the
13535 recommendations in the Ada Reference Manual, as indicated by the
13536 form of the syntax rules. For example an @code{else} keyword must
13537 be lined up with the corresponding @code{if} keyword.
13539 There are two respects in which the style rule enforced by this check
13540 option are more liberal than those in the Ada Reference Manual. First
13541 in the case of record declarations, it is permissible to put the
13542 @code{record} keyword on the same line as the @code{type} keyword, and
13543 then the @code{end} in @code{end record} must line up under @code{type}.
13544 This is also permitted when the type declaration is split on two lines.
13545 For example, any of the following three layouts is acceptable:
13547 @example
13548 type q is record
13549    a : integer;
13550    b : integer;
13551 end record;
13553 type q is
13554    record
13555       a : integer;
13556       b : integer;
13557    end record;
13559 type q is
13560    record
13561       a : integer;
13562       b : integer;
13563 end record;
13564 @end example
13566 Second, in the case of a block statement, a permitted alternative
13567 is to put the block label on the same line as the @code{declare} or
13568 @code{begin} keyword, and then line the @code{end} keyword up under
13569 the block label. For example both the following are permitted:
13571 @example
13572 Block : declare
13573    A : Integer := 3;
13574 begin
13575    Proc (A, A);
13576 end Block;
13578 Block :
13579    declare
13580       A : Integer := 3;
13581    begin
13582       Proc (A, A);
13583    end Block;
13584 @end example
13586 The same alternative format is allowed for loops. For example, both of
13587 the following are permitted:
13589 @example
13590 Clear : while J < 10 loop
13591    A (J) := 0;
13592 end loop Clear;
13594 Clear :
13595    while J < 10 loop
13596       A (J) := 0;
13597    end loop Clear;
13598 @end example
13599 @end table
13601 @geindex -gnatyLnnn (gcc)
13604 @table @asis
13606 @item @code{-gnatyL}
13608 @emph{Set maximum nesting level.}
13610 The maximum level of nesting of constructs (including subprograms, loops,
13611 blocks, packages, and conditionals) may not exceed the given value
13612 @emph{nnn}. A value of zero disconnects this style check.
13613 @end table
13615 @geindex -gnatym (gcc)
13618 @table @asis
13620 @item @code{-gnatym}
13622 @emph{Check maximum line length.}
13624 The length of source lines must not exceed 79 characters, including
13625 any trailing blanks. The value of 79 allows convenient display on an
13626 80 character wide device or window, allowing for possible special
13627 treatment of 80 character lines. Note that this count is of
13628 characters in the source text. This means that a tab character counts
13629 as one character in this count and a wide character sequence counts as
13630 a single character (however many bytes are needed in the encoding).
13631 @end table
13633 @geindex -gnatyMnnn (gcc)
13636 @table @asis
13638 @item @code{-gnatyM}
13640 @emph{Set maximum line length.}
13642 The length of lines must not exceed the
13643 given value @emph{nnn}. The maximum value that can be specified is 32767.
13644 If neither style option for setting the line length is used, then the
13645 default is 255. This also controls the maximum length of lexical elements,
13646 where the only restriction is that they must fit on a single line.
13647 @end table
13649 @geindex -gnatyn (gcc)
13652 @table @asis
13654 @item @code{-gnatyn}
13656 @emph{Check casing of entities in Standard.}
13658 Any identifier from Standard must be cased
13659 to match the presentation in the Ada Reference Manual (for example,
13660 @code{Integer} and @code{ASCII.NUL}).
13661 @end table
13663 @geindex -gnatyN (gcc)
13666 @table @asis
13668 @item @code{-gnatyN}
13670 @emph{Turn off all style checks.}
13672 All style check options are turned off.
13673 @end table
13675 @geindex -gnatyo (gcc)
13678 @table @asis
13680 @item @code{-gnatyo}
13682 @emph{Check order of subprogram bodies.}
13684 All subprogram bodies in a given scope
13685 (e.g., a package body) must be in alphabetical order. The ordering
13686 rule uses normal Ada rules for comparing strings, ignoring casing
13687 of letters, except that if there is a trailing numeric suffix, then
13688 the value of this suffix is used in the ordering (e.g., Junk2 comes
13689 before Junk10).
13690 @end table
13692 @geindex -gnatyO (gcc)
13695 @table @asis
13697 @item @code{-gnatyO}
13699 @emph{Check that overriding subprograms are explicitly marked as such.}
13701 This applies to all subprograms of a derived type that override a primitive
13702 operation of the type, for both tagged and untagged types. In particular,
13703 the declaration of a primitive operation of a type extension that overrides
13704 an inherited operation must carry an overriding indicator. Another case is
13705 the declaration of a function that overrides a predefined operator (such
13706 as an equality operator).
13707 @end table
13709 @geindex -gnatyp (gcc)
13712 @table @asis
13714 @item @code{-gnatyp}
13716 @emph{Check pragma casing.}
13718 Pragma names must be written in mixed case, that is, the
13719 initial letter and any letter following an underscore must be uppercase.
13720 All other letters must be lowercase. An exception is that SPARK_Mode is
13721 allowed as an alternative for Spark_Mode.
13722 @end table
13724 @geindex -gnatyr (gcc)
13727 @table @asis
13729 @item @code{-gnatyr}
13731 @emph{Check references.}
13733 All identifier references must be cased in the same way as the
13734 corresponding declaration. No specific casing style is imposed on
13735 identifiers. The only requirement is for consistency of references
13736 with declarations.
13737 @end table
13739 @geindex -gnatys (gcc)
13742 @table @asis
13744 @item @code{-gnatys}
13746 @emph{Check separate specs.}
13748 Separate declarations (‘specs’) are required for subprograms (a
13749 body is not allowed to serve as its own declaration). The only
13750 exception is that parameterless library level procedures are
13751 not required to have a separate declaration. This exception covers
13752 the most frequent form of main program procedures.
13753 @end table
13755 @geindex -gnatyS (gcc)
13758 @table @asis
13760 @item @code{-gnatyS}
13762 @emph{Check no statements after then/else.}
13764 No statements are allowed
13765 on the same line as a @code{then} or @code{else} keyword following the
13766 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
13767 affected, and a special exception allows a pragma to appear after @code{else}.
13768 @end table
13770 @geindex -gnatyt (gcc)
13773 @table @asis
13775 @item @code{-gnatyt}
13777 @emph{Check token spacing.}
13779 The following token spacing rules are enforced:
13782 @itemize *
13784 @item 
13785 The keywords @code{abs} and @code{not} must be followed by a space.
13787 @item 
13788 The token @code{=>} must be surrounded by spaces.
13790 @item 
13791 The token @code{<>} must be preceded by a space or a left parenthesis.
13793 @item 
13794 Binary operators other than @code{**} must be surrounded by spaces.
13795 There is no restriction on the layout of the @code{**} binary operator.
13797 @item 
13798 Colon must be surrounded by spaces.
13800 @item 
13801 Colon-equal (assignment, initialization) must be surrounded by spaces.
13803 @item 
13804 Comma must be the first non-blank character on the line, or be
13805 immediately preceded by a non-blank character, and must be followed
13806 by a space.
13808 @item 
13809 If the token preceding a left parenthesis ends with a letter or digit, then
13810 a space must separate the two tokens.
13812 @item 
13813 If the token following a right parenthesis starts with a letter or digit, then
13814 a space must separate the two tokens.
13816 @item 
13817 A right parenthesis must either be the first non-blank character on
13818 a line, or it must be preceded by a non-blank character.
13820 @item 
13821 A semicolon must not be preceded by a space, and must not be followed by
13822 a non-blank character.
13824 @item 
13825 A unary plus or minus may not be followed by a space.
13827 @item 
13828 A vertical bar must be surrounded by spaces.
13829 @end itemize
13831 Exactly one blank (and no other white space) must appear between
13832 a @code{not} token and a following @code{in} token.
13833 @end table
13835 @geindex -gnatyu (gcc)
13838 @table @asis
13840 @item @code{-gnatyu}
13842 @emph{Check unnecessary blank lines.}
13844 Unnecessary blank lines are not allowed. A blank line is considered
13845 unnecessary if it appears at the end of the file, or if more than
13846 one blank line occurs in sequence.
13847 @end table
13849 @geindex -gnatyx (gcc)
13852 @table @asis
13854 @item @code{-gnatyx}
13856 @emph{Check extra parentheses.}
13858 Unnecessary extra level of parentheses (C-style) are not allowed
13859 around conditions in @code{if} statements, @code{while} statements and
13860 @code{exit} statements.
13861 @end table
13863 @geindex -gnatyy (gcc)
13866 @table @asis
13868 @item @code{-gnatyy}
13870 @emph{Set all standard style check options.}
13872 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
13873 options enabled with the exception of @code{-gnatyB}, @code{-gnatyd},
13874 @code{-gnatyI}, @code{-gnatyLnnn}, @code{-gnatyo}, @code{-gnatyO},
13875 @code{-gnatyS}, @code{-gnatyu}, and @code{-gnatyx}.
13876 @end table
13878 @geindex -gnaty- (gcc)
13881 @table @asis
13883 @item @code{-gnaty-}
13885 @emph{Remove style check options.}
13887 This causes any subsequent options in the string to act as canceling the
13888 corresponding style check option. To cancel maximum nesting level control,
13889 use the @code{L} parameter without any integer value after that, because any
13890 digit following @emph{-} in the parameter string of the @code{-gnaty}
13891 option will be treated as canceling the indentation check. The same is true
13892 for the @code{M} parameter. @code{y} and @code{N} parameters are not
13893 allowed after @emph{-}.
13894 @end table
13896 @geindex -gnaty+ (gcc)
13899 @table @asis
13901 @item @code{-gnaty+}
13903 @emph{Enable style check options.}
13905 This causes any subsequent options in the string to enable the corresponding
13906 style check option. That is, it cancels the effect of a previous -,
13907 if any.
13908 @end table
13910 @c end of switch description (leave this comment to ease automatic parsing for
13912 @c GNAT Studio)
13914 In the above rules, appearing in column one is always permitted, that is,
13915 counts as meeting either a requirement for a required preceding space,
13916 or as meeting a requirement for no preceding space.
13918 Appearing at the end of a line is also always permitted, that is, counts
13919 as meeting either a requirement for a following space, or as meeting
13920 a requirement for no following space.
13922 If any of these style rules is violated, a message is generated giving
13923 details on the violation. The initial characters of such messages are
13924 always ‘@cite{(style)}’. Note that these messages are treated as warning
13925 messages, so they normally do not prevent the generation of an object
13926 file. The @code{-gnatwe} switch can be used to treat warning messages,
13927 including style messages, as fatal errors.
13929 The switch @code{-gnaty} on its own (that is not
13930 followed by any letters or digits) is equivalent
13931 to the use of @code{-gnatyy} as described above, that is all
13932 built-in standard style check options are enabled.
13934 The switch @code{-gnatyN} clears any previously set style checks.
13936 @node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
13937 @anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{f5}@anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{ea}
13938 @subsection Run-Time Checks
13941 @geindex Division by zero
13943 @geindex Access before elaboration
13945 @geindex Checks
13946 @geindex division by zero
13948 @geindex Checks
13949 @geindex access before elaboration
13951 @geindex Checks
13952 @geindex stack overflow checking
13954 By default, the following checks are suppressed: stack overflow
13955 checks, and checks for access before elaboration on subprogram
13956 calls. All other checks, including overflow checks, range checks and
13957 array bounds checks, are turned on by default. The following @code{gcc}
13958 switches refine this default behavior.
13960 @geindex -gnatp (gcc)
13963 @table @asis
13965 @item @code{-gnatp}
13967 @geindex Suppressing checks
13969 @geindex Checks
13970 @geindex suppressing
13972 This switch causes the unit to be compiled
13973 as though @code{pragma Suppress (All_checks)}
13974 had been present in the source. Validity checks are also eliminated (in
13975 other words @code{-gnatp} also implies @code{-gnatVn}.
13976 Use this switch to improve the performance
13977 of the code at the expense of safety in the presence of invalid data or
13978 program bugs.
13980 Note that when checks are suppressed, the compiler is allowed, but not
13981 required, to omit the checking code. If the run-time cost of the
13982 checking code is zero or near-zero, the compiler will generate it even
13983 if checks are suppressed. In particular, if the compiler can prove
13984 that a certain check will necessarily fail, it will generate code to
13985 do an unconditional ‘raise’, even if checks are suppressed. The
13986 compiler warns in this case. Another case in which checks may not be
13987 eliminated is when they are embedded in certain run-time routines such
13988 as math library routines.
13990 Of course, run-time checks are omitted whenever the compiler can prove
13991 that they will not fail, whether or not checks are suppressed.
13993 Note that if you suppress a check that would have failed, program
13994 execution is erroneous, which means the behavior is totally
13995 unpredictable. The program might crash, or print wrong answers, or
13996 do anything else. It might even do exactly what you wanted it to do
13997 (and then it might start failing mysteriously next week or next
13998 year). The compiler will generate code based on the assumption that
13999 the condition being checked is true, which can result in erroneous
14000 execution if that assumption is wrong.
14002 The checks subject to suppression include all the checks defined by the Ada
14003 standard, the additional implementation defined checks @code{Alignment_Check},
14004 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, @code{Container_Checks}, @code{Tampering_Check},
14005 and @code{Validity_Check}, as well as any checks introduced using @code{pragma Check_Name}.
14006 Note that @code{Atomic_Synchronization} is not automatically suppressed by use of this option.
14008 If the code depends on certain checks being active, you can use
14009 pragma @code{Unsuppress} either as a configuration pragma or as
14010 a local pragma to make sure that a specified check is performed
14011 even if @code{gnatp} is specified.
14013 The @code{-gnatp} switch has no effect if a subsequent
14014 @code{-gnat-p} switch appears.
14015 @end table
14017 @geindex -gnat-p (gcc)
14019 @geindex Suppressing checks
14021 @geindex Checks
14022 @geindex suppressing
14024 @geindex Suppress
14027 @table @asis
14029 @item @code{-gnat-p}
14031 This switch cancels the effect of a previous @code{gnatp} switch.
14032 @end table
14034 @geindex -gnato?? (gcc)
14036 @geindex Overflow checks
14038 @geindex Overflow mode
14040 @geindex Check
14041 @geindex overflow
14044 @table @asis
14046 @item @code{-gnato??}
14048 This switch controls the mode used for computing intermediate
14049 arithmetic integer operations, and also enables overflow checking.
14050 For a full description of overflow mode and checking control, see
14051 the ‘Overflow Check Handling in GNAT’ appendix in this
14052 User’s Guide.
14054 Overflow checks are always enabled by this switch. The argument
14055 controls the mode, using the codes
14058 @table @asis
14060 @item @emph{1 = STRICT}
14062 In STRICT mode, intermediate operations are always done using the
14063 base type, and overflow checking ensures that the result is within
14064 the base type range.
14066 @item @emph{2 = MINIMIZED}
14068 In MINIMIZED mode, overflows in intermediate operations are avoided
14069 where possible by using a larger integer type for the computation
14070 (typically @code{Long_Long_Integer}). Overflow checking ensures that
14071 the result fits in this larger integer type.
14073 @item @emph{3 = ELIMINATED}
14075 In ELIMINATED mode, overflows in intermediate operations are avoided
14076 by using multi-precision arithmetic. In this case, overflow checking
14077 has no effect on intermediate operations (since overflow is impossible).
14078 @end table
14080 If two digits are present after @code{-gnato} then the first digit
14081 sets the mode for expressions outside assertions, and the second digit
14082 sets the mode for expressions within assertions. Here assertions is used
14083 in the technical sense (which includes for example precondition and
14084 postcondition expressions).
14086 If one digit is present, the corresponding mode is applicable to both
14087 expressions within and outside assertion expressions.
14089 If no digits are present, the default is to enable overflow checks
14090 and set STRICT mode for both kinds of expressions. This is compatible
14091 with the use of @code{-gnato} in previous versions of GNAT.
14093 @geindex Machine_Overflows
14095 Note that the @code{-gnato??} switch does not affect the code generated
14096 for any floating-point operations; it applies only to integer semantics.
14097 For floating-point, GNAT has the @code{Machine_Overflows}
14098 attribute set to @code{False} and the normal mode of operation is to
14099 generate IEEE NaN and infinite values on overflow or invalid operations
14100 (such as dividing 0.0 by 0.0).
14102 The reason that we distinguish overflow checking from other kinds of
14103 range constraint checking is that a failure of an overflow check, unlike
14104 for example the failure of a range check, can result in an incorrect
14105 value, but cannot cause random memory destruction (like an out of range
14106 subscript), or a wild jump (from an out of range case value). Overflow
14107 checking is also quite expensive in time and space, since in general it
14108 requires the use of double length arithmetic.
14110 Note again that the default is @code{-gnato11} (equivalent to @code{-gnato1}),
14111 so overflow checking is performed in STRICT mode by default.
14112 @end table
14114 @geindex -gnatE (gcc)
14116 @geindex Elaboration checks
14118 @geindex Check
14119 @geindex elaboration
14122 @table @asis
14124 @item @code{-gnatE}
14126 Enables dynamic checks for access-before-elaboration
14127 on subprogram calls and generic instantiations.
14128 Note that @code{-gnatE} is not necessary for safety, because in the
14129 default mode, GNAT ensures statically that the checks would not fail.
14130 For full details of the effect and use of this switch,
14131 @ref{c7,,Compiling with gcc}.
14132 @end table
14134 @geindex -fstack-check (gcc)
14136 @geindex Stack Overflow Checking
14138 @geindex Checks
14139 @geindex stack overflow checking
14142 @table @asis
14144 @item @code{-fstack-check}
14146 Activates stack overflow checking. For full details of the effect and use of
14147 this switch see @ref{e5,,Stack Overflow Checking}.
14148 @end table
14150 @geindex Unsuppress
14152 The setting of these switches only controls the default setting of the
14153 checks. You may modify them using either @code{Suppress} (to remove
14154 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
14155 the program source.
14157 @node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
14158 @anchor{gnat_ugn/building_executable_programs_with_gnat id20}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-syntax-checking}@anchor{f7}
14159 @subsection Using @code{gcc} for Syntax Checking
14162 @geindex -gnats (gcc)
14165 @table @asis
14167 @item @code{-gnats}
14169 The @code{s} stands for ‘syntax’.
14171 Run GNAT in syntax checking only mode. For
14172 example, the command
14174 @example
14175 $ gcc -c -gnats x.adb
14176 @end example
14178 compiles file @code{x.adb} in syntax-check-only mode. You can check a
14179 series of files in a single command
14180 , and can use wildcards to specify such a group of files.
14181 Note that you must specify the @code{-c} (compile
14182 only) flag in addition to the @code{-gnats} flag.
14184 You may use other switches in conjunction with @code{-gnats}. In
14185 particular, @code{-gnatl} and @code{-gnatv} are useful to control the
14186 format of any generated error messages.
14188 When the source file is empty or contains only empty lines and/or comments,
14189 the output is a warning:
14191 @example
14192 $ gcc -c -gnats -x ada toto.txt
14193 toto.txt:1:01: warning: empty file, contains no compilation units
14195 @end example
14197 Otherwise, the output is simply the error messages, if any. No object file or
14198 ALI file is generated by a syntax-only compilation. Also, no units other
14199 than the one specified are accessed. For example, if a unit @code{X}
14200 @emph{with}s a unit @code{Y}, compiling unit @code{X} in syntax
14201 check only mode does not access the source file containing unit
14202 @code{Y}.
14204 @geindex Multiple units
14205 @geindex syntax checking
14207 Normally, GNAT allows only a single unit in a source file. However, this
14208 restriction does not apply in syntax-check-only mode, and it is possible
14209 to check a file containing multiple compilation units concatenated
14210 together. This is primarily used by the @code{gnatchop} utility
14211 (@ref{1d,,Renaming Files with gnatchop}).
14212 @end table
14214 @node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
14215 @anchor{gnat_ugn/building_executable_programs_with_gnat id21}@anchor{f8}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-semantic-checking}@anchor{f9}
14216 @subsection Using @code{gcc} for Semantic Checking
14219 @geindex -gnatc (gcc)
14222 @table @asis
14224 @item @code{-gnatc}
14226 The @code{c} stands for ‘check’.
14227 Causes the compiler to operate in semantic check mode,
14228 with full checking for all illegalities specified in the
14229 Ada Reference Manual, but without generation of any object code
14230 (no object file is generated).
14232 Because dependent files must be accessed, you must follow the GNAT
14233 semantic restrictions on file structuring to operate in this mode:
14236 @itemize *
14238 @item 
14239 The needed source files must be accessible
14240 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
14242 @item 
14243 Each file must contain only one compilation unit.
14245 @item 
14246 The file name and unit name must match (@ref{3b,,File Naming Rules}).
14247 @end itemize
14249 The output consists of error messages as appropriate. No object file is
14250 generated. An @code{ALI} file is generated for use in the context of
14251 cross-reference tools, but this file is marked as not being suitable
14252 for binding (since no object file is generated).
14253 The checking corresponds exactly to the notion of
14254 legality in the Ada Reference Manual.
14256 Any unit can be compiled in semantics-checking-only mode, including
14257 units that would not normally be compiled (subunits,
14258 and specifications where a separate body is present).
14259 @end table
14261 @node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
14262 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-different-versions-of-ada}@anchor{6}@anchor{gnat_ugn/building_executable_programs_with_gnat id22}@anchor{fa}
14263 @subsection Compiling Different Versions of Ada
14266 The switches described in this section allow you to explicitly specify
14267 the version of the Ada language that your programs are written in.
14268 The default mode is Ada 2012,
14269 but you can also specify Ada 95, Ada 2005 mode, or
14270 indicate Ada 83 compatibility mode.
14272 @geindex Compatibility with Ada 83
14274 @geindex -gnat83 (gcc)
14276 @geindex ACVC
14277 @geindex Ada 83 tests
14279 @geindex Ada 83 mode
14282 @table @asis
14284 @item @code{-gnat83} (Ada 83 Compatibility Mode)
14286 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
14287 specifies that the program is to be compiled in Ada 83 mode. With
14288 @code{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
14289 semantics where this can be done easily.
14290 It is not possible to guarantee this switch does a perfect
14291 job; some subtle tests, such as are
14292 found in earlier ACVC tests (and that have been removed from the ACATS suite
14293 for Ada 95), might not compile correctly.
14294 Nevertheless, this switch may be useful in some circumstances, for example
14295 where, due to contractual reasons, existing code needs to be maintained
14296 using only Ada 83 features.
14298 With few exceptions (most notably the need to use @code{<>} on
14299 unconstrained 
14300 @geindex Generic formal parameters
14301 generic formal parameters,
14302 the use of the new Ada 95 / Ada 2005
14303 reserved words, and the use of packages
14304 with optional bodies), it is not necessary to specify the
14305 @code{-gnat83} switch when compiling Ada 83 programs, because, with rare
14306 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
14307 a correct Ada 83 program is usually also a correct program
14308 in these later versions of the language standard. For further information
14309 please refer to the @emph{Compatibility and Porting Guide} chapter in the
14310 @cite{GNAT Reference Manual}.
14311 @end table
14313 @geindex -gnat95 (gcc)
14315 @geindex Ada 95 mode
14318 @table @asis
14320 @item @code{-gnat95} (Ada 95 mode)
14322 This switch directs the compiler to implement the Ada 95 version of the
14323 language.
14324 Since Ada 95 is almost completely upwards
14325 compatible with Ada 83, Ada 83 programs may generally be compiled using
14326 this switch (see the description of the @code{-gnat83} switch for further
14327 information about Ada 83 mode).
14328 If an Ada 2005 program is compiled in Ada 95 mode,
14329 uses of the new Ada 2005 features will cause error
14330 messages or warnings.
14332 This switch also can be used to cancel the effect of a previous
14333 @code{-gnat83}, @code{-gnat05/2005}, or @code{-gnat12/2012}
14334 switch earlier in the command line.
14335 @end table
14337 @geindex -gnat05 (gcc)
14339 @geindex -gnat2005 (gcc)
14341 @geindex Ada 2005 mode
14344 @table @asis
14346 @item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
14348 This switch directs the compiler to implement the Ada 2005 version of the
14349 language, as documented in the official Ada standards document.
14350 Since Ada 2005 is almost completely upwards
14351 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
14352 may generally be compiled using this switch (see the description of the
14353 @code{-gnat83} and @code{-gnat95} switches for further
14354 information).
14355 @end table
14357 @geindex -gnat12 (gcc)
14359 @geindex -gnat2012 (gcc)
14361 @geindex Ada 2012 mode
14364 @table @asis
14366 @item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
14368 This switch directs the compiler to implement the Ada 2012 version of the
14369 language (also the default).
14370 Since Ada 2012 is almost completely upwards
14371 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
14372 Ada 83 and Ada 95 programs
14373 may generally be compiled using this switch (see the description of the
14374 @code{-gnat83}, @code{-gnat95}, and @code{-gnat05/2005} switches
14375 for further information).
14376 @end table
14378 @geindex -gnat2022 (gcc)
14380 @geindex Ada 2022 mode
14383 @table @asis
14385 @item @code{-gnat2022} (Ada 2022 mode)
14387 This switch directs the compiler to implement the Ada 2022 version of the
14388 language.
14389 @end table
14391 @geindex -gnatX (gcc)
14393 @geindex Ada language extensions
14395 @geindex GNAT extensions
14398 @table @asis
14400 @item @code{-gnatX} (Enable GNAT Extensions)
14402 This switch directs the compiler to implement the latest version of the
14403 language (currently Ada 2022) and also to enable certain GNAT implementation
14404 extensions that are not part of any Ada standard. For a full list of these
14405 extensions, see the GNAT reference manual, @code{Pragma Extensions_Allowed}.
14406 @end table
14408 @node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14409 @anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{31}@anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{fb}
14410 @subsection Character Set Control
14413 @geindex -gnati (gcc)
14416 @table @asis
14418 @item @code{-gnati@emph{c}}
14420 Normally GNAT recognizes the Latin-1 character set in source program
14421 identifiers, as described in the Ada Reference Manual.
14422 This switch causes
14423 GNAT to recognize alternate character sets in identifiers. @code{c} is a
14424 single character  indicating the character set, as follows:
14427 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14428 @item
14430 @emph{1}
14432 @tab
14434 ISO 8859-1 (Latin-1) identifiers
14436 @item
14438 @emph{2}
14440 @tab
14442 ISO 8859-2 (Latin-2) letters allowed in identifiers
14444 @item
14446 @emph{3}
14448 @tab
14450 ISO 8859-3 (Latin-3) letters allowed in identifiers
14452 @item
14454 @emph{4}
14456 @tab
14458 ISO 8859-4 (Latin-4) letters allowed in identifiers
14460 @item
14462 @emph{5}
14464 @tab
14466 ISO 8859-5 (Cyrillic) letters allowed in identifiers
14468 @item
14470 @emph{9}
14472 @tab
14474 ISO 8859-15 (Latin-9) letters allowed in identifiers
14476 @item
14478 @emph{p}
14480 @tab
14482 IBM PC letters (code page 437) allowed in identifiers
14484 @item
14486 @emph{8}
14488 @tab
14490 IBM PC letters (code page 850) allowed in identifiers
14492 @item
14494 @emph{f}
14496 @tab
14498 Full upper-half codes allowed in identifiers
14500 @item
14502 @emph{n}
14504 @tab
14506 No upper-half codes allowed in identifiers
14508 @item
14510 @emph{w}
14512 @tab
14514 Wide-character codes (that is, codes greater than 255)
14515 allowed in identifiers
14517 @end multitable
14520 See @ref{23,,Foreign Language Representation} for full details on the
14521 implementation of these character sets.
14522 @end table
14524 @geindex -gnatW (gcc)
14527 @table @asis
14529 @item @code{-gnatW@emph{e}}
14531 Specify the method of encoding for wide characters.
14532 @code{e} is one of the following:
14535 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14536 @item
14538 @emph{h}
14540 @tab
14542 Hex encoding (brackets coding also recognized)
14544 @item
14546 @emph{u}
14548 @tab
14550 Upper half encoding (brackets encoding also recognized)
14552 @item
14554 @emph{s}
14556 @tab
14558 Shift/JIS encoding (brackets encoding also recognized)
14560 @item
14562 @emph{e}
14564 @tab
14566 EUC encoding (brackets encoding also recognized)
14568 @item
14570 @emph{8}
14572 @tab
14574 UTF-8 encoding (brackets encoding also recognized)
14576 @item
14578 @emph{b}
14580 @tab
14582 Brackets encoding only (default value)
14584 @end multitable
14587 For full details on these encoding
14588 methods see @ref{37,,Wide_Character Encodings}.
14589 Note that brackets coding is always accepted, even if one of the other
14590 options is specified, so for example @code{-gnatW8} specifies that both
14591 brackets and UTF-8 encodings will be recognized. The units that are
14592 with’ed directly or indirectly will be scanned using the specified
14593 representation scheme, and so if one of the non-brackets scheme is
14594 used, it must be used consistently throughout the program. However,
14595 since brackets encoding is always recognized, it may be conveniently
14596 used in standard libraries, allowing these libraries to be used with
14597 any of the available coding schemes.
14599 Note that brackets encoding only applies to program text. Within comments,
14600 brackets are considered to be normal graphic characters, and bracket sequences
14601 are never recognized as wide characters.
14603 If no @code{-gnatW?} parameter is present, then the default
14604 representation is normally Brackets encoding only. However, if the
14605 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14606 byte order mark or BOM for UTF-8), then these three characters are
14607 skipped and the default representation for the file is set to UTF-8.
14609 Note that the wide character representation that is specified (explicitly
14610 or by default) for the main program also acts as the default encoding used
14611 for Wide_Text_IO files if not specifically overridden by a WCEM form
14612 parameter.
14613 @end table
14615 When no @code{-gnatW?} is specified, then characters (other than wide
14616 characters represented using brackets notation) are treated as 8-bit
14617 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14618 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14619 characters in the range 16#00#..16#1F# are not accepted in program text
14620 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14621 in program text, but allowed and ignored in comments. Note in particular
14622 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14623 as an end of line in this default mode. If your source program contains
14624 instances of the NEL character used as a line terminator,
14625 you must use UTF-8 encoding for the whole
14626 source program. In default mode, all lines must be ended by a standard
14627 end of line sequence (CR, CR/LF, or LF).
14629 Note that the convention of simply accepting all upper half characters in
14630 comments means that programs that use standard ASCII for program text, but
14631 UTF-8 encoding for comments are accepted in default mode, providing that the
14632 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14633 This is a common mode for many programs with foreign language comments.
14635 @node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14636 @anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{fc}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{fd}
14637 @subsection File Naming Control
14640 @geindex -gnatk (gcc)
14643 @table @asis
14645 @item @code{-gnatk@emph{n}}
14647 Activates file name ‘krunching’. @code{n}, a decimal integer in the range
14648 1-999, indicates the maximum allowable length of a file name (not
14649 including the @code{.ads} or @code{.adb} extension). The default is not
14650 to enable file name krunching.
14652 For the source file naming rules, @ref{3b,,File Naming Rules}.
14653 @end table
14655 @node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14656 @anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{fe}@anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{ff}
14657 @subsection Subprogram Inlining Control
14660 @geindex -gnatn (gcc)
14663 @table @asis
14665 @item @code{-gnatn[12]}
14667 The @code{n} here is intended to suggest the first syllable of the word ‘inline’.
14668 GNAT recognizes and processes @code{Inline} pragmas. However, for inlining to
14669 actually occur, optimization must be enabled and, by default, inlining of
14670 subprograms across units is not performed. If you want to additionally
14671 enable inlining of subprograms specified by pragma @code{Inline} across units,
14672 you must also specify this switch.
14674 In the absence of this switch, GNAT does not attempt inlining across units
14675 and does not access the bodies of subprograms for which @code{pragma Inline} is
14676 specified if they are not in the current unit.
14678 You can optionally specify the inlining level: 1 for moderate inlining across
14679 units, which is a good compromise between compilation times and performances
14680 at run time, or 2 for full inlining across units, which may bring about
14681 longer compilation times. If no inlining level is specified, the compiler will
14682 pick it based on the optimization level: 1 for @code{-O1}, @code{-O2} or
14683 @code{-Os} and 2 for @code{-O3}.
14685 If you specify this switch the compiler will access these bodies,
14686 creating an extra source dependency for the resulting object file, and
14687 where possible, the call will be inlined.
14688 For further details on when inlining is possible
14689 see @ref{100,,Inlining of Subprograms}.
14690 @end table
14692 @geindex -gnatN (gcc)
14695 @table @asis
14697 @item @code{-gnatN}
14699 This switch activates front-end inlining which also
14700 generates additional dependencies.
14702 When using a gcc-based back end, then the use of
14703 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
14704 Historically front end inlining was more extensive than the gcc back end
14705 inlining, but that is no longer the case.
14706 @end table
14708 @node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14709 @anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{101}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{102}
14710 @subsection Auxiliary Output Control
14713 @geindex -gnatu (gcc)
14716 @table @asis
14718 @item @code{-gnatu}
14720 Print a list of units required by this compilation on @code{stdout}.
14721 The listing includes all units on which the unit being compiled depends
14722 either directly or indirectly.
14723 @end table
14725 @geindex -pass-exit-codes (gcc)
14728 @table @asis
14730 @item @code{-pass-exit-codes}
14732 If this switch is not used, the exit code returned by @code{gcc} when
14733 compiling multiple files indicates whether all source files have
14734 been successfully used to generate object files or not.
14736 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
14737 exit status and allows an integrated development environment to better
14738 react to a compilation failure. Those exit status are:
14741 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14742 @item
14744 @emph{5}
14746 @tab
14748 There was an error in at least one source file.
14750 @item
14752 @emph{3}
14754 @tab
14756 At least one source file did not generate an object file.
14758 @item
14760 @emph{2}
14762 @tab
14764 The compiler died unexpectedly (internal error for example).
14766 @item
14768 @emph{0}
14770 @tab
14772 An object file has been generated for every source file.
14774 @end multitable
14776 @end table
14778 @node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
14779 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{103}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{104}
14780 @subsection Debugging Control
14783 @quotation
14785 @geindex Debugging options
14786 @end quotation
14788 @geindex -gnatd (gcc)
14791 @table @asis
14793 @item @code{-gnatd@emph{x}}
14795 Activate internal debugging switches. @code{x} is a letter or digit, or
14796 string of letters or digits, which specifies the type of debugging
14797 outputs desired. Normally these are used only for internal development
14798 or system debugging purposes. You can find full documentation for these
14799 switches in the body of the @code{Debug} unit in the compiler source
14800 file @code{debug.adb}.
14801 @end table
14803 @geindex -gnatG (gcc)
14806 @table @asis
14808 @item @code{-gnatG[=@emph{nn}]}
14810 This switch causes the compiler to generate auxiliary output containing
14811 a pseudo-source listing of the generated expanded code. Like most Ada
14812 compilers, GNAT works by first transforming the high level Ada code into
14813 lower level constructs. For example, tasking operations are transformed
14814 into calls to the tasking run-time routines. A unique capability of GNAT
14815 is to list this expanded code in a form very close to normal Ada source.
14816 This is very useful in understanding the implications of various Ada
14817 usage on the efficiency of the generated code. There are many cases in
14818 Ada (e.g., the use of controlled types), where simple Ada statements can
14819 generate a lot of run-time code. By using @code{-gnatG} you can identify
14820 these cases, and consider whether it may be desirable to modify the coding
14821 approach to improve efficiency.
14823 The optional parameter @code{nn} if present after -gnatG specifies an
14824 alternative maximum line length that overrides the normal default of 72.
14825 This value is in the range 40-999999, values less than 40 being silently
14826 reset to 40. The equal sign is optional.
14828 The format of the output is very similar to standard Ada source, and is
14829 easily understood by an Ada programmer. The following special syntactic
14830 additions correspond to low level features used in the generated code that
14831 do not have any exact analogies in pure Ada source form. The following
14832 is a partial list of these special constructions. See the spec
14833 of package @code{Sprint} in file @code{sprint.ads} for a full list.
14835 @geindex -gnatL (gcc)
14837 If the switch @code{-gnatL} is used in conjunction with
14838 @code{-gnatG}, then the original source lines are interspersed
14839 in the expanded source (as comment lines with the original line number).
14842 @table @asis
14844 @item @code{new @emph{xxx} [storage_pool = @emph{yyy}]}
14846 Shows the storage pool being used for an allocator.
14848 @item @code{at end @emph{procedure-name};}
14850 Shows the finalization (cleanup) procedure for a scope.
14852 @item @code{(if @emph{expr} then @emph{expr} else @emph{expr})}
14854 Conditional expression equivalent to the @code{x?y:z} construction in C.
14856 @item @code{@emph{target}^(@emph{source})}
14858 A conversion with floating-point truncation instead of rounding.
14860 @item @code{@emph{target}?(@emph{source})}
14862 A conversion that bypasses normal Ada semantic checking. In particular
14863 enumeration types and fixed-point types are treated simply as integers.
14865 @item @code{@emph{target}?^(@emph{source})}
14867 Combines the above two cases.
14868 @end table
14870 @code{@emph{x} #/ @emph{y}}
14872 @code{@emph{x} #mod @emph{y}}
14874 @code{@emph{x} # @emph{y}}
14877 @table @asis
14879 @item @code{@emph{x} #rem @emph{y}}
14881 A division or multiplication of fixed-point values which are treated as
14882 integers without any kind of scaling.
14884 @item @code{free @emph{expr} [storage_pool = @emph{xxx}]}
14886 Shows the storage pool associated with a @code{free} statement.
14888 @item @code{[subtype or type declaration]}
14890 Used to list an equivalent declaration for an internally generated
14891 type that is referenced elsewhere in the listing.
14893 @item @code{freeze @emph{type-name} [@emph{actions}]}
14895 Shows the point at which @code{type-name} is frozen, with possible
14896 associated actions to be performed at the freeze point.
14898 @item @code{reference @emph{itype}}
14900 Reference (and hence definition) to internal type @code{itype}.
14902 @item @code{@emph{function-name}! (@emph{arg}, @emph{arg}, @emph{arg})}
14904 Intrinsic function call.
14906 @item @code{@emph{label-name} : label}
14908 Declaration of label @code{labelname}.
14910 @item @code{#$ @emph{subprogram-name}}
14912 An implicit call to a run-time support routine
14913 (to meet the requirement of H.3.1(9) in a
14914 convenient manner).
14916 @item @code{@emph{expr} && @emph{expr} && @emph{expr} ... && @emph{expr}}
14918 A multiple concatenation (same effect as @code{expr} & @code{expr} &
14919 @code{expr}, but handled more efficiently).
14921 @item @code{[constraint_error]}
14923 Raise the @code{Constraint_Error} exception.
14925 @item @code{@emph{expression}'reference}
14927 A pointer to the result of evaluating @{expression@}.
14929 @item @code{@emph{target-type}!(@emph{source-expression})}
14931 An unchecked conversion of @code{source-expression} to @code{target-type}.
14933 @item @code{[@emph{numerator}/@emph{denominator}]}
14935 Used to represent internal real literals (that) have no exact
14936 representation in base 2-16 (for example, the result of compile time
14937 evaluation of the expression 1.0/27.0).
14938 @end table
14939 @end table
14941 @geindex -gnatD (gcc)
14944 @table @asis
14946 @item @code{-gnatD[=nn]}
14948 When used in conjunction with @code{-gnatG}, this switch causes
14949 the expanded source, as described above for
14950 @code{-gnatG} to be written to files with names
14951 @code{xxx.dg}, where @code{xxx} is the normal file name,
14952 instead of to the standard output file. For
14953 example, if the source file name is @code{hello.adb}, then a file
14954 @code{hello.adb.dg} will be written.  The debugging
14955 information generated by the @code{gcc} @code{-g} switch
14956 will refer to the generated @code{xxx.dg} file. This allows
14957 you to do source level debugging using the generated code which is
14958 sometimes useful for complex code, for example to find out exactly
14959 which part of a complex construction raised an exception. This switch
14960 also suppresses generation of cross-reference information (see
14961 @code{-gnatx}) since otherwise the cross-reference information
14962 would refer to the @code{.dg} file, which would cause
14963 confusion since this is not the original source file.
14965 Note that @code{-gnatD} actually implies @code{-gnatG}
14966 automatically, so it is not necessary to give both options.
14967 In other words @code{-gnatD} is equivalent to @code{-gnatDG}).
14969 @geindex -gnatL (gcc)
14971 If the switch @code{-gnatL} is used in conjunction with
14972 @code{-gnatDG}, then the original source lines are interspersed
14973 in the expanded source (as comment lines with the original line number).
14975 The optional parameter @code{nn} if present after -gnatD specifies an
14976 alternative maximum line length that overrides the normal default of 72.
14977 This value is in the range 40-999999, values less than 40 being silently
14978 reset to 40. The equal sign is optional.
14979 @end table
14981 @geindex -gnatr (gcc)
14983 @geindex pragma Restrictions
14986 @table @asis
14988 @item @code{-gnatr}
14990 This switch causes pragma Restrictions to be treated as Restriction_Warnings
14991 so that violation of restrictions causes warnings rather than illegalities.
14992 This is useful during the development process when new restrictions are added
14993 or investigated. The switch also causes pragma Profile to be treated as
14994 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
14995 restriction warnings rather than restrictions.
14996 @end table
14998 @geindex -gnatR (gcc)
15001 @table @asis
15003 @item @code{-gnatR[0|1|2|3|4][e][j][m][s]}
15005 This switch controls output from the compiler of a listing showing
15006 representation information for declared types, objects and subprograms.
15007 For @code{-gnatR0}, no information is output (equivalent to omitting
15008 the @code{-gnatR} switch). For @code{-gnatR1} (which is the default,
15009 so @code{-gnatR} with no parameter has the same effect), size and
15010 alignment information is listed for declared array and record types.
15012 For @code{-gnatR2}, size and alignment information is listed for all
15013 declared types and objects. The @code{Linker_Section} is also listed for any
15014 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
15015 latter case occurs for objects of a type for which a @code{Linker_Section}
15016 is set).
15018 For @code{-gnatR3}, symbolic expressions for values that are computed
15019 at run time for records are included. These symbolic expressions have
15020 a mostly obvious format with #n being used to represent the value of the
15021 n’th discriminant. See source files @code{repinfo.ads/adb} in the
15022 GNAT sources for full details on the format of @code{-gnatR3} output.
15024 For @code{-gnatR4}, information for relevant compiler-generated types
15025 is also listed, i.e. when they are structurally part of other declared
15026 types and objects.
15028 If the switch is followed by an @code{e} (e.g. @code{-gnatR2e}), then
15029 extended representation information for record sub-components of records
15030 is included.
15032 If the switch is followed by an @code{m} (e.g. @code{-gnatRm}), then
15033 subprogram conventions and parameter passing mechanisms for all the
15034 subprograms are included.
15036 If the switch is followed by a @code{j} (e.g., @code{-gnatRj}), then
15037 the output is in the JSON data interchange format specified by the
15038 ECMA-404 standard. The semantic description of this JSON output is
15039 available in the specification of the Repinfo unit present in the
15040 compiler sources.
15042 If the switch is followed by an @code{s} (e.g., @code{-gnatR3s}), then
15043 the output is to a file with the name @code{file.rep} where @code{file} is
15044 the name of the corresponding source file, except if @code{j} is also
15045 specified, in which case the file name is @code{file.json}.
15047 Note that it is possible for record components to have zero size. In
15048 this case, the component clause uses an obvious extension of permitted
15049 Ada syntax, for example @code{at 0 range 0 .. -1}.
15050 @end table
15052 @geindex -gnatS (gcc)
15055 @table @asis
15057 @item @code{-gnatS}
15059 The use of the switch @code{-gnatS} for an
15060 Ada compilation will cause the compiler to output a
15061 representation of package Standard in a form very
15062 close to standard Ada. It is not quite possible to
15063 do this entirely in standard Ada (since new
15064 numeric base types cannot be created in standard
15065 Ada), but the output is easily
15066 readable to any Ada programmer, and is useful to
15067 determine the characteristics of target dependent
15068 types in package Standard.
15069 @end table
15071 @geindex -gnatx (gcc)
15074 @table @asis
15076 @item @code{-gnatx}
15078 Normally the compiler generates full cross-referencing information in
15079 the @code{ALI} file. This information is used by a number of tools,
15080 including @code{gnatfind} and @code{gnatxref}. The @code{-gnatx} switch
15081 suppresses this information. This saves some space and may slightly
15082 speed up compilation, but means that these tools cannot be used.
15083 @end table
15085 @geindex -fgnat-encodings (gcc)
15088 @table @asis
15090 @item @code{-fgnat-encodings=[all|gdb|minimal]}
15092 This switch controls the balance between GNAT encodings and standard DWARF
15093 emitted in the debug information.
15095 Historically, old debug formats like stabs were not powerful enough to
15096 express some Ada types (for instance, variant records or fixed-point types).
15097 To work around this, GNAT introduced proprietary encodings that embed the
15098 missing information (“GNAT encodings”).
15100 Recent versions of the DWARF debug information format are now able to
15101 correctly describe most of these Ada constructs (“standard DWARF”). As
15102 third-party tools started to use this format, GNAT has been enhanced to
15103 generate it. However, most tools (including GDB) are still relying on GNAT
15104 encodings.
15106 To support all tools, GNAT needs to be versatile about the balance between
15107 generation of GNAT encodings and standard DWARF. This is what
15108 @code{-fgnat-encodings} is about.
15111 @itemize *
15113 @item 
15114 @code{=all}: Emit all GNAT encodings, and then emit as much standard DWARF as
15115 possible so it does not conflict with GNAT encodings.
15117 @item 
15118 @code{=gdb}: Emit as much standard DWARF as possible as long as the current
15119 GDB handles it. Emit GNAT encodings for the rest.
15121 @item 
15122 @code{=minimal}: Emit as much standard DWARF as possible and emit GNAT
15123 encodings for the rest.
15124 @end itemize
15125 @end table
15127 @node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
15128 @anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{105}@anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{106}
15129 @subsection Exception Handling Control
15132 GNAT uses two methods for handling exceptions at run time. The
15133 @code{setjmp/longjmp} method saves the context when entering
15134 a frame with an exception handler. Then when an exception is
15135 raised, the context can be restored immediately, without the
15136 need for tracing stack frames. This method provides very fast
15137 exception propagation, but introduces significant overhead for
15138 the use of exception handlers, even if no exception is raised.
15140 The other approach is called ‘zero cost’ exception handling.
15141 With this method, the compiler builds static tables to describe
15142 the exception ranges. No dynamic code is required when entering
15143 a frame containing an exception handler. When an exception is
15144 raised, the tables are used to control a back trace of the
15145 subprogram invocation stack to locate the required exception
15146 handler. This method has considerably poorer performance for
15147 the propagation of exceptions, but there is no overhead for
15148 exception handlers if no exception is raised. Note that in this
15149 mode and in the context of mixed Ada and C/C++ programming,
15150 to propagate an exception through a C/C++ code, the C/C++ code
15151 must be compiled with the @code{-funwind-tables} GCC’s
15152 option.
15154 The following switches may be used to control which of the
15155 two exception handling methods is used.
15157 @geindex --RTS=sjlj (gnatmake)
15160 @table @asis
15162 @item @code{--RTS=sjlj}
15164 This switch causes the setjmp/longjmp run-time (when available) to be used
15165 for exception handling. If the default
15166 mechanism for the target is zero cost exceptions, then
15167 this switch can be used to modify this default, and must be
15168 used for all units in the partition.
15169 This option is rarely used. One case in which it may be
15170 advantageous is if you have an application where exception
15171 raising is common and the overall performance of the
15172 application is improved by favoring exception propagation.
15173 @end table
15175 @geindex --RTS=zcx (gnatmake)
15177 @geindex Zero Cost Exceptions
15180 @table @asis
15182 @item @code{--RTS=zcx}
15184 This switch causes the zero cost approach to be used
15185 for exception handling. If this is the default mechanism for the
15186 target (see below), then this switch is unneeded. If the default
15187 mechanism for the target is setjmp/longjmp exceptions, then
15188 this switch can be used to modify this default, and must be
15189 used for all units in the partition.
15190 This option can only be used if the zero cost approach
15191 is available for the target in use, otherwise it will generate an error.
15192 @end table
15194 The same option @code{--RTS} must be used both for @code{gcc}
15195 and @code{gnatbind}. Passing this option to @code{gnatmake}
15196 (@ref{ce,,Switches for gnatmake}) will ensure the required consistency
15197 through the compilation and binding steps.
15199 @node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
15200 @anchor{gnat_ugn/building_executable_programs_with_gnat id29}@anchor{107}@anchor{gnat_ugn/building_executable_programs_with_gnat units-to-sources-mapping-files}@anchor{e8}
15201 @subsection Units to Sources Mapping Files
15204 @geindex -gnatem (gcc)
15207 @table @asis
15209 @item @code{-gnatem=@emph{path}}
15211 A mapping file is a way to communicate to the compiler two mappings:
15212 from unit names to file names (without any directory information) and from
15213 file names to path names (with full directory information). These mappings
15214 are used by the compiler to short-circuit the path search.
15216 The use of mapping files is not required for correct operation of the
15217 compiler, but mapping files can improve efficiency, particularly when
15218 sources are read over a slow network connection. In normal operation,
15219 you need not be concerned with the format or use of mapping files,
15220 and the @code{-gnatem} switch is not a switch that you would use
15221 explicitly. It is intended primarily for use by automatic tools such as
15222 @code{gnatmake} running under the project file facility. The
15223 description here of the format of mapping files is provided
15224 for completeness and for possible use by other tools.
15226 A mapping file is a sequence of sets of three lines. In each set, the
15227 first line is the unit name, in lower case, with @code{%s} appended
15228 for specs and @code{%b} appended for bodies; the second line is the
15229 file name; and the third line is the path name.
15231 Example:
15233 @example
15234 main%b
15235 main.2.ada
15236 /gnat/project1/sources/main.2.ada
15237 @end example
15239 When the switch @code{-gnatem} is specified, the compiler will
15240 create in memory the two mappings from the specified file. If there is
15241 any problem (nonexistent file, truncated file or duplicate entries),
15242 no mapping will be created.
15244 Several @code{-gnatem} switches may be specified; however, only the
15245 last one on the command line will be taken into account.
15247 When using a project file, @code{gnatmake} creates a temporary
15248 mapping file and communicates it to the compiler using this switch.
15249 @end table
15251 @node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
15252 @anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{108}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{109}
15253 @subsection Code Generation Control
15256 The GCC technology provides a wide range of target dependent
15257 @code{-m} switches for controlling
15258 details of code generation with respect to different versions of
15259 architectures. This includes variations in instruction sets (e.g.,
15260 different members of the power pc family), and different requirements
15261 for optimal arrangement of instructions (e.g., different members of
15262 the x86 family). The list of available @code{-m} switches may be
15263 found in the GCC documentation.
15265 Use of these @code{-m} switches may in some cases result in improved
15266 code performance.
15268 The GNAT technology is tested and qualified without any
15269 @code{-m} switches,
15270 so generally the most reliable approach is to avoid the use of these
15271 switches. However, we generally expect most of these switches to work
15272 successfully with GNAT, and many customers have reported successful
15273 use of these options.
15275 Our general advice is to avoid the use of @code{-m} switches unless
15276 special needs lead to requirements in this area. In particular,
15277 there is no point in using @code{-m} switches to improve performance
15278 unless you actually see a performance improvement.
15280 @node Linker Switches,Binding with gnatbind,Compiler Switches,Building Executable Programs with GNAT
15281 @anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{10a}@anchor{gnat_ugn/building_executable_programs_with_gnat linker-switches}@anchor{10b}
15282 @section Linker Switches
15285 Linker switches can be specified after @code{-largs} builder switch.
15287 @geindex -fuse-ld=name
15290 @table @asis
15292 @item @code{-fuse-ld=@emph{name}}
15294 Linker to be used. The default is @code{bfd} for @code{ld.bfd},
15295 the alternative being @code{gold} for @code{ld.gold}. The later is
15296 a more recent and faster linker, but only available on GNU/Linux
15297 platforms.
15298 @end table
15300 @node Binding with gnatbind,Linking with gnatlink,Linker Switches,Building Executable Programs with GNAT
15301 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{c8}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{10c}
15302 @section Binding with @code{gnatbind}
15305 @geindex gnatbind
15307 This chapter describes the GNAT binder, @code{gnatbind}, which is used
15308 to bind compiled GNAT objects.
15310 The @code{gnatbind} program performs four separate functions:
15313 @itemize *
15315 @item 
15316 Checks that a program is consistent, in accordance with the rules in
15317 Chapter 10 of the Ada Reference Manual. In particular, error
15318 messages are generated if a program uses inconsistent versions of a
15319 given unit.
15321 @item 
15322 Checks that an acceptable order of elaboration exists for the program
15323 and issues an error message if it cannot find an order of elaboration
15324 that satisfies the rules in Chapter 10 of the Ada Language Manual.
15326 @item 
15327 Generates a main program incorporating the given elaboration order.
15328 This program is a small Ada package (body and spec) that
15329 must be subsequently compiled
15330 using the GNAT compiler. The necessary compilation step is usually
15331 performed automatically by @code{gnatlink}. The two most important
15332 functions of this program
15333 are to call the elaboration routines of units in an appropriate order
15334 and to call the main program.
15336 @item 
15337 Determines the set of object files required by the given main program.
15338 This information is output in the forms of comments in the generated program,
15339 to be read by the @code{gnatlink} utility used to link the Ada application.
15340 @end itemize
15342 @menu
15343 * Running gnatbind:: 
15344 * Switches for gnatbind:: 
15345 * Command-Line Access:: 
15346 * Search Paths for gnatbind:: 
15347 * Examples of gnatbind Usage:: 
15349 @end menu
15351 @node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
15352 @anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{10d}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{10e}
15353 @subsection Running @code{gnatbind}
15356 The form of the @code{gnatbind} command is
15358 @example
15359 $ gnatbind [ switches ] mainprog[.ali] [ switches ]
15360 @end example
15362 where @code{mainprog.adb} is the Ada file containing the main program
15363 unit body. @code{gnatbind} constructs an Ada
15364 package in two files whose names are
15365 @code{b~mainprog.ads}, and @code{b~mainprog.adb}.
15366 For example, if given the
15367 parameter @code{hello.ali}, for a main program contained in file
15368 @code{hello.adb}, the binder output files would be @code{b~hello.ads}
15369 and @code{b~hello.adb}.
15371 When doing consistency checking, the binder takes into consideration
15372 any source files it can locate. For example, if the binder determines
15373 that the given main program requires the package @code{Pack}, whose
15374 @code{.ALI}
15375 file is @code{pack.ali} and whose corresponding source spec file is
15376 @code{pack.ads}, it attempts to locate the source file @code{pack.ads}
15377 (using the same search path conventions as previously described for the
15378 @code{gcc} command). If it can locate this source file, it checks that
15379 the time stamps
15380 or source checksums of the source and its references to in @code{ALI} files
15381 match. In other words, any @code{ALI} files that mentions this spec must have
15382 resulted from compiling this version of the source file (or in the case
15383 where the source checksums match, a version close enough that the
15384 difference does not matter).
15386 @geindex Source files
15387 @geindex use by binder
15389 The effect of this consistency checking, which includes source files, is
15390 that the binder ensures that the program is consistent with the latest
15391 version of the source files that can be located at bind time. Editing a
15392 source file without compiling files that depend on the source file cause
15393 error messages to be generated by the binder.
15395 For example, suppose you have a main program @code{hello.adb} and a
15396 package @code{P}, from file @code{p.ads} and you perform the following
15397 steps:
15400 @itemize *
15402 @item 
15403 Enter @code{gcc -c hello.adb} to compile the main program.
15405 @item 
15406 Enter @code{gcc -c p.ads} to compile package @code{P}.
15408 @item 
15409 Edit file @code{p.ads}.
15411 @item 
15412 Enter @code{gnatbind hello}.
15413 @end itemize
15415 At this point, the file @code{p.ali} contains an out-of-date time stamp
15416 because the file @code{p.ads} has been edited. The attempt at binding
15417 fails, and the binder generates the following error messages:
15419 @example
15420 error: "hello.adb" must be recompiled ("p.ads" has been modified)
15421 error: "p.ads" has been modified and must be recompiled
15422 @end example
15424 Now both files must be recompiled as indicated, and then the bind can
15425 succeed, generating a main program. You need not normally be concerned
15426 with the contents of this file, but for reference purposes a sample
15427 binder output file is given in @ref{e,,Example of Binder Output File}.
15429 In most normal usage, the default mode of @code{gnatbind} which is to
15430 generate the main package in Ada, as described in the previous section.
15431 In particular, this means that any Ada programmer can read and understand
15432 the generated main program. It can also be debugged just like any other
15433 Ada code provided the @code{-g} switch is used for
15434 @code{gnatbind} and @code{gnatlink}.
15436 @node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
15437 @anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{10f}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{110}
15438 @subsection Switches for @code{gnatbind}
15441 The following switches are available with @code{gnatbind}; details will
15442 be presented in subsequent sections.
15444 @geindex --version (gnatbind)
15447 @table @asis
15449 @item @code{--version}
15451 Display Copyright and version, then exit disregarding all other options.
15452 @end table
15454 @geindex --help (gnatbind)
15457 @table @asis
15459 @item @code{--help}
15461 If @code{--version} was not used, display usage, then exit disregarding
15462 all other options.
15463 @end table
15465 @geindex -a (gnatbind)
15468 @table @asis
15470 @item @code{-a}
15472 Indicates that, if supported by the platform, the adainit procedure should
15473 be treated as an initialisation routine by the linker (a constructor). This
15474 is intended to be used by the Project Manager to automatically initialize
15475 shared Stand-Alone Libraries.
15476 @end table
15478 @geindex -aO (gnatbind)
15481 @table @asis
15483 @item @code{-aO}
15485 Specify directory to be searched for ALI files.
15486 @end table
15488 @geindex -aI (gnatbind)
15491 @table @asis
15493 @item @code{-aI}
15495 Specify directory to be searched for source file.
15496 @end table
15498 @geindex -A (gnatbind)
15501 @table @asis
15503 @item @code{-A[=@emph{filename}]}
15505 Output ALI list (to standard output or to the named file).
15506 @end table
15508 @geindex -b (gnatbind)
15511 @table @asis
15513 @item @code{-b}
15515 Generate brief messages to @code{stderr} even if verbose mode set.
15516 @end table
15518 @geindex -c (gnatbind)
15521 @table @asis
15523 @item @code{-c}
15525 Check only, no generation of binder output file.
15526 @end table
15528 @geindex -dnn[k|m] (gnatbind)
15531 @table @asis
15533 @item @code{-d@emph{nn}[k|m]}
15535 This switch can be used to change the default task stack size value
15536 to a specified size @code{nn}, which is expressed in bytes by default, or
15537 in kilobytes when suffixed with @code{k} or in megabytes when suffixed
15538 with @code{m}.
15539 In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15540 in effect, to completing all task specs with
15542 @example
15543 pragma Storage_Size (nn);
15544 @end example
15546 When they do not already have such a pragma.
15547 @end table
15549 @geindex -D (gnatbind)
15552 @table @asis
15554 @item @code{-D@emph{nn}[k|m]}
15556 Set the default secondary stack size to @code{nn}. The suffix indicates whether
15557 the size is in bytes (no suffix), kilobytes (@code{k} suffix) or megabytes
15558 (@code{m} suffix).
15560 The secondary stack holds objects of unconstrained types that are returned by
15561 functions, for example unconstrained Strings. The size of the secondary stack
15562 can be dynamic or fixed depending on the target.
15564 For most targets, the secondary stack grows on demand and is implemented as
15565 a chain of blocks in the heap. In this case, the default secondary stack size
15566 determines the initial size of the secondary stack for each task and the
15567 smallest amount the secondary stack can grow by.
15569 For Ravenscar, ZFP, and Cert run-times the size of the secondary stack is
15570 fixed. This switch can be used to change the default size of these stacks.
15571 The default secondary stack size can be overridden on a per-task basis if
15572 individual tasks have different secondary stack requirements. This is
15573 achieved through the Secondary_Stack_Size aspect that takes the size of the
15574 secondary stack in bytes.
15575 @end table
15577 @geindex -e (gnatbind)
15580 @table @asis
15582 @item @code{-e}
15584 Output complete list of elaboration-order dependencies.
15585 @end table
15587 @geindex -Ea (gnatbind)
15590 @table @asis
15592 @item @code{-Ea}
15594 Store tracebacks in exception occurrences when the target supports it.
15595 The “a” is for “address”; tracebacks will contain hexadecimal addresses,
15596 unless symbolic tracebacks are enabled.
15598 See also the packages @code{GNAT.Traceback} and
15599 @code{GNAT.Traceback.Symbolic} for more information.
15600 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
15601 @code{gcc} option.
15602 @end table
15604 @geindex -Es (gnatbind)
15607 @table @asis
15609 @item @code{-Es}
15611 Store tracebacks in exception occurrences when the target supports it.
15612 The “s” is for “symbolic”; symbolic tracebacks are enabled.
15613 @end table
15615 @geindex -E (gnatbind)
15618 @table @asis
15620 @item @code{-E}
15622 Currently the same as @code{-Ea}.
15623 @end table
15625 @geindex -f (gnatbind)
15628 @table @asis
15630 @item @code{-f@emph{elab-order}}
15632 Force elaboration order. For further details see @ref{111,,Elaboration Control}
15633 and @ref{f,,Elaboration Order Handling in GNAT}.
15634 @end table
15636 @geindex -F (gnatbind)
15639 @table @asis
15641 @item @code{-F}
15643 Force the checks of elaboration flags. @code{gnatbind} does not normally
15644 generate checks of elaboration flags for the main executable, except when
15645 a Stand-Alone Library is used. However, there are cases when this cannot be
15646 detected by gnatbind. An example is importing an interface of a Stand-Alone
15647 Library through a pragma Import and only specifying through a linker switch
15648 this Stand-Alone Library. This switch is used to guarantee that elaboration
15649 flag checks are generated.
15650 @end table
15652 @geindex -h (gnatbind)
15655 @table @asis
15657 @item @code{-h}
15659 Output usage (help) information.
15660 @end table
15662 @geindex -H (gnatbind)
15665 @table @asis
15667 @item @code{-H}
15669 Legacy elaboration order model enabled. For further details see
15670 @ref{f,,Elaboration Order Handling in GNAT}.
15671 @end table
15673 @geindex -H32 (gnatbind)
15676 @table @asis
15678 @item @code{-H32}
15680 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
15681 For further details see @ref{112,,Dynamic Allocation Control}.
15682 @end table
15684 @geindex -H64 (gnatbind)
15686 @geindex __gnat_malloc
15689 @table @asis
15691 @item @code{-H64}
15693 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
15694 For further details see @ref{112,,Dynamic Allocation Control}.
15696 @geindex -I (gnatbind)
15698 @item @code{-I}
15700 Specify directory to be searched for source and ALI files.
15702 @geindex -I- (gnatbind)
15704 @item @code{-I-}
15706 Do not look for sources in the current directory where @code{gnatbind} was
15707 invoked, and do not look for ALI files in the directory containing the
15708 ALI file named in the @code{gnatbind} command line.
15710 @geindex -l (gnatbind)
15712 @item @code{-l}
15714 Output chosen elaboration order.
15716 @geindex -L (gnatbind)
15718 @item @code{-L@emph{xxx}}
15720 Bind the units for library building. In this case the @code{adainit} and
15721 @code{adafinal} procedures (@ref{a0,,Binding with Non-Ada Main Programs})
15722 are renamed to @code{@emph{xxx}init} and
15723 @code{@emph{xxx}final}.
15724 Implies -n.
15725 (@ref{2a,,GNAT and Libraries}, for more details.)
15727 @geindex -M (gnatbind)
15729 @item @code{-M@emph{xyz}}
15731 Rename generated main program from main to xyz. This option is
15732 supported on cross environments only.
15734 @geindex -m (gnatbind)
15736 @item @code{-m@emph{n}}
15738 Limit number of detected errors or warnings to @code{n}, where @code{n} is
15739 in the range 1..999999. The default value if no switch is
15740 given is 9999. If the number of warnings reaches this limit, then a
15741 message is output and further warnings are suppressed, the bind
15742 continues in this case. If the number of errors reaches this
15743 limit, then a message is output and the bind is abandoned.
15744 A value of zero means that no limit is enforced. The equal
15745 sign is optional.
15747 @geindex -minimal (gnatbind)
15749 @item @code{-minimal}
15751 Generate a binder file suitable for space-constrained applications. When
15752 active, binder-generated objects not required for program operation are no
15753 longer generated. @strong{Warning:} this option comes with the following
15754 limitations:
15757 @itemize *
15759 @item 
15760 Starting the program’s execution in the debugger will cause it to
15761 stop at the start of the @code{main} function instead of the main subprogram.
15762 This can be worked around by manually inserting a breakpoint on that
15763 subprogram and resuming the program’s execution until reaching that breakpoint.
15765 @item 
15766 Programs using GNAT.Compiler_Version will not link.
15767 @end itemize
15769 @geindex -n (gnatbind)
15771 @item @code{-n}
15773 No main program.
15775 @geindex -nostdinc (gnatbind)
15777 @item @code{-nostdinc}
15779 Do not look for sources in the system default directory.
15781 @geindex -nostdlib (gnatbind)
15783 @item @code{-nostdlib}
15785 Do not look for library files in the system default directory.
15787 @geindex --RTS (gnatbind)
15789 @item @code{--RTS=@emph{rts-path}}
15791 Specifies the default location of the run-time library. Same meaning as the
15792 equivalent @code{gnatmake} flag (@ref{ce,,Switches for gnatmake}).
15794 @geindex -o (gnatbind)
15796 @item @code{-o @emph{file}}
15798 Name the output file @code{file} (default is @code{b~`xxx}.adb`).
15799 Note that if this option is used, then linking must be done manually,
15800 gnatlink cannot be used.
15802 @geindex -O (gnatbind)
15804 @item @code{-O[=@emph{filename}]}
15806 Output object list (to standard output or to the named file).
15808 @geindex -p (gnatbind)
15810 @item @code{-p}
15812 Pessimistic (worst-case) elaboration order.
15814 @geindex -P (gnatbind)
15816 @item @code{-P}
15818 Generate binder file suitable for CodePeer.
15820 @geindex -R (gnatbind)
15822 @item @code{-R}
15824 Output closure source list, which includes all non-run-time units that are
15825 included in the bind.
15827 @geindex -Ra (gnatbind)
15829 @item @code{-Ra}
15831 Like @code{-R} but the list includes run-time units.
15833 @geindex -s (gnatbind)
15835 @item @code{-s}
15837 Require all source files to be present.
15839 @geindex -S (gnatbind)
15841 @item @code{-S@emph{xxx}}
15843 Specifies the value to be used when detecting uninitialized scalar
15844 objects with pragma Initialize_Scalars.
15845 The @code{xxx} string specified with the switch is one of:
15848 @itemize *
15850 @item 
15851 @code{in} for an invalid value.
15853 If zero is invalid for the discrete type in question,
15854 then the scalar value is set to all zero bits.
15855 For signed discrete types, the largest possible negative value of
15856 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15857 For unsigned discrete types, the underlying scalar value is set to all
15858 one bits. For floating-point types, a NaN value is set
15859 (see body of package System.Scalar_Values for exact values).
15861 @item 
15862 @code{lo} for low value.
15864 If zero is invalid for the discrete type in question,
15865 then the scalar value is set to all zero bits.
15866 For signed discrete types, the largest possible negative value of
15867 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15868 For unsigned discrete types, the underlying scalar value is set to all
15869 zero bits. For floating-point, a small value is set
15870 (see body of package System.Scalar_Values for exact values).
15872 @item 
15873 @code{hi} for high value.
15875 If zero is invalid for the discrete type in question,
15876 then the scalar value is set to all one bits.
15877 For signed discrete types, the largest possible positive value of
15878 the underlying scalar is set (i.e. a zero bit followed by all one bits).
15879 For unsigned discrete types, the underlying scalar value is set to all
15880 one bits. For floating-point, a large value is set
15881 (see body of package System.Scalar_Values for exact values).
15883 @item 
15884 @code{xx} for hex value (two hex digits).
15886 The underlying scalar is set to a value consisting of repeated bytes, whose
15887 value corresponds to the given value. For example if @code{BF} is given,
15888 then a 32-bit scalar value will be set to the bit patterm @code{16#BFBFBFBF#}.
15889 @end itemize
15891 @geindex GNAT_INIT_SCALARS
15893 In addition, you can specify @code{-Sev} to indicate that the value is
15894 to be set at run time. In this case, the program will look for an environment
15895 variable of the form @code{GNAT_INIT_SCALARS=@emph{yy}}, where @code{yy} is one
15896 of @code{in/lo/hi/@emph{xx}} with the same meanings as above.
15897 If no environment variable is found, or if it does not have a valid value,
15898 then the default is @code{in} (invalid values).
15899 @end table
15901 @geindex -static (gnatbind)
15904 @table @asis
15906 @item @code{-static}
15908 Link against a static GNAT run-time.
15910 @geindex -shared (gnatbind)
15912 @item @code{-shared}
15914 Link against a shared GNAT run-time when available.
15916 @geindex -t (gnatbind)
15918 @item @code{-t}
15920 Tolerate time stamp and other consistency errors.
15922 @geindex -T (gnatbind)
15924 @item @code{-T@emph{n}}
15926 Set the time slice value to @code{n} milliseconds. If the system supports
15927 the specification of a specific time slice value, then the indicated value
15928 is used. If the system does not support specific time slice values, but
15929 does support some general notion of round-robin scheduling, then any
15930 nonzero value will activate round-robin scheduling.
15932 A value of zero is treated specially. It turns off time
15933 slicing, and in addition, indicates to the tasking run-time that the
15934 semantics should match as closely as possible the Annex D
15935 requirements of the Ada RM, and in particular sets the default
15936 scheduling policy to @code{FIFO_Within_Priorities}.
15938 @geindex -u (gnatbind)
15940 @item @code{-u@emph{n}}
15942 Enable dynamic stack usage, with @code{n} results stored and displayed
15943 at program termination. A result is generated when a task
15944 terminates. Results that can’t be stored are displayed on the fly, at
15945 task termination. This option is currently not supported on Itanium
15946 platforms. (See @ref{113,,Dynamic Stack Usage Analysis} for details.)
15948 @geindex -v (gnatbind)
15950 @item @code{-v}
15952 Verbose mode. Write error messages, header, summary output to
15953 @code{stdout}.
15955 @geindex -V (gnatbind)
15957 @item @code{-V@emph{key}=@emph{value}}
15959 Store the given association of @code{key} to @code{value} in the bind environment.
15960 Values stored this way can be retrieved at run time using
15961 @code{GNAT.Bind_Environment}.
15963 @geindex -w (gnatbind)
15965 @item @code{-w@emph{x}}
15967 Warning mode; @code{x} = s/e for suppress/treat as error.
15969 @geindex -Wx (gnatbind)
15971 @item @code{-Wx@emph{e}}
15973 Override default wide character encoding for standard Text_IO files.
15975 @geindex -x (gnatbind)
15977 @item @code{-x}
15979 Exclude source files (check object consistency only).
15981 @geindex -xdr (gnatbind)
15983 @item @code{-xdr}
15985 Use the target-independent XDR protocol for stream oriented attributes
15986 instead of the default implementation which is based on direct binary
15987 representations and is therefore target-and endianness-dependent.
15988 However it does not support 128-bit integer types and the exception
15989 @code{Ada.IO_Exceptions.Device_Error} is raised if any attempt is made
15990 at streaming 128-bit integer types with it.
15992 @geindex -Xnnn (gnatbind)
15994 @item @code{-X@emph{nnn}}
15996 Set default exit status value, normally 0 for POSIX compliance.
15998 @geindex -y (gnatbind)
16000 @item @code{-y}
16002 Enable leap seconds support in @code{Ada.Calendar} and its children.
16004 @geindex -z (gnatbind)
16006 @item @code{-z}
16008 No main subprogram.
16009 @end table
16011 You may obtain this listing of switches by running @code{gnatbind} with
16012 no arguments.
16014 @menu
16015 * Consistency-Checking Modes:: 
16016 * Binder Error Message Control:: 
16017 * Elaboration Control:: 
16018 * Output Control:: 
16019 * Dynamic Allocation Control:: 
16020 * Binding with Non-Ada Main Programs:: 
16021 * Binding Programs with No Main Subprogram:: 
16023 @end menu
16025 @node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
16026 @anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{114}@anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{115}
16027 @subsubsection Consistency-Checking Modes
16030 As described earlier, by default @code{gnatbind} checks
16031 that object files are consistent with one another and are consistent
16032 with any source files it can locate. The following switches control binder
16033 access to sources.
16035 @quotation
16037 @geindex -s (gnatbind)
16038 @end quotation
16041 @table @asis
16043 @item @code{-s}
16045 Require source files to be present. In this mode, the binder must be
16046 able to locate all source files that are referenced, in order to check
16047 their consistency. In normal mode, if a source file cannot be located it
16048 is simply ignored. If you specify this switch, a missing source
16049 file is an error.
16051 @geindex -Wx (gnatbind)
16053 @item @code{-Wx@emph{e}}
16055 Override default wide character encoding for standard Text_IO files.
16056 Normally the default wide character encoding method used for standard
16057 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
16058 the main source input (see description of switch
16059 @code{-gnatWx} for the compiler). The
16060 use of this switch for the binder (which has the same set of
16061 possible arguments) overrides this default as specified.
16063 @geindex -x (gnatbind)
16065 @item @code{-x}
16067 Exclude source files. In this mode, the binder only checks that ALI
16068 files are consistent with one another. Source files are not accessed.
16069 The binder runs faster in this mode, and there is still a guarantee that
16070 the resulting program is self-consistent.
16071 If a source file has been edited since it was last compiled, and you
16072 specify this switch, the binder will not detect that the object
16073 file is out of date with respect to the source file. Note that this is the
16074 mode that is automatically used by @code{gnatmake} because in this
16075 case the checking against sources has already been performed by
16076 @code{gnatmake} in the course of compilation (i.e., before binding).
16077 @end table
16079 @node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
16080 @anchor{gnat_ugn/building_executable_programs_with_gnat binder-error-message-control}@anchor{116}@anchor{gnat_ugn/building_executable_programs_with_gnat id36}@anchor{117}
16081 @subsubsection Binder Error Message Control
16084 The following switches provide control over the generation of error
16085 messages from the binder:
16087 @quotation
16089 @geindex -v (gnatbind)
16090 @end quotation
16093 @table @asis
16095 @item @code{-v}
16097 Verbose mode. In the normal mode, brief error messages are generated to
16098 @code{stderr}. If this switch is present, a header is written
16099 to @code{stdout} and any error messages are directed to @code{stdout}.
16100 All that is written to @code{stderr} is a brief summary message.
16102 @geindex -b (gnatbind)
16104 @item @code{-b}
16106 Generate brief error messages to @code{stderr} even if verbose mode is
16107 specified. This is relevant only when used with the
16108 @code{-v} switch.
16110 @geindex -m (gnatbind)
16112 @item @code{-m@emph{n}}
16114 Limits the number of error messages to @code{n}, a decimal integer in the
16115 range 1-999. The binder terminates immediately if this limit is reached.
16117 @geindex -M (gnatbind)
16119 @item @code{-M@emph{xxx}}
16121 Renames the generated main program from @code{main} to @code{xxx}.
16122 This is useful in the case of some cross-building environments, where
16123 the actual main program is separate from the one generated
16124 by @code{gnatbind}.
16126 @geindex -ws (gnatbind)
16128 @geindex Warnings
16130 @item @code{-ws}
16132 Suppress all warning messages.
16134 @geindex -we (gnatbind)
16136 @item @code{-we}
16138 Treat any warning messages as fatal errors.
16140 @geindex -t (gnatbind)
16142 @geindex Time stamp checks
16143 @geindex in binder
16145 @geindex Binder consistency checks
16147 @geindex Consistency checks
16148 @geindex in binder
16150 @item @code{-t}
16152 The binder performs a number of consistency checks including:
16155 @itemize *
16157 @item 
16158 Check that time stamps of a given source unit are consistent
16160 @item 
16161 Check that checksums of a given source unit are consistent
16163 @item 
16164 Check that consistent versions of @code{GNAT} were used for compilation
16166 @item 
16167 Check consistency of configuration pragmas as required
16168 @end itemize
16170 Normally failure of such checks, in accordance with the consistency
16171 requirements of the Ada Reference Manual, causes error messages to be
16172 generated which abort the binder and prevent the output of a binder
16173 file and subsequent link to obtain an executable.
16175 The @code{-t} switch converts these error messages
16176 into warnings, so that
16177 binding and linking can continue to completion even in the presence of such
16178 errors. The result may be a failed link (due to missing symbols), or a
16179 non-functional executable which has undefined semantics.
16181 @cartouche
16182 @quotation Note 
16183 This means that @code{-t} should be used only in unusual situations,
16184 with extreme care.
16185 @end quotation
16186 @end cartouche
16187 @end table
16189 @node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
16190 @anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{111}@anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{118}
16191 @subsubsection Elaboration Control
16194 The following switches provide additional control over the elaboration
16195 order. For further details see @ref{f,,Elaboration Order Handling in GNAT}.
16197 @geindex -f (gnatbind)
16200 @table @asis
16202 @item @code{-f@emph{elab-order}}
16204 Force elaboration order.
16206 @code{elab-order} should be the name of a “forced elaboration order file”, that
16207 is, a text file containing library item names, one per line. A name of the
16208 form “some.unit%s” or “some.unit (spec)” denotes the spec of Some.Unit. A
16209 name of the form “some.unit%b” or “some.unit (body)” denotes the body of
16210 Some.Unit. Each pair of lines is taken to mean that there is an elaboration
16211 dependence of the second line on the first. For example, if the file
16212 contains:
16214 @example
16215 this (spec)
16216 this (body)
16217 that (spec)
16218 that (body)
16219 @end example
16221 then the spec of This will be elaborated before the body of This, and the
16222 body of This will be elaborated before the spec of That, and the spec of That
16223 will be elaborated before the body of That. The first and last of these three
16224 dependences are already required by Ada rules, so this file is really just
16225 forcing the body of This to be elaborated before the spec of That.
16227 The given order must be consistent with Ada rules, or else @code{gnatbind} will
16228 give elaboration cycle errors. For example, if you say x (body) should be
16229 elaborated before x (spec), there will be a cycle, because Ada rules require
16230 x (spec) to be elaborated before x (body); you can’t have the spec and body
16231 both elaborated before each other.
16233 If you later add “with That;” to the body of This, there will be a cycle, in
16234 which case you should erase either “this (body)” or “that (spec)” from the
16235 above forced elaboration order file.
16237 Blank lines and Ada-style comments are ignored. Unit names that do not exist
16238 in the program are ignored. Units in the GNAT predefined library are also
16239 ignored.
16240 @end table
16242 @geindex -p (gnatbind)
16245 @table @asis
16247 @item @code{-p}
16249 Pessimistic elaboration order
16251 This switch is only applicable to the pre-20.x legacy elaboration models.
16252 The post-20.x elaboration model uses a more informed approach of ordering
16253 the units.
16255 Normally the binder attempts to choose an elaboration order that is likely to
16256 minimize the likelihood of an elaboration order error resulting in raising a
16257 @code{Program_Error} exception. This switch reverses the action of the binder,
16258 and requests that it deliberately choose an order that is likely to maximize
16259 the likelihood of an elaboration error. This is useful in ensuring
16260 portability and avoiding dependence on accidental fortuitous elaboration
16261 ordering.
16263 Normally it only makes sense to use the @code{-p} switch if dynamic
16264 elaboration checking is used (@code{-gnatE} switch used for compilation).
16265 This is because in the default static elaboration mode, all necessary
16266 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
16267 These implicit pragmas are still respected by the binder in @code{-p}
16268 mode, so a safe elaboration order is assured.
16270 Note that @code{-p} is not intended for production use; it is more for
16271 debugging/experimental use.
16272 @end table
16274 @node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
16275 @anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{119}@anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{11a}
16276 @subsubsection Output Control
16279 The following switches allow additional control over the output
16280 generated by the binder.
16282 @quotation
16284 @geindex -c (gnatbind)
16285 @end quotation
16288 @table @asis
16290 @item @code{-c}
16292 Check only. Do not generate the binder output file. In this mode the
16293 binder performs all error checks but does not generate an output file.
16295 @geindex -e (gnatbind)
16297 @item @code{-e}
16299 Output complete list of elaboration-order dependencies, showing the
16300 reason for each dependency. This output can be rather extensive but may
16301 be useful in diagnosing problems with elaboration order. The output is
16302 written to @code{stdout}.
16304 @geindex -h (gnatbind)
16306 @item @code{-h}
16308 Output usage information. The output is written to @code{stdout}.
16310 @geindex -K (gnatbind)
16312 @item @code{-K}
16314 Output linker options to @code{stdout}. Includes library search paths,
16315 contents of pragmas Ident and Linker_Options, and libraries added
16316 by @code{gnatbind}.
16318 @geindex -l (gnatbind)
16320 @item @code{-l}
16322 Output chosen elaboration order. The output is written to @code{stdout}.
16324 @geindex -O (gnatbind)
16326 @item @code{-O}
16328 Output full names of all the object files that must be linked to provide
16329 the Ada component of the program. The output is written to @code{stdout}.
16330 This list includes the files explicitly supplied and referenced by the user
16331 as well as implicitly referenced run-time unit files. The latter are
16332 omitted if the corresponding units reside in shared libraries. The
16333 directory names for the run-time units depend on the system configuration.
16335 @geindex -o (gnatbind)
16337 @item @code{-o @emph{file}}
16339 Set name of output file to @code{file} instead of the normal
16340 @code{b~`mainprog}.adb` default. Note that @code{file} denote the Ada
16341 binder generated body filename.
16342 Note that if this option is used, then linking must be done manually.
16343 It is not possible to use gnatlink in this case, since it cannot locate
16344 the binder file.
16346 @geindex -r (gnatbind)
16348 @item @code{-r}
16350 Generate list of @code{pragma Restrictions} that could be applied to
16351 the current unit. This is useful for code audit purposes, and also may
16352 be used to improve code generation in some cases.
16353 @end table
16355 @node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
16356 @anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{112}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{11b}
16357 @subsubsection Dynamic Allocation Control
16360 The heap control switches – @code{-H32} and @code{-H64} –
16361 determine whether dynamic allocation uses 32-bit or 64-bit memory.
16362 They only affect compiler-generated allocations via @code{__gnat_malloc};
16363 explicit calls to @code{malloc} and related functions from the C
16364 run-time library are unaffected.
16367 @table @asis
16369 @item @code{-H32}
16371 Allocate memory on 32-bit heap
16373 @item @code{-H64}
16375 Allocate memory on 64-bit heap.  This is the default
16376 unless explicitly overridden by a @code{'Size} clause on the access type.
16377 @end table
16379 These switches are only effective on VMS platforms.
16381 @node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
16382 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-non-ada-main-programs}@anchor{a0}@anchor{gnat_ugn/building_executable_programs_with_gnat id40}@anchor{11c}
16383 @subsubsection Binding with Non-Ada Main Programs
16386 The description so far has assumed that the main
16387 program is in Ada, and that the task of the binder is to generate a
16388 corresponding function @code{main} that invokes this Ada main
16389 program. GNAT also supports the building of executable programs where
16390 the main program is not in Ada, but some of the called routines are
16391 written in Ada and compiled using GNAT (@ref{2c,,Mixed Language Programming}).
16392 The following switch is used in this situation:
16394 @quotation
16396 @geindex -n (gnatbind)
16397 @end quotation
16400 @table @asis
16402 @item @code{-n}
16404 No main program. The main program is not in Ada.
16405 @end table
16407 In this case, most of the functions of the binder are still required,
16408 but instead of generating a main program, the binder generates a file
16409 containing the following callable routines:
16411 @quotation
16413 @geindex adainit
16416 @table @asis
16418 @item @code{adainit}
16420 You must call this routine to initialize the Ada part of the program by
16421 calling the necessary elaboration routines. A call to @code{adainit} is
16422 required before the first call to an Ada subprogram.
16424 Note that it is assumed that the basic execution environment must be setup
16425 to be appropriate for Ada execution at the point where the first Ada
16426 subprogram is called. In particular, if the Ada code will do any
16427 floating-point operations, then the FPU must be setup in an appropriate
16428 manner. For the case of the x86, for example, full precision mode is
16429 required. The procedure GNAT.Float_Control.Reset may be used to ensure
16430 that the FPU is in the right state.
16431 @end table
16433 @geindex adafinal
16436 @table @asis
16438 @item @code{adafinal}
16440 You must call this routine to perform any library-level finalization
16441 required by the Ada subprograms. A call to @code{adafinal} is required
16442 after the last call to an Ada subprogram, and before the program
16443 terminates.
16444 @end table
16445 @end quotation
16447 @geindex -n (gnatbind)
16449 @geindex Binder
16450 @geindex multiple input files
16452 If the @code{-n} switch
16453 is given, more than one ALI file may appear on
16454 the command line for @code{gnatbind}. The normal @code{closure}
16455 calculation is performed for each of the specified units. Calculating
16456 the closure means finding out the set of units involved by tracing
16457 @emph{with} references. The reason it is necessary to be able to
16458 specify more than one ALI file is that a given program may invoke two or
16459 more quite separate groups of Ada units.
16461 The binder takes the name of its output file from the last specified ALI
16462 file, unless overridden by the use of the @code{-o file}.
16464 @geindex -o (gnatbind)
16466 The output is an Ada unit in source form that can be compiled with GNAT.
16467 This compilation occurs automatically as part of the @code{gnatlink}
16468 processing.
16470 Currently the GNAT run-time requires a FPU using 80 bits mode
16471 precision. Under targets where this is not the default it is required to
16472 call GNAT.Float_Control.Reset before using floating point numbers (this
16473 include float computation, float input and output) in the Ada code. A
16474 side effect is that this could be the wrong mode for the foreign code
16475 where floating point computation could be broken after this call.
16477 @node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
16478 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-programs-with-no-main-subprogram}@anchor{11d}@anchor{gnat_ugn/building_executable_programs_with_gnat id41}@anchor{11e}
16479 @subsubsection Binding Programs with No Main Subprogram
16482 It is possible to have an Ada program which does not have a main
16483 subprogram. This program will call the elaboration routines of all the
16484 packages, then the finalization routines.
16486 The following switch is used to bind programs organized in this manner:
16488 @quotation
16490 @geindex -z (gnatbind)
16491 @end quotation
16494 @table @asis
16496 @item @code{-z}
16498 Normally the binder checks that the unit name given on the command line
16499 corresponds to a suitable main subprogram. When this switch is used,
16500 a list of ALI files can be given, and the execution of the program
16501 consists of elaboration of these units in an appropriate order. Note
16502 that the default wide character encoding method for standard Text_IO
16503 files is always set to Brackets if this switch is set (you can use
16504 the binder switch
16505 @code{-Wx} to override this default).
16506 @end table
16508 @node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
16509 @anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{11f}@anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{120}
16510 @subsection Command-Line Access
16513 The package @code{Ada.Command_Line} provides access to the command-line
16514 arguments and program name. In order for this interface to operate
16515 correctly, the two variables
16517 @example
16518 int gnat_argc;
16519 char **gnat_argv;
16520 @end example
16522 @geindex gnat_argv
16524 @geindex gnat_argc
16526 are declared in one of the GNAT library routines. These variables must
16527 be set from the actual @code{argc} and @code{argv} values passed to the
16528 main program. With no @emph{n} present, @code{gnatbind}
16529 generates the C main program to automatically set these variables.
16530 If the @emph{n} switch is used, there is no automatic way to
16531 set these variables. If they are not set, the procedures in
16532 @code{Ada.Command_Line} will not be available, and any attempt to use
16533 them will raise @code{Constraint_Error}. If command line access is
16534 required, your main program must set @code{gnat_argc} and
16535 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
16538 @node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
16539 @anchor{gnat_ugn/building_executable_programs_with_gnat id43}@anchor{121}@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-for-gnatbind}@anchor{76}
16540 @subsection Search Paths for @code{gnatbind}
16543 The binder takes the name of an ALI file as its argument and needs to
16544 locate source files as well as other ALI files to verify object consistency.
16546 For source files, it follows exactly the same search rules as @code{gcc}
16547 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
16548 directories searched are:
16551 @itemize *
16553 @item 
16554 The directory containing the ALI file named in the command line, unless
16555 the switch @code{-I-} is specified.
16557 @item 
16558 All directories specified by @code{-I}
16559 switches on the @code{gnatbind}
16560 command line, in the order given.
16562 @geindex ADA_PRJ_OBJECTS_FILE
16564 @item 
16565 Each of the directories listed in the text file whose name is given
16566 by the 
16567 @geindex ADA_PRJ_OBJECTS_FILE
16568 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16569 @code{ADA_PRJ_OBJECTS_FILE} environment variable.
16571 @geindex ADA_PRJ_OBJECTS_FILE
16572 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16573 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
16574 driver when project files are used. It should not normally be set
16575 by other means.
16577 @geindex ADA_OBJECTS_PATH
16579 @item 
16580 Each of the directories listed in the value of the
16581 @geindex ADA_OBJECTS_PATH
16582 @geindex environment variable; ADA_OBJECTS_PATH
16583 @code{ADA_OBJECTS_PATH} environment variable.
16584 Construct this value
16585 exactly as the 
16586 @geindex PATH
16587 @geindex environment variable; PATH
16588 @code{PATH} environment variable: a list of directory
16589 names separated by colons (semicolons when working with the NT version
16590 of GNAT).
16592 @item 
16593 The content of the @code{ada_object_path} file which is part of the GNAT
16594 installation tree and is used to store standard libraries such as the
16595 GNAT Run-Time Library (RTL) unless the switch @code{-nostdlib} is
16596 specified. See @ref{72,,Installing a library}
16597 @end itemize
16599 @geindex -I (gnatbind)
16601 @geindex -aI (gnatbind)
16603 @geindex -aO (gnatbind)
16605 In the binder the switch @code{-I}
16606 is used to specify both source and
16607 library file paths. Use @code{-aI}
16608 instead if you want to specify
16609 source paths only, and @code{-aO}
16610 if you want to specify library paths
16611 only. This means that for the binder
16612 @code{-I@emph{dir}} is equivalent to
16613 @code{-aI@emph{dir}}
16614 @code{-aO`@emph{dir}}.
16615 The binder generates the bind file (a C language source file) in the
16616 current working directory.
16618 @geindex Ada
16620 @geindex System
16622 @geindex Interfaces
16624 @geindex GNAT
16626 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
16627 children make up the GNAT Run-Time Library, together with the package
16628 GNAT and its children, which contain a set of useful additional
16629 library functions provided by GNAT. The sources for these units are
16630 needed by the compiler and are kept together in one directory. The ALI
16631 files and object files generated by compiling the RTL are needed by the
16632 binder and the linker and are kept together in one directory, typically
16633 different from the directory containing the sources. In a normal
16634 installation, you need not specify these directory names when compiling
16635 or binding. Either the environment variables or the built-in defaults
16636 cause these files to be found.
16638 Besides simplifying access to the RTL, a major use of search paths is
16639 in compiling sources from multiple directories. This can make
16640 development environments much more flexible.
16642 @node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16643 @anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatbind-usage}@anchor{122}@anchor{gnat_ugn/building_executable_programs_with_gnat id44}@anchor{123}
16644 @subsection Examples of @code{gnatbind} Usage
16647 Here are some examples of @code{gnatbind} invovations:
16649 @quotation
16651 @example
16652 gnatbind hello
16653 @end example
16655 The main program @code{Hello} (source program in @code{hello.adb}) is
16656 bound using the standard switch settings. The generated main program is
16657 @code{b~hello.adb}. This is the normal, default use of the binder.
16659 @example
16660 gnatbind hello -o mainprog.adb
16661 @end example
16663 The main program @code{Hello} (source program in @code{hello.adb}) is
16664 bound using the standard switch settings. The generated main program is
16665 @code{mainprog.adb} with the associated spec in
16666 @code{mainprog.ads}. Note that you must specify the body here not the
16667 spec. Note that if this option is used, then linking must be done manually,
16668 since gnatlink will not be able to find the generated file.
16669 @end quotation
16671 @node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16672 @anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{124}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{c9}
16673 @section Linking with @code{gnatlink}
16676 @geindex gnatlink
16678 This chapter discusses @code{gnatlink}, a tool that links
16679 an Ada program and builds an executable file. This utility
16680 invokes the system linker (via the @code{gcc} command)
16681 with a correct list of object files and library references.
16682 @code{gnatlink} automatically determines the list of files and
16683 references for the Ada part of a program. It uses the binder file
16684 generated by the @code{gnatbind} to determine this list.
16686 @menu
16687 * Running gnatlink:: 
16688 * Switches for gnatlink:: 
16690 @end menu
16692 @node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16693 @anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{125}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{126}
16694 @subsection Running @code{gnatlink}
16697 The form of the @code{gnatlink} command is
16699 @example
16700 $ gnatlink [ switches ] mainprog [.ali]
16701            [ non-Ada objects ] [ linker options ]
16702 @end example
16704 The arguments of @code{gnatlink} (switches, main @code{ALI} file,
16705 non-Ada objects
16706 or linker options) may be in any order, provided that no non-Ada object may
16707 be mistaken for a main @code{ALI} file.
16708 Any file name @code{F} without the @code{.ali}
16709 extension will be taken as the main @code{ALI} file if a file exists
16710 whose name is the concatenation of @code{F} and @code{.ali}.
16712 @code{mainprog.ali} references the ALI file of the main program.
16713 The @code{.ali} extension of this file can be omitted. From this
16714 reference, @code{gnatlink} locates the corresponding binder file
16715 @code{b~mainprog.adb} and, using the information in this file along
16716 with the list of non-Ada objects and linker options, constructs a
16717 linker command file to create the executable.
16719 The arguments other than the @code{gnatlink} switches and the main
16720 @code{ALI} file are passed to the linker uninterpreted.
16721 They typically include the names of
16722 object files for units written in other languages than Ada and any library
16723 references required to resolve references in any of these foreign language
16724 units, or in @code{Import} pragmas in any Ada units.
16726 @code{linker options} is an optional list of linker specific
16727 switches.
16728 The default linker called by gnatlink is @code{gcc} which in
16729 turn calls the appropriate system linker.
16731 One useful option for the linker is @code{-s}: it reduces the size of the
16732 executable by removing all symbol table and relocation information from the
16733 executable.
16735 Standard options for the linker such as @code{-lmy_lib} or
16736 @code{-Ldir} can be added as is.
16737 For options that are not recognized by
16738 @code{gcc} as linker options, use the @code{gcc} switches
16739 @code{-Xlinker} or @code{-Wl,}.
16741 Refer to the GCC documentation for
16742 details.
16744 Here is an example showing how to generate a linker map:
16746 @example
16747 $ gnatlink my_prog -Wl,-Map,MAPFILE
16748 @end example
16750 Using @code{linker options} it is possible to set the program stack and
16751 heap size.
16752 See @ref{127,,Setting Stack Size from gnatlink} and
16753 @ref{128,,Setting Heap Size from gnatlink}.
16755 @code{gnatlink} determines the list of objects required by the Ada
16756 program and prepends them to the list of objects passed to the linker.
16757 @code{gnatlink} also gathers any arguments set by the use of
16758 @code{pragma Linker_Options} and adds them to the list of arguments
16759 presented to the linker.
16761 @node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
16762 @anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{129}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{12a}
16763 @subsection Switches for @code{gnatlink}
16766 The following switches are available with the @code{gnatlink} utility:
16768 @geindex --version (gnatlink)
16771 @table @asis
16773 @item @code{--version}
16775 Display Copyright and version, then exit disregarding all other options.
16776 @end table
16778 @geindex --help (gnatlink)
16781 @table @asis
16783 @item @code{--help}
16785 If @code{--version} was not used, display usage, then exit disregarding
16786 all other options.
16787 @end table
16789 @geindex Command line length
16791 @geindex -f (gnatlink)
16794 @table @asis
16796 @item @code{-f}
16798 On some targets, the command line length is limited, and @code{gnatlink}
16799 will generate a separate file for the linker if the list of object files
16800 is too long.
16801 The @code{-f} switch forces this file
16802 to be generated even if
16803 the limit is not exceeded. This is useful in some cases to deal with
16804 special situations where the command line length is exceeded.
16805 @end table
16807 @geindex Debugging information
16808 @geindex including
16810 @geindex -g (gnatlink)
16813 @table @asis
16815 @item @code{-g}
16817 The option to include debugging information causes the Ada bind file (in
16818 other words, @code{b~mainprog.adb}) to be compiled with @code{-g}.
16819 In addition, the binder does not delete the @code{b~mainprog.adb},
16820 @code{b~mainprog.o} and @code{b~mainprog.ali} files.
16821 Without @code{-g}, the binder removes these files by default.
16822 @end table
16824 @geindex -n (gnatlink)
16827 @table @asis
16829 @item @code{-n}
16831 Do not compile the file generated by the binder. This may be used when
16832 a link is rerun with different options, but there is no need to recompile
16833 the binder file.
16834 @end table
16836 @geindex -v (gnatlink)
16839 @table @asis
16841 @item @code{-v}
16843 Verbose mode. Causes additional information to be output, including a full
16844 list of the included object files.
16845 This switch option is most useful when you want
16846 to see what set of object files are being used in the link step.
16847 @end table
16849 @geindex -v -v (gnatlink)
16852 @table @asis
16854 @item @code{-v -v}
16856 Very verbose mode. Requests that the compiler operate in verbose mode when
16857 it compiles the binder file, and that the system linker run in verbose mode.
16858 @end table
16860 @geindex -o (gnatlink)
16863 @table @asis
16865 @item @code{-o @emph{exec-name}}
16867 @code{exec-name} specifies an alternate name for the generated
16868 executable program. If this switch is omitted, the executable has the same
16869 name as the main unit. For example, @code{gnatlink try.ali} creates
16870 an executable called @code{try}.
16871 @end table
16873 @geindex -B (gnatlink)
16876 @table @asis
16878 @item @code{-B@emph{dir}}
16880 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
16881 from @code{dir} instead of the default location. Only use this switch
16882 when multiple versions of the GNAT compiler are available.
16883 See the @code{Directory Options} section in @cite{The_GNU_Compiler_Collection}
16884 for further details. You would normally use the @code{-b} or
16885 @code{-V} switch instead.
16886 @end table
16888 @geindex -M (gnatlink)
16891 @table @asis
16893 @item @code{-M}
16895 When linking an executable, create a map file. The name of the map file
16896 has the same name as the executable with extension “.map”.
16897 @end table
16899 @geindex -M= (gnatlink)
16902 @table @asis
16904 @item @code{-M=@emph{mapfile}}
16906 When linking an executable, create a map file. The name of the map file is
16907 @code{mapfile}.
16908 @end table
16910 @geindex --GCC=compiler_name (gnatlink)
16913 @table @asis
16915 @item @code{--GCC=@emph{compiler_name}}
16917 Program used for compiling the binder file. The default is
16918 @code{gcc}. You need to use quotes around @code{compiler_name} if
16919 @code{compiler_name} contains spaces or other separator characters.
16920 As an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to
16921 use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
16922 inserted after your command name. Thus in the above example the compiler
16923 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
16924 A limitation of this syntax is that the name and path name of the executable
16925 itself must not include any embedded spaces. If the compiler executable is
16926 different from the default one (gcc or <prefix>-gcc), then the back-end
16927 switches in the ALI file are not used to compile the binder generated source.
16928 For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
16929 switches will be used for @code{--GCC="gcc -gnatv"}. If several
16930 @code{--GCC=compiler_name} are used, only the last @code{compiler_name}
16931 is taken into account. However, all the additional switches are also taken
16932 into account. Thus,
16933 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
16934 @code{--GCC="bar -x -y -z -t"}.
16935 @end table
16937 @geindex --LINK= (gnatlink)
16940 @table @asis
16942 @item @code{--LINK=@emph{name}}
16944 @code{name} is the name of the linker to be invoked. This is especially
16945 useful in mixed language programs since languages such as C++ require
16946 their own linker to be used. When this switch is omitted, the default
16947 name for the linker is @code{gcc}. When this switch is used, the
16948 specified linker is called instead of @code{gcc} with exactly the same
16949 parameters that would have been passed to @code{gcc} so if the desired
16950 linker requires different parameters it is necessary to use a wrapper
16951 script that massages the parameters before invoking the real linker. It
16952 may be useful to control the exact invocation by using the verbose
16953 switch.
16954 @end table
16956 @node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
16957 @anchor{gnat_ugn/building_executable_programs_with_gnat id48}@anchor{12b}@anchor{gnat_ugn/building_executable_programs_with_gnat using-the-gnu-make-utility}@anchor{70}
16958 @section Using the GNU @code{make} Utility
16961 @geindex make (GNU)
16962 @geindex GNU make
16964 This chapter offers some examples of makefiles that solve specific
16965 problems. It does not explain how to write a makefile, nor does it try to replace the
16966 @code{gnatmake} utility (@ref{c6,,Building with gnatmake}).
16968 All the examples in this section are specific to the GNU version of
16969 make. Although @code{make} is a standard utility, and the basic language
16970 is the same, these examples use some advanced features found only in
16971 @code{GNU make}.
16973 @menu
16974 * Using gnatmake in a Makefile:: 
16975 * Automatically Creating a List of Directories:: 
16976 * Generating the Command Line Switches:: 
16977 * Overcoming Command Line Length Limits:: 
16979 @end menu
16981 @node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
16982 @anchor{gnat_ugn/building_executable_programs_with_gnat id49}@anchor{12c}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gnatmake-in-a-makefile}@anchor{12d}
16983 @subsection Using gnatmake in a Makefile
16986 @c index makefile (GNU make)
16988 Complex project organizations can be handled in a very powerful way by
16989 using GNU make combined with gnatmake. For instance, here is a Makefile
16990 which allows you to build each subsystem of a big project into a separate
16991 shared library. Such a makefile allows you to significantly reduce the link
16992 time of very big applications while maintaining full coherence at
16993 each step of the build process.
16995 The list of dependencies are handled automatically by
16996 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
16997 the appropriate directories.
16999 Note that you should also read the example on how to automatically
17000 create the list of directories
17001 (@ref{12e,,Automatically Creating a List of Directories})
17002 which might help you in case your project has a lot of subdirectories.
17004 @example
17005 ## This Makefile is intended to be used with the following directory
17006 ## configuration:
17007 ##  - The sources are split into a series of csc (computer software components)
17008 ##    Each of these csc is put in its own directory.
17009 ##    Their name are referenced by the directory names.
17010 ##    They will be compiled into shared library (although this would also work
17011 ##    with static libraries)
17012 ##  - The main program (and possibly other packages that do not belong to any
17013 ##    csc) is put in the top level directory (where the Makefile is).
17014 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17015 ##                    \\_ second_csc (sources) __ lib (will contain the library)
17016 ##                    \\_ ...
17017 ## Although this Makefile is build for shared library, it is easy to modify
17018 ## to build partial link objects instead (modify the lines with -shared and
17019 ## gnatlink below)
17021 ## With this makefile, you can change any file in the system or add any new
17022 ## file, and everything will be recompiled correctly (only the relevant shared
17023 ## objects will be recompiled, and the main program will be re-linked).
17025 # The list of computer software component for your project. This might be
17026 # generated automatically.
17027 CSC_LIST=aa bb cc
17029 # Name of the main program (no extension)
17030 MAIN=main
17032 # If we need to build objects with -fPIC, uncomment the following line
17033 #NEED_FPIC=-fPIC
17035 # The following variable should give the directory containing libgnat.so
17036 # You can get this directory through 'gnatls -v'. This is usually the last
17037 # directory in the Object_Path.
17038 GLIB=...
17040 # The directories for the libraries
17041 # (This macro expands the list of CSC to the list of shared libraries, you
17042 # could simply use the expanded form:
17043 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17044 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17046 $@{MAIN@}: objects $@{LIB_DIR@}
17047     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17048     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17050 objects::
17051     # recompile the sources
17052     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17054 # Note: In a future version of GNAT, the following commands will be simplified
17055 # by a new tool, gnatmlib
17056 $@{LIB_DIR@}:
17057     mkdir -p $@{dir $@@ @}
17058     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17059     cd $@{dir $@@ @} && cp -f ../*.ali .
17061 # The dependencies for the modules
17062 # Note that we have to force the expansion of *.o, since in some cases
17063 # make won't be able to do it itself.
17064 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17065 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17066 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17068 # Make sure all of the shared libraries are in the path before starting the
17069 # program
17070 run::
17071     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17073 clean::
17074     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17075     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17076     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17077     $@{RM@} *.o *.ali $@{MAIN@}
17078 @end example
17080 @node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
17081 @anchor{gnat_ugn/building_executable_programs_with_gnat automatically-creating-a-list-of-directories}@anchor{12e}@anchor{gnat_ugn/building_executable_programs_with_gnat id50}@anchor{12f}
17082 @subsection Automatically Creating a List of Directories
17085 In most makefiles, you will have to specify a list of directories, and
17086 store it in a variable. For small projects, it is often easier to
17087 specify each of them by hand, since you then have full control over what
17088 is the proper order for these directories, which ones should be
17089 included.
17091 However, in larger projects, which might involve hundreds of
17092 subdirectories, it might be more convenient to generate this list
17093 automatically.
17095 The example below presents two methods. The first one, although less
17096 general, gives you more control over the list. It involves wildcard
17097 characters, that are automatically expanded by @code{make}. Its
17098 shortcoming is that you need to explicitly specify some of the
17099 organization of your project, such as for instance the directory tree
17100 depth, whether some directories are found in a separate tree, etc.
17102 The second method is the most general one. It requires an external
17103 program, called @code{find}, which is standard on all Unix systems. All
17104 the directories found under a given root directory will be added to the
17105 list.
17107 @example
17108 # The examples below are based on the following directory hierarchy:
17109 # All the directories can contain any number of files
17110 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17111 #                       ->  ab
17112 #                       ->  ac
17113 #                ->  b  ->  ba  ->  baa
17114 #                       ->  bb
17115 #                       ->  bc
17116 # This Makefile creates a variable called DIRS, that can be reused any time
17117 # you need this list (see the other examples in this section)
17119 # The root of your project's directory hierarchy
17120 ROOT_DIRECTORY=.
17122 ####
17123 # First method: specify explicitly the list of directories
17124 # This allows you to specify any subset of all the directories you need.
17125 ####
17127 DIRS := a/aa/ a/ab/ b/ba/
17129 ####
17130 # Second method: use wildcards
17131 # Note that the argument(s) to wildcard below should end with a '/'.
17132 # Since wildcards also return file names, we have to filter them out
17133 # to avoid duplicate directory names.
17134 # We thus use make's `@w{`}dir`@w{`} and `@w{`}sort`@w{`} functions.
17135 # It sets DIRs to the following value (note that the directories aaa and baa
17136 # are not given, unless you change the arguments to wildcard).
17137 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17138 ####
17140 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17141                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17143 ####
17144 # Third method: use an external program
17145 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17146 # This is the most complete command: it sets DIRs to the following value:
17147 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17148 ####
17150 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17151 @end example
17153 @node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
17154 @anchor{gnat_ugn/building_executable_programs_with_gnat generating-the-command-line-switches}@anchor{130}@anchor{gnat_ugn/building_executable_programs_with_gnat id51}@anchor{131}
17155 @subsection Generating the Command Line Switches
17158 Once you have created the list of directories as explained in the
17159 previous section (@ref{12e,,Automatically Creating a List of Directories}),
17160 you can easily generate the command line arguments to pass to gnatmake.
17162 For the sake of completeness, this example assumes that the source path
17163 is not the same as the object path, and that you have two separate lists
17164 of directories.
17166 @example
17167 # see "Automatically creating a list of directories" to create
17168 # these variables
17169 SOURCE_DIRS=
17170 OBJECT_DIRS=
17172 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17173 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17175 all:
17176         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17177 @end example
17179 @node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
17180 @anchor{gnat_ugn/building_executable_programs_with_gnat id52}@anchor{132}@anchor{gnat_ugn/building_executable_programs_with_gnat overcoming-command-line-length-limits}@anchor{133}
17181 @subsection Overcoming Command Line Length Limits
17184 One problem that might be encountered on big projects is that many
17185 operating systems limit the length of the command line. It is thus hard to give
17186 gnatmake the list of source and object directories.
17188 This example shows how you can set up environment variables, which will
17189 make @code{gnatmake} behave exactly as if the directories had been
17190 specified on the command line, but have a much higher length limit (or
17191 even none on most systems).
17193 It assumes that you have created a list of directories in your Makefile,
17194 using one of the methods presented in
17195 @ref{12e,,Automatically Creating a List of Directories}.
17196 For the sake of completeness, we assume that the object
17197 path (where the ALI files are found) is different from the sources patch.
17199 Note a small trick in the Makefile below: for efficiency reasons, we
17200 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17201 expanded immediately by @code{make}. This way we overcome the standard
17202 make behavior which is to expand the variables only when they are
17203 actually used.
17205 On Windows, if you are using the standard Windows command shell, you must
17206 replace colons with semicolons in the assignments to these variables.
17208 @example
17209 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17210 # This is the same thing as putting the -I arguments on the command line.
17211 # (the equivalent of using -aI on the command line would be to define
17212 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17213 # You can of course have different values for these variables.
17215 # Note also that we need to keep the previous values of these variables, since
17216 # they might have been set before running 'make' to specify where the GNAT
17217 # library is installed.
17219 # see "Automatically creating a list of directories" to create these
17220 # variables
17221 SOURCE_DIRS=
17222 OBJECT_DIRS=
17224 empty:=
17225 space:=$@{empty@} $@{empty@}
17226 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17227 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17228 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17229 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17230 export ADA_INCLUDE_PATH
17231 export ADA_OBJECTS_PATH
17233 all:
17234         gnatmake main_unit
17235 @end example
17237 @node GNAT Utility Programs,GNAT and Program Execution,Building Executable Programs with GNAT,Top
17238 @anchor{gnat_ugn/gnat_utility_programs doc}@anchor{134}@anchor{gnat_ugn/gnat_utility_programs gnat-utility-programs}@anchor{b}@anchor{gnat_ugn/gnat_utility_programs id1}@anchor{135}
17239 @chapter GNAT Utility Programs
17242 This chapter describes a number of utility programs:
17246 @itemize *
17248 @item 
17249 @ref{136,,The File Cleanup Utility gnatclean}
17251 @item 
17252 @ref{137,,The GNAT Library Browser gnatls}
17253 @end itemize
17255 Other GNAT utilities are described elsewhere in this manual:
17258 @itemize *
17260 @item 
17261 @ref{42,,Handling Arbitrary File Naming Conventions with gnatname}
17263 @item 
17264 @ref{4c,,File Name Krunching with gnatkr}
17266 @item 
17267 @ref{1d,,Renaming Files with gnatchop}
17269 @item 
17270 @ref{8f,,Preprocessing with gnatprep}
17271 @end itemize
17273 @menu
17274 * The File Cleanup Utility gnatclean:: 
17275 * The GNAT Library Browser gnatls:: 
17277 @end menu
17279 @node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
17280 @anchor{gnat_ugn/gnat_utility_programs id2}@anchor{138}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{136}
17281 @section The File Cleanup Utility @code{gnatclean}
17284 @geindex File cleanup tool
17286 @geindex gnatclean
17288 @code{gnatclean} is a tool that allows the deletion of files produced by the
17289 compiler, binder and linker, including ALI files, object files, tree files,
17290 expanded source files, library files, interface copy source files, binder
17291 generated files and executable files.
17293 @menu
17294 * Running gnatclean:: 
17295 * Switches for gnatclean:: 
17297 @end menu
17299 @node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
17300 @anchor{gnat_ugn/gnat_utility_programs id3}@anchor{139}@anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{13a}
17301 @subsection Running @code{gnatclean}
17304 The @code{gnatclean} command has the form:
17306 @quotation
17308 @example
17309 $ gnatclean switches names
17310 @end example
17311 @end quotation
17313 where @code{names} is a list of source file names. Suffixes @code{.ads} and
17314 @code{adb} may be omitted. If a project file is specified using switch
17315 @code{-P}, then @code{names} may be completely omitted.
17317 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17318 if switch @code{-c} is not specified, by the binder and
17319 the linker. In informative-only mode, specified by switch
17320 @code{-n}, the list of files that would have been deleted in
17321 normal mode is listed, but no file is actually deleted.
17323 @node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
17324 @anchor{gnat_ugn/gnat_utility_programs id4}@anchor{13b}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{13c}
17325 @subsection Switches for @code{gnatclean}
17328 @code{gnatclean} recognizes the following switches:
17330 @geindex --version (gnatclean)
17333 @table @asis
17335 @item @code{--version}
17337 Display copyright and version, then exit disregarding all other options.
17338 @end table
17340 @geindex --help (gnatclean)
17343 @table @asis
17345 @item @code{--help}
17347 If @code{--version} was not used, display usage, then exit disregarding
17348 all other options.
17350 @item @code{--subdirs=@emph{subdir}}
17352 Actual object directory of each project file is the subdirectory subdir of the
17353 object directory specified or defaulted in the project file.
17355 @item @code{--unchecked-shared-lib-imports}
17357 By default, shared library projects are not allowed to import static library
17358 projects. When this switch is used on the command line, this restriction is
17359 relaxed.
17360 @end table
17362 @geindex -c (gnatclean)
17365 @table @asis
17367 @item @code{-c}
17369 Only attempt to delete the files produced by the compiler, not those produced
17370 by the binder or the linker. The files that are not to be deleted are library
17371 files, interface copy files, binder generated files and executable files.
17372 @end table
17374 @geindex -D (gnatclean)
17377 @table @asis
17379 @item @code{-D @emph{dir}}
17381 Indicate that ALI and object files should normally be found in directory @code{dir}.
17382 @end table
17384 @geindex -F (gnatclean)
17387 @table @asis
17389 @item @code{-F}
17391 When using project files, if some errors or warnings are detected during
17392 parsing and verbose mode is not in effect (no use of switch
17393 -v), then error lines start with the full path name of the project
17394 file, rather than its simple file name.
17395 @end table
17397 @geindex -h (gnatclean)
17400 @table @asis
17402 @item @code{-h}
17404 Output a message explaining the usage of @code{gnatclean}.
17405 @end table
17407 @geindex -n (gnatclean)
17410 @table @asis
17412 @item @code{-n}
17414 Informative-only mode. Do not delete any files. Output the list of the files
17415 that would have been deleted if this switch was not specified.
17416 @end table
17418 @geindex -P (gnatclean)
17421 @table @asis
17423 @item @code{-P@emph{project}}
17425 Use project file @code{project}. Only one such switch can be used.
17426 When cleaning a project file, the files produced by the compilation of the
17427 immediate sources or inherited sources of the project files are to be
17428 deleted. This is not depending on the presence or not of executable names
17429 on the command line.
17430 @end table
17432 @geindex -q (gnatclean)
17435 @table @asis
17437 @item @code{-q}
17439 Quiet output. If there are no errors, do not output anything, except in
17440 verbose mode (switch -v) or in informative-only mode
17441 (switch -n).
17442 @end table
17444 @geindex -r (gnatclean)
17447 @table @asis
17449 @item @code{-r}
17451 When a project file is specified (using switch -P),
17452 clean all imported and extended project files, recursively. If this switch
17453 is not specified, only the files related to the main project file are to be
17454 deleted. This switch has no effect if no project file is specified.
17455 @end table
17457 @geindex -v (gnatclean)
17460 @table @asis
17462 @item @code{-v}
17464 Verbose mode.
17465 @end table
17467 @geindex -vP (gnatclean)
17470 @table @asis
17472 @item @code{-vP@emph{x}}
17474 Indicates the verbosity of the parsing of GNAT project files.
17475 @ref{cf,,Switches Related to Project Files}.
17476 @end table
17478 @geindex -X (gnatclean)
17481 @table @asis
17483 @item @code{-X@emph{name}=@emph{value}}
17485 Indicates that external variable @code{name} has the value @code{value}.
17486 The Project Manager will use this value for occurrences of
17487 @code{external(name)} when parsing the project file.
17488 See @ref{cf,,Switches Related to Project Files}.
17489 @end table
17491 @geindex -aO (gnatclean)
17494 @table @asis
17496 @item @code{-aO@emph{dir}}
17498 When searching for ALI and object files, look in directory @code{dir}.
17499 @end table
17501 @geindex -I (gnatclean)
17504 @table @asis
17506 @item @code{-I@emph{dir}}
17508 Equivalent to @code{-aO@emph{dir}}.
17509 @end table
17511 @geindex -I- (gnatclean)
17513 @geindex Source files
17514 @geindex suppressing search
17517 @table @asis
17519 @item @code{-I-}
17521 Do not look for ALI or object files in the directory
17522 where @code{gnatclean} was invoked.
17523 @end table
17525 @node The GNAT Library Browser gnatls,,The File Cleanup Utility gnatclean,GNAT Utility Programs
17526 @anchor{gnat_ugn/gnat_utility_programs id5}@anchor{13d}@anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{137}
17527 @section The GNAT Library Browser @code{gnatls}
17530 @geindex Library browser
17532 @geindex gnatls
17534 @code{gnatls} is a tool that outputs information about compiled
17535 units. It gives the relationship between objects, unit names and source
17536 files. It can also be used to check the source dependencies of a unit
17537 as well as various characteristics.
17539 @menu
17540 * Running gnatls:: 
17541 * Switches for gnatls:: 
17542 * Example of gnatls Usage:: 
17544 @end menu
17546 @node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
17547 @anchor{gnat_ugn/gnat_utility_programs id6}@anchor{13e}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{13f}
17548 @subsection Running @code{gnatls}
17551 The @code{gnatls} command has the form
17553 @quotation
17555 @example
17556 $ gnatls switches object_or_ali_file
17557 @end example
17558 @end quotation
17560 The main argument is the list of object or @code{ali} files
17561 (see @ref{28,,The Ada Library Information Files})
17562 for which information is requested.
17564 In normal mode, without additional option, @code{gnatls} produces a
17565 four-column listing. Each line represents information for a specific
17566 object. The first column gives the full path of the object, the second
17567 column gives the name of the principal unit in this object, the third
17568 column gives the status of the source and the fourth column gives the
17569 full path of the source representing this unit.
17570 Here is a simple example of use:
17572 @quotation
17574 @example
17575 $ gnatls *.o
17576 ./demo1.o            demo1            DIF demo1.adb
17577 ./demo2.o            demo2             OK demo2.adb
17578 ./hello.o            h1                OK hello.adb
17579 ./instr-child.o      instr.child      MOK instr-child.adb
17580 ./instr.o            instr             OK instr.adb
17581 ./tef.o              tef              DIF tef.adb
17582 ./text_io_example.o  text_io_example   OK text_io_example.adb
17583 ./tgef.o             tgef             DIF tgef.adb
17584 @end example
17585 @end quotation
17587 The first line can be interpreted as follows: the main unit which is
17588 contained in
17589 object file @code{demo1.o} is demo1, whose main source is in
17590 @code{demo1.adb}. Furthermore, the version of the source used for the
17591 compilation of demo1 has been modified (DIF). Each source file has a status
17592 qualifier which can be:
17595 @table @asis
17597 @item @emph{OK (unchanged)}
17599 The version of the source file used for the compilation of the
17600 specified unit corresponds exactly to the actual source file.
17602 @item @emph{MOK (slightly modified)}
17604 The version of the source file used for the compilation of the
17605 specified unit differs from the actual source file but not enough to
17606 require recompilation. If you use gnatmake with the option
17607 @code{-m} (minimal recompilation), a file marked
17608 MOK will not be recompiled.
17610 @item @emph{DIF (modified)}
17612 No version of the source found on the path corresponds to the source
17613 used to build this object.
17615 @item @emph{??? (file not found)}
17617 No source file was found for this unit.
17619 @item @emph{HID (hidden,  unchanged version not first on PATH)}
17621 The version of the source that corresponds exactly to the source used
17622 for compilation has been found on the path but it is hidden by another
17623 version of the same source that has been modified.
17624 @end table
17626 @node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
17627 @anchor{gnat_ugn/gnat_utility_programs id7}@anchor{140}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{141}
17628 @subsection Switches for @code{gnatls}
17631 @code{gnatls} recognizes the following switches:
17633 @geindex --version (gnatls)
17636 @table @asis
17638 @item @code{--version}
17640 Display copyright and version, then exit disregarding all other options.
17641 @end table
17643 @geindex --help (gnatls)
17646 @table @asis
17648 @item @code{--help}
17650 If @code{--version} was not used, display usage, then exit disregarding
17651 all other options.
17652 @end table
17654 @geindex -a (gnatls)
17657 @table @asis
17659 @item @code{-a}
17661 Consider all units, including those of the predefined Ada library.
17662 Especially useful with @code{-d}.
17663 @end table
17665 @geindex -d (gnatls)
17668 @table @asis
17670 @item @code{-d}
17672 List sources from which specified units depend on.
17673 @end table
17675 @geindex -h (gnatls)
17678 @table @asis
17680 @item @code{-h}
17682 Output the list of options.
17683 @end table
17685 @geindex -o (gnatls)
17688 @table @asis
17690 @item @code{-o}
17692 Only output information about object files.
17693 @end table
17695 @geindex -s (gnatls)
17698 @table @asis
17700 @item @code{-s}
17702 Only output information about source files.
17703 @end table
17705 @geindex -u (gnatls)
17708 @table @asis
17710 @item @code{-u}
17712 Only output information about compilation units.
17713 @end table
17715 @geindex -files (gnatls)
17718 @table @asis
17720 @item @code{-files=@emph{file}}
17722 Take as arguments the files listed in text file @code{file}.
17723 Text file @code{file} may contain empty lines that are ignored.
17724 Each nonempty line should contain the name of an existing file.
17725 Several such switches may be specified simultaneously.
17726 @end table
17728 @geindex -aO (gnatls)
17730 @geindex -aI (gnatls)
17732 @geindex -I (gnatls)
17734 @geindex -I- (gnatls)
17737 @table @asis
17739 @item @code{-aO@emph{dir}}, @code{-aI@emph{dir}}, @code{-I@emph{dir}}, @code{-I-}, @code{-nostdinc}
17741 Source path manipulation. Same meaning as the equivalent @code{gnatmake}
17742 flags (@ref{ce,,Switches for gnatmake}).
17743 @end table
17745 @geindex -aP (gnatls)
17748 @table @asis
17750 @item @code{-aP@emph{dir}}
17752 Add @code{dir} at the beginning of the project search dir.
17753 @end table
17755 @geindex --RTS (gnatls)
17758 @table @asis
17760 @item @code{--RTS=@emph{rts-path}}
17762 Specifies the default location of the runtime library. Same meaning as the
17763 equivalent @code{gnatmake} flag (@ref{ce,,Switches for gnatmake}).
17764 @end table
17766 @geindex -v (gnatls)
17769 @table @asis
17771 @item @code{-v}
17773 Verbose mode. Output the complete source, object and project paths. Do not use
17774 the default column layout but instead use long format giving as much as
17775 information possible on each requested units, including special
17776 characteristics such as:
17779 @itemize *
17781 @item 
17782 @emph{Preelaborable}: The unit is preelaborable in the Ada sense.
17784 @item 
17785 @emph{No_Elab_Code}:  No elaboration code has been produced by the compiler for this unit.
17787 @item 
17788 @emph{Pure}: The unit is pure in the Ada sense.
17790 @item 
17791 @emph{Elaborate_Body}: The unit contains a pragma Elaborate_Body.
17793 @item 
17794 @emph{Remote_Types}: The unit contains a pragma Remote_Types.
17796 @item 
17797 @emph{Shared_Passive}: The unit contains a pragma Shared_Passive.
17799 @item 
17800 @emph{Predefined}: This unit is part of the predefined environment and cannot be modified
17801 by the user.
17803 @item 
17804 @emph{Remote_Call_Interface}: The unit contains a pragma Remote_Call_Interface.
17805 @end itemize
17806 @end table
17808 @node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
17809 @anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{142}@anchor{gnat_ugn/gnat_utility_programs id8}@anchor{143}
17810 @subsection Example of @code{gnatls} Usage
17813 Example of using the verbose switch. Note how the source and
17814 object paths are affected by the -I switch.
17816 @quotation
17818 @example
17819 $ gnatls -v -I.. demo1.o
17821 GNATLS 5.03w (20041123-34)
17822 Copyright 1997-2004 Free Software Foundation, Inc.
17824 Source Search Path:
17825    <Current_Directory>
17826    ../
17827    /home/comar/local/adainclude/
17829 Object Search Path:
17830    <Current_Directory>
17831    ../
17832    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17834 Project Search Path:
17835    <Current_Directory>
17836    /home/comar/local/lib/gnat/
17838 ./demo1.o
17839    Unit =>
17840      Name   => demo1
17841      Kind   => subprogram body
17842      Flags  => No_Elab_Code
17843      Source => demo1.adb    modified
17844 @end example
17845 @end quotation
17847 The following is an example of use of the dependency list.
17848 Note the use of the -s switch
17849 which gives a straight list of source files. This can be useful for
17850 building specialized scripts.
17852 @quotation
17854 @example
17855 $ gnatls -d demo2.o
17856 ./demo2.o   demo2        OK demo2.adb
17857                          OK gen_list.ads
17858                          OK gen_list.adb
17859                          OK instr.ads
17860                          OK instr-child.ads
17862 $ gnatls -d -s -a demo1.o
17863 demo1.adb
17864 /home/comar/local/adainclude/ada.ads
17865 /home/comar/local/adainclude/a-finali.ads
17866 /home/comar/local/adainclude/a-filico.ads
17867 /home/comar/local/adainclude/a-stream.ads
17868 /home/comar/local/adainclude/a-tags.ads
17869 gen_list.ads
17870 gen_list.adb
17871 /home/comar/local/adainclude/gnat.ads
17872 /home/comar/local/adainclude/g-io.ads
17873 instr.ads
17874 /home/comar/local/adainclude/system.ads
17875 /home/comar/local/adainclude/s-exctab.ads
17876 /home/comar/local/adainclude/s-finimp.ads
17877 /home/comar/local/adainclude/s-finroo.ads
17878 /home/comar/local/adainclude/s-secsta.ads
17879 /home/comar/local/adainclude/s-stalib.ads
17880 /home/comar/local/adainclude/s-stoele.ads
17881 /home/comar/local/adainclude/s-stratt.ads
17882 /home/comar/local/adainclude/s-tasoli.ads
17883 /home/comar/local/adainclude/s-unstyp.ads
17884 /home/comar/local/adainclude/unchconv.ads
17885 @end example
17886 @end quotation
17894 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
17896 @node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
17897 @anchor{gnat_ugn/gnat_and_program_execution doc}@anchor{144}@anchor{gnat_ugn/gnat_and_program_execution gnat-and-program-execution}@anchor{c}@anchor{gnat_ugn/gnat_and_program_execution id1}@anchor{145}
17898 @chapter GNAT and Program Execution
17901 This chapter covers several topics:
17904 @itemize *
17906 @item 
17907 @ref{146,,Running and Debugging Ada Programs}
17909 @item 
17910 @ref{147,,Profiling}
17912 @item 
17913 @ref{148,,Improving Performance}
17915 @item 
17916 @ref{149,,Overflow Check Handling in GNAT}
17918 @item 
17919 @ref{14a,,Performing Dimensionality Analysis in GNAT}
17921 @item 
17922 @ref{14b,,Stack Related Facilities}
17924 @item 
17925 @ref{14c,,Memory Management Issues}
17926 @end itemize
17928 @menu
17929 * Running and Debugging Ada Programs:: 
17930 * Profiling:: 
17931 * Improving Performance:: 
17932 * Overflow Check Handling in GNAT:: 
17933 * Performing Dimensionality Analysis in GNAT:: 
17934 * Stack Related Facilities:: 
17935 * Memory Management Issues:: 
17937 @end menu
17939 @node Running and Debugging Ada Programs,Profiling,,GNAT and Program Execution
17940 @anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{146}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{14d}
17941 @section Running and Debugging Ada Programs
17944 @geindex Debugging
17946 This section discusses how to debug Ada programs.
17948 An incorrect Ada program may be handled in three ways by the GNAT compiler:
17951 @itemize *
17953 @item 
17954 The illegality may be a violation of the static semantics of Ada. In
17955 that case GNAT diagnoses the constructs in the program that are illegal.
17956 It is then a straightforward matter for the user to modify those parts of
17957 the program.
17959 @item 
17960 The illegality may be a violation of the dynamic semantics of Ada. In
17961 that case the program compiles and executes, but may generate incorrect
17962 results, or may terminate abnormally with some exception.
17964 @item 
17965 When presented with a program that contains convoluted errors, GNAT
17966 itself may terminate abnormally without providing full diagnostics on
17967 the incorrect user program.
17968 @end itemize
17970 @geindex Debugger
17972 @geindex gdb
17974 @menu
17975 * The GNAT Debugger GDB:: 
17976 * Running GDB:: 
17977 * Introduction to GDB Commands:: 
17978 * Using Ada Expressions:: 
17979 * Calling User-Defined Subprograms:: 
17980 * Using the next Command in a Function:: 
17981 * Stopping When Ada Exceptions Are Raised:: 
17982 * Ada Tasks:: 
17983 * Debugging Generic Units:: 
17984 * Remote Debugging with gdbserver:: 
17985 * GNAT Abnormal Termination or Failure to Terminate:: 
17986 * Naming Conventions for GNAT Source Files:: 
17987 * Getting Internal Debugging Information:: 
17988 * Stack Traceback:: 
17989 * Pretty-Printers for the GNAT runtime:: 
17991 @end menu
17993 @node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
17994 @anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{14e}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{14f}
17995 @subsection The GNAT Debugger GDB
17998 @code{GDB} is a general purpose, platform-independent debugger that
17999 can be used to debug mixed-language programs compiled with @code{gcc},
18000 and in particular is capable of debugging Ada programs compiled with
18001 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18002 complex Ada data structures.
18004 See @cite{Debugging with GDB},
18005 for full details on the usage of @code{GDB}, including a section on
18006 its usage on programs. This manual should be consulted for full
18007 details. The section that follows is a brief introduction to the
18008 philosophy and use of @code{GDB}.
18010 When GNAT programs are compiled, the compiler optionally writes debugging
18011 information into the generated object file, including information on
18012 line numbers, and on declared types and variables. This information is
18013 separate from the generated code. It makes the object files considerably
18014 larger, but it does not add to the size of the actual executable that
18015 will be loaded into memory, and has no impact on run-time performance. The
18016 generation of debug information is triggered by the use of the
18017 @code{-g} switch in the @code{gcc} or @code{gnatmake} command
18018 used to carry out the compilations. It is important to emphasize that
18019 the use of these options does not change the generated code.
18021 The debugging information is written in standard system formats that
18022 are used by many tools, including debuggers and profilers. The format
18023 of the information is typically designed to describe C types and
18024 semantics, but GNAT implements a translation scheme which allows full
18025 details about Ada types and variables to be encoded into these
18026 standard C formats. Details of this encoding scheme may be found in
18027 the file exp_dbug.ads in the GNAT source distribution. However, the
18028 details of this encoding are, in general, of no interest to a user,
18029 since @code{GDB} automatically performs the necessary decoding.
18031 When a program is bound and linked, the debugging information is
18032 collected from the object files, and stored in the executable image of
18033 the program. Again, this process significantly increases the size of
18034 the generated executable file, but it does not increase the size of
18035 the executable program itself. Furthermore, if this program is run in
18036 the normal manner, it runs exactly as if the debug information were
18037 not present, and takes no more actual memory.
18039 However, if the program is run under control of @code{GDB}, the
18040 debugger is activated.  The image of the program is loaded, at which
18041 point it is ready to run.  If a run command is given, then the program
18042 will run exactly as it would have if @code{GDB} were not present. This
18043 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18044 entirely non-intrusive until a breakpoint is encountered.  If no
18045 breakpoint is ever hit, the program will run exactly as it would if no
18046 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18047 the debugging information and can respond to user commands to inspect
18048 variables, and more generally to report on the state of execution.
18050 @node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
18051 @anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{150}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{151}
18052 @subsection Running GDB
18055 This section describes how to initiate the debugger.
18057 The debugger can be launched from a @code{GNAT Studio} menu or
18058 directly from the command line. The description below covers the latter use.
18059 All the commands shown can be used in the @code{GNAT Studio} debug console window,
18060 but there are usually more GUI-based ways to achieve the same effect.
18062 The command to run @code{GDB} is
18064 @quotation
18066 @example
18067 $ gdb program
18068 @end example
18069 @end quotation
18071 where @code{program} is the name of the executable file. This
18072 activates the debugger and results in a prompt for debugger commands.
18073 The simplest command is simply @code{run}, which causes the program to run
18074 exactly as if the debugger were not present. The following section
18075 describes some of the additional commands that can be given to @code{GDB}.
18077 @node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
18078 @anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{152}@anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{153}
18079 @subsection Introduction to GDB Commands
18082 @code{GDB} contains a large repertoire of commands.
18083 See @cite{Debugging with GDB} for extensive documentation on the use
18084 of these commands, together with examples of their use. Furthermore,
18085 the command @emph{help} invoked from within GDB activates a simple help
18086 facility which summarizes the available commands and their options.
18087 In this section we summarize a few of the most commonly
18088 used commands to give an idea of what @code{GDB} is about. You should create
18089 a simple program with debugging information and experiment with the use of
18090 these @code{GDB} commands on the program as you read through the
18091 following section.
18094 @itemize *
18096 @item 
18098 @table @asis
18100 @item @code{set args @emph{arguments}}
18102 The @emph{arguments} list above is a list of arguments to be passed to
18103 the program on a subsequent run command, just as though the arguments
18104 had been entered on a normal invocation of the program. The @code{set args}
18105 command is not needed if the program does not require arguments.
18106 @end table
18108 @item 
18110 @table @asis
18112 @item @code{run}
18114 The @code{run} command causes execution of the program to start from
18115 the beginning. If the program is already running, that is to say if
18116 you are currently positioned at a breakpoint, then a prompt will ask
18117 for confirmation that you want to abandon the current execution and
18118 restart.
18119 @end table
18121 @item 
18123 @table @asis
18125 @item @code{breakpoint @emph{location}}
18127 The breakpoint command sets a breakpoint, that is to say a point at which
18128 execution will halt and @code{GDB} will await further
18129 commands. @emph{location} is
18130 either a line number within a file, given in the format @code{file:linenumber},
18131 or it is the name of a subprogram. If you request that a breakpoint be set on
18132 a subprogram that is overloaded, a prompt will ask you to specify on which of
18133 those subprograms you want to breakpoint. You can also
18134 specify that all of them should be breakpointed. If the program is run
18135 and execution encounters the breakpoint, then the program
18136 stops and @code{GDB} signals that the breakpoint was encountered by
18137 printing the line of code before which the program is halted.
18138 @end table
18140 @item 
18142 @table @asis
18144 @item @code{catch exception @emph{name}}
18146 This command causes the program execution to stop whenever exception
18147 @code{name} is raised.  If @code{name} is omitted, then the execution is
18148 suspended when any exception is raised.
18149 @end table
18151 @item 
18153 @table @asis
18155 @item @code{print @emph{expression}}
18157 This will print the value of the given expression. Most simple
18158 Ada expression formats are properly handled by @code{GDB}, so the expression
18159 can contain function calls, variables, operators, and attribute references.
18160 @end table
18162 @item 
18164 @table @asis
18166 @item @code{continue}
18168 Continues execution following a breakpoint, until the next breakpoint or the
18169 termination of the program.
18170 @end table
18172 @item 
18174 @table @asis
18176 @item @code{step}
18178 Executes a single line after a breakpoint. If the next statement
18179 is a subprogram call, execution continues into (the first statement of)
18180 the called subprogram.
18181 @end table
18183 @item 
18185 @table @asis
18187 @item @code{next}
18189 Executes a single line. If this line is a subprogram call, executes and
18190 returns from the call.
18191 @end table
18193 @item 
18195 @table @asis
18197 @item @code{list}
18199 Lists a few lines around the current source location. In practice, it
18200 is usually more convenient to have a separate edit window open with the
18201 relevant source file displayed. Successive applications of this command
18202 print subsequent lines. The command can be given an argument which is a
18203 line number, in which case it displays a few lines around the specified one.
18204 @end table
18206 @item 
18208 @table @asis
18210 @item @code{backtrace}
18212 Displays a backtrace of the call chain. This command is typically
18213 used after a breakpoint has occurred, to examine the sequence of calls that
18214 leads to the current breakpoint. The display includes one line for each
18215 activation record (frame) corresponding to an active subprogram.
18216 @end table
18218 @item 
18220 @table @asis
18222 @item @code{up}
18224 At a breakpoint, @code{GDB} can display the values of variables local
18225 to the current frame. The command @code{up} can be used to
18226 examine the contents of other active frames, by moving the focus up
18227 the stack, that is to say from callee to caller, one frame at a time.
18228 @end table
18230 @item 
18232 @table @asis
18234 @item @code{down}
18236 Moves the focus of @code{GDB} down from the frame currently being
18237 examined to the frame of its callee (the reverse of the previous command),
18238 @end table
18240 @item 
18242 @table @asis
18244 @item @code{frame @emph{n}}
18246 Inspect the frame with the given number. The value 0 denotes the frame
18247 of the current breakpoint, that is to say the top of the call stack.
18248 @end table
18250 @item 
18252 @table @asis
18254 @item @code{kill}
18256 Kills the child process in which the program is running under GDB.
18257 This may be useful for several purposes:
18260 @itemize *
18262 @item 
18263 It allows you to recompile and relink your program, since on many systems
18264 you cannot regenerate an executable file while it is running in a process.
18266 @item 
18267 You can run your program outside the debugger, on systems that do not
18268 permit executing a program outside GDB while breakpoints are set
18269 within GDB.
18271 @item 
18272 It allows you to debug a core dump rather than a running process.
18273 @end itemize
18274 @end table
18275 @end itemize
18277 The above list is a very short introduction to the commands that
18278 @code{GDB} provides. Important additional capabilities, including conditional
18279 breakpoints, the ability to execute command sequences on a breakpoint,
18280 the ability to debug at the machine instruction level and many other
18281 features are described in detail in @cite{Debugging with GDB}.
18282 Note that most commands can be abbreviated
18283 (for example, c for continue, bt for backtrace).
18285 @node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
18286 @anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{154}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{155}
18287 @subsection Using Ada Expressions
18290 @geindex Ada expressions (in gdb)
18292 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18293 extensions. The philosophy behind the design of this subset is
18295 @quotation
18298 @itemize *
18300 @item 
18301 That @code{GDB} should provide basic literals and access to operations for
18302 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18303 leaving more sophisticated computations to subprograms written into the
18304 program (which therefore may be called from @code{GDB}).
18306 @item 
18307 That type safety and strict adherence to Ada language restrictions
18308 are not particularly relevant in a debugging context.
18310 @item 
18311 That brevity is important to the @code{GDB} user.
18312 @end itemize
18313 @end quotation
18315 Thus, for brevity, the debugger acts as if there were
18316 implicit @code{with} and @code{use} clauses in effect for all user-written
18317 packages, thus making it unnecessary to fully qualify most names with
18318 their packages, regardless of context. Where this causes ambiguity,
18319 @code{GDB} asks the user’s intent.
18321 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
18323 @node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
18324 @anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{156}@anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{157}
18325 @subsection Calling User-Defined Subprograms
18328 An important capability of @code{GDB} is the ability to call user-defined
18329 subprograms while debugging. This is achieved simply by entering
18330 a subprogram call statement in the form:
18332 @quotation
18334 @example
18335 call subprogram-name (parameters)
18336 @end example
18337 @end quotation
18339 The keyword @code{call} can be omitted in the normal case where the
18340 @code{subprogram-name} does not coincide with any of the predefined
18341 @code{GDB} commands.
18343 The effect is to invoke the given subprogram, passing it the
18344 list of parameters that is supplied. The parameters can be expressions and
18345 can include variables from the program being debugged. The
18346 subprogram must be defined
18347 at the library level within your program, and @code{GDB} will call the
18348 subprogram within the environment of your program execution (which
18349 means that the subprogram is free to access or even modify variables
18350 within your program).
18352 The most important use of this facility is in allowing the inclusion of
18353 debugging routines that are tailored to particular data structures
18354 in your program. Such debugging routines can be written to provide a suitably
18355 high-level description of an abstract type, rather than a low-level dump
18356 of its physical layout. After all, the standard
18357 @code{GDB print} command only knows the physical layout of your
18358 types, not their abstract meaning. Debugging routines can provide information
18359 at the desired semantic level and are thus enormously useful.
18361 For example, when debugging GNAT itself, it is crucial to have access to
18362 the contents of the tree nodes used to represent the program internally.
18363 But tree nodes are represented simply by an integer value (which in turn
18364 is an index into a table of nodes).
18365 Using the @code{print} command on a tree node would simply print this integer
18366 value, which is not very useful. But the PN routine (defined in file
18367 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18368 a useful high level representation of the tree node, which includes the
18369 syntactic category of the node, its position in the source, the integers
18370 that denote descendant nodes and parent node, as well as varied
18371 semantic information. To study this example in more detail, you might want to
18372 look at the body of the PN procedure in the stated file.
18374 Another useful application of this capability is to deal with situations of
18375 complex data which are not handled suitably by GDB. For example, if you specify
18376 Convention Fortran for a multi-dimensional array, GDB does not know that
18377 the ordering of array elements has been switched and will not properly
18378 address the array elements. In such a case, instead of trying to print the
18379 elements directly from GDB, you can write a callable procedure that prints
18380 the elements in the desired format.
18382 @node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
18383 @anchor{gnat_ugn/gnat_and_program_execution id8}@anchor{158}@anchor{gnat_ugn/gnat_and_program_execution using-the-next-command-in-a-function}@anchor{159}
18384 @subsection Using the @emph{next} Command in a Function
18387 When you use the @code{next} command in a function, the current source
18388 location will advance to the next statement as usual. A special case
18389 arises in the case of a @code{return} statement.
18391 Part of the code for a return statement is the ‘epilogue’ of the function.
18392 This is the code that returns to the caller. There is only one copy of
18393 this epilogue code, and it is typically associated with the last return
18394 statement in the function if there is more than one return. In some
18395 implementations, this epilogue is associated with the first statement
18396 of the function.
18398 The result is that if you use the @code{next} command from a return
18399 statement that is not the last return statement of the function you
18400 may see a strange apparent jump to the last return statement or to
18401 the start of the function. You should simply ignore this odd jump.
18402 The value returned is always that from the first return statement
18403 that was stepped through.
18405 @node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
18406 @anchor{gnat_ugn/gnat_and_program_execution id9}@anchor{15a}@anchor{gnat_ugn/gnat_and_program_execution stopping-when-ada-exceptions-are-raised}@anchor{15b}
18407 @subsection Stopping When Ada Exceptions Are Raised
18410 @geindex Exceptions (in gdb)
18412 You can set catchpoints that stop the program execution when your program
18413 raises selected exceptions.
18416 @itemize *
18418 @item 
18420 @table @asis
18422 @item @code{catch exception}
18424 Set a catchpoint that stops execution whenever (any task in the) program
18425 raises any exception.
18426 @end table
18428 @item 
18430 @table @asis
18432 @item @code{catch exception @emph{name}}
18434 Set a catchpoint that stops execution whenever (any task in the) program
18435 raises the exception @emph{name}.
18436 @end table
18438 @item 
18440 @table @asis
18442 @item @code{catch exception unhandled}
18444 Set a catchpoint that stops executing whenever (any task in the) program
18445 raises an exception for which there is no handler.
18446 @end table
18448 @item 
18450 @table @asis
18452 @item @code{info exceptions}, @code{info exceptions @emph{regexp}}
18454 The @code{info exceptions} command permits the user to examine all defined
18455 exceptions within Ada programs. With a regular expression, @emph{regexp}, as
18456 argument, prints out only those exceptions whose name matches @emph{regexp}.
18457 @end table
18458 @end itemize
18460 @geindex Tasks (in gdb)
18462 @node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
18463 @anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{15c}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{15d}
18464 @subsection Ada Tasks
18467 @code{GDB} allows the following task-related commands:
18470 @itemize *
18472 @item 
18474 @table @asis
18476 @item @code{info tasks}
18478 This command shows a list of current Ada tasks, as in the following example:
18480 @example
18481 (gdb) info tasks
18482   ID       TID P-ID   Thread Pri State                 Name
18483    1   8088000   0   807e000  15 Child Activation Wait main_task
18484    2   80a4000   1   80ae000  15 Accept/Select Wait    b
18485    3   809a800   1   80a4800  15 Child Activation Wait a
18486 *  4   80ae800   3   80b8000  15 Running               c
18487 @end example
18489 In this listing, the asterisk before the first task indicates it to be the
18490 currently running task. The first column lists the task ID that is used
18491 to refer to tasks in the following commands.
18492 @end table
18493 @end itemize
18495 @geindex Breakpoints and tasks
18498 @itemize *
18500 @item 
18501 @code{break} @emph{linespec} @code{task} @emph{taskid}, @code{break} @emph{linespec} @code{task} @emph{taskid} @code{if} …
18503 @quotation
18505 These commands are like the @code{break ... thread ...}.
18506 @emph{linespec} specifies source lines.
18508 Use the qualifier @code{task @emph{taskid}} with a breakpoint command
18509 to specify that you only want @code{GDB} to stop the program when a
18510 particular Ada task reaches this breakpoint. @emph{taskid} is one of the
18511 numeric task identifiers assigned by @code{GDB}, shown in the first
18512 column of the @code{info tasks} display.
18514 If you do not specify @code{task @emph{taskid}} when you set a
18515 breakpoint, the breakpoint applies to @emph{all} tasks of your
18516 program.
18518 You can use the @code{task} qualifier on conditional breakpoints as
18519 well; in this case, place @code{task @emph{taskid}} before the
18520 breakpoint condition (before the @code{if}).
18521 @end quotation
18522 @end itemize
18524 @geindex Task switching (in gdb)
18527 @itemize *
18529 @item 
18530 @code{task @emph{taskno}}
18532 @quotation
18534 This command allows switching to the task referred by @emph{taskno}. In
18535 particular, this allows browsing of the backtrace of the specified
18536 task. It is advisable to switch back to the original task before
18537 continuing execution otherwise the scheduling of the program may be
18538 perturbed.
18539 @end quotation
18540 @end itemize
18542 For more detailed information on the tasking support,
18543 see @cite{Debugging with GDB}.
18545 @geindex Debugging Generic Units
18547 @geindex Generics
18549 @node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
18550 @anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{15e}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{15f}
18551 @subsection Debugging Generic Units
18554 GNAT always uses code expansion for generic instantiation. This means that
18555 each time an instantiation occurs, a complete copy of the original code is
18556 made, with appropriate substitutions of formals by actuals.
18558 It is not possible to refer to the original generic entities in
18559 @code{GDB}, but it is always possible to debug a particular instance of
18560 a generic, by using the appropriate expanded names. For example, if we have
18562 @quotation
18564 @example
18565 procedure g is
18567    generic package k is
18568       procedure kp (v1 : in out integer);
18569    end k;
18571    package body k is
18572       procedure kp (v1 : in out integer) is
18573       begin
18574          v1 := v1 + 1;
18575       end kp;
18576    end k;
18578    package k1 is new k;
18579    package k2 is new k;
18581    var : integer := 1;
18583 begin
18584    k1.kp (var);
18585    k2.kp (var);
18586    k1.kp (var);
18587    k2.kp (var);
18588 end;
18589 @end example
18590 @end quotation
18592 Then to break on a call to procedure kp in the k2 instance, simply
18593 use the command:
18595 @quotation
18597 @example
18598 (gdb) break g.k2.kp
18599 @end example
18600 @end quotation
18602 When the breakpoint occurs, you can step through the code of the
18603 instance in the normal manner and examine the values of local variables, as for
18604 other units.
18606 @geindex Remote Debugging with gdbserver
18608 @node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
18609 @anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{160}@anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{161}
18610 @subsection Remote Debugging with gdbserver
18613 On platforms where gdbserver is supported, it is possible to use this tool
18614 to debug your application remotely.  This can be useful in situations
18615 where the program needs to be run on a target host that is different
18616 from the host used for development, particularly when the target has
18617 a limited amount of resources (either CPU and/or memory).
18619 To do so, start your program using gdbserver on the target machine.
18620 gdbserver then automatically suspends the execution of your program
18621 at its entry point, waiting for a debugger to connect to it.  The
18622 following commands starts an application and tells gdbserver to
18623 wait for a connection with the debugger on localhost port 4444.
18625 @quotation
18627 @example
18628 $ gdbserver localhost:4444 program
18629 Process program created; pid = 5685
18630 Listening on port 4444
18631 @end example
18632 @end quotation
18634 Once gdbserver has started listening, we can tell the debugger to establish
18635 a connection with this gdbserver, and then start the same debugging session
18636 as if the program was being debugged on the same host, directly under
18637 the control of GDB.
18639 @quotation
18641 @example
18642 $ gdb program
18643 (gdb) target remote targethost:4444
18644 Remote debugging using targethost:4444
18645 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
18646 (gdb) b foo.adb:3
18647 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
18648 (gdb) continue
18649 Continuing.
18651 Breakpoint 1, foo () at foo.adb:4
18652 4       end foo;
18653 @end example
18654 @end quotation
18656 It is also possible to use gdbserver to attach to an already running
18657 program, in which case the execution of that program is simply suspended
18658 until the connection between the debugger and gdbserver is established.
18660 For more information on how to use gdbserver, see the @emph{Using the gdbserver Program}
18661 section in @cite{Debugging with GDB}.
18662 GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
18664 @geindex Abnormal Termination or Failure to Terminate
18666 @node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
18667 @anchor{gnat_ugn/gnat_and_program_execution gnat-abnormal-termination-or-failure-to-terminate}@anchor{162}@anchor{gnat_ugn/gnat_and_program_execution id13}@anchor{163}
18668 @subsection GNAT Abnormal Termination or Failure to Terminate
18671 When presented with programs that contain serious errors in syntax
18672 or semantics,
18673 GNAT may on rare occasions  experience problems in operation, such
18674 as aborting with a
18675 segmentation fault or illegal memory access, raising an internal
18676 exception, terminating abnormally, or failing to terminate at all.
18677 In such cases, you can activate
18678 various features of GNAT that can help you pinpoint the construct in your
18679 program that is the likely source of the problem.
18681 The following strategies are presented in increasing order of
18682 difficulty, corresponding to your experience in using GNAT and your
18683 familiarity with compiler internals.
18686 @itemize *
18688 @item 
18689 Run @code{gcc} with the @code{-gnatf}. This first
18690 switch causes all errors on a given line to be reported. In its absence,
18691 only the first error on a line is displayed.
18693 The @code{-gnatdO} switch causes errors to be displayed as soon as they
18694 are encountered, rather than after compilation is terminated. If GNAT
18695 terminates prematurely or goes into an infinite loop, the last error
18696 message displayed may help to pinpoint the culprit.
18698 @item 
18699 Run @code{gcc} with the @code{-v} (verbose) switch. In this
18700 mode, @code{gcc} produces ongoing information about the progress of the
18701 compilation and provides the name of each procedure as code is
18702 generated. This switch allows you to find which Ada procedure was being
18703 compiled when it encountered a code generation problem.
18704 @end itemize
18706 @geindex -gnatdc switch
18709 @itemize *
18711 @item 
18712 Run @code{gcc} with the @code{-gnatdc} switch. This is a GNAT specific
18713 switch that does for the front-end what @code{-v} does
18714 for the back end. The system prints the name of each unit,
18715 either a compilation unit or nested unit, as it is being analyzed.
18717 @item 
18718 Finally, you can start
18719 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
18720 front-end of GNAT, and can be run independently (normally it is just
18721 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
18722 would on a C program (but @ref{14f,,The GNAT Debugger GDB} for caveats). The
18723 @code{where} command is the first line of attack; the variable
18724 @code{lineno} (seen by @code{print lineno}), used by the second phase of
18725 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
18726 which the execution stopped, and @code{input_file name} indicates the name of
18727 the source file.
18728 @end itemize
18730 @node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
18731 @anchor{gnat_ugn/gnat_and_program_execution id14}@anchor{164}@anchor{gnat_ugn/gnat_and_program_execution naming-conventions-for-gnat-source-files}@anchor{165}
18732 @subsection Naming Conventions for GNAT Source Files
18735 In order to examine the workings of the GNAT system, the following
18736 brief description of its organization may be helpful:
18739 @itemize *
18741 @item 
18742 Files with prefix @code{sc} contain the lexical scanner.
18744 @item 
18745 All files prefixed with @code{par} are components of the parser. The
18746 numbers correspond to chapters of the Ada Reference Manual. For example,
18747 parsing of select statements can be found in @code{par-ch9.adb}.
18749 @item 
18750 All files prefixed with @code{sem} perform semantic analysis. The
18751 numbers correspond to chapters of the Ada standard. For example, all
18752 issues involving context clauses can be found in @code{sem_ch10.adb}. In
18753 addition, some features of the language require sufficient special processing
18754 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
18755 dynamic dispatching, etc.
18757 @item 
18758 All files prefixed with @code{exp} perform normalization and
18759 expansion of the intermediate representation (abstract syntax tree, or AST).
18760 these files use the same numbering scheme as the parser and semantics files.
18761 For example, the construction of record initialization procedures is done in
18762 @code{exp_ch3.adb}.
18764 @item 
18765 The files prefixed with @code{bind} implement the binder, which
18766 verifies the consistency of the compilation, determines an order of
18767 elaboration, and generates the bind file.
18769 @item 
18770 The files @code{atree.ads} and @code{atree.adb} detail the low-level
18771 data structures used by the front-end.
18773 @item 
18774 The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
18775 the abstract syntax tree as produced by the parser.
18777 @item 
18778 The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
18779 all entities, computed during semantic analysis.
18781 @item 
18782 Library management issues are dealt with in files with prefix
18783 @code{lib}.
18785 @geindex Annex A (in Ada Reference Manual)
18787 @item 
18788 Ada files with the prefix @code{a-} are children of @code{Ada}, as
18789 defined in Annex A.
18791 @geindex Annex B (in Ada reference Manual)
18793 @item 
18794 Files with prefix @code{i-} are children of @code{Interfaces}, as
18795 defined in Annex B.
18797 @geindex System (package in Ada Reference Manual)
18799 @item 
18800 Files with prefix @code{s-} are children of @code{System}. This includes
18801 both language-defined children and GNAT run-time routines.
18803 @geindex GNAT (package)
18805 @item 
18806 Files with prefix @code{g-} are children of @code{GNAT}. These are useful
18807 general-purpose packages, fully documented in their specs. All
18808 the other @code{.c} files are modifications of common @code{gcc} files.
18809 @end itemize
18811 @node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
18812 @anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{166}@anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{167}
18813 @subsection Getting Internal Debugging Information
18816 Most compilers have internal debugging switches and modes. GNAT
18817 does also, except GNAT internal debugging switches and modes are not
18818 secret. A summary and full description of all the compiler and binder
18819 debug flags are in the file @code{debug.adb}. You must obtain the
18820 sources of the compiler to see the full detailed effects of these flags.
18822 The switches that print the source of the program (reconstructed from
18823 the internal tree) are of general interest for user programs, as are the
18824 options to print
18825 the full internal tree, and the entity table (the symbol table
18826 information). The reconstructed source provides a readable version of the
18827 program after the front-end has completed analysis and  expansion,
18828 and is useful when studying the performance of specific constructs.
18829 For example, constraint checks are indicated, complex aggregates
18830 are replaced with loops and assignments, and tasking primitives
18831 are replaced with run-time calls.
18833 @geindex traceback
18835 @geindex stack traceback
18837 @geindex stack unwinding
18839 @node Stack Traceback,Pretty-Printers for the GNAT runtime,Getting Internal Debugging Information,Running and Debugging Ada Programs
18840 @anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{168}@anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{169}
18841 @subsection Stack Traceback
18844 Traceback is a mechanism to display the sequence of subprogram calls that
18845 leads to a specified execution point in a program. Often (but not always)
18846 the execution point is an instruction at which an exception has been raised.
18847 This mechanism is also known as @emph{stack unwinding} because it obtains
18848 its information by scanning the run-time stack and recovering the activation
18849 records of all active subprograms. Stack unwinding is one of the most
18850 important tools for program debugging.
18852 The first entry stored in traceback corresponds to the deepest calling level,
18853 that is to say the subprogram currently executing the instruction
18854 from which we want to obtain the traceback.
18856 Note that there is no runtime performance penalty when stack traceback
18857 is enabled, and no exception is raised during program execution.
18859 @geindex traceback
18860 @geindex non-symbolic
18862 @menu
18863 * Non-Symbolic Traceback:: 
18864 * Symbolic Traceback:: 
18866 @end menu
18868 @node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
18869 @anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{16a}@anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{16b}
18870 @subsubsection Non-Symbolic Traceback
18873 Note: this feature is not supported on all platforms. See
18874 @code{GNAT.Traceback} spec in @code{g-traceb.ads}
18875 for a complete list of supported platforms.
18877 @subsubheading Tracebacks From an Unhandled Exception
18880 A runtime non-symbolic traceback is a list of addresses of call instructions.
18881 To enable this feature you must use the @code{-E}
18882 @code{gnatbind} option. With this option a stack traceback is stored as part
18883 of exception information. You can retrieve this information using the
18884 @code{addr2line} tool.
18886 Here is a simple example:
18888 @quotation
18890 @example
18891 procedure STB is
18893    procedure P1 is
18894    begin
18895       raise Constraint_Error;
18896    end P1;
18898    procedure P2 is
18899    begin
18900       P1;
18901    end P2;
18903 begin
18904    P2;
18905 end STB;
18906 @end example
18908 @example
18909 $ gnatmake stb -bargs -E
18910 $ stb
18912 Execution terminated by unhandled exception
18913 Exception name: CONSTRAINT_ERROR
18914 Message: stb.adb:5
18915 Call stack traceback locations:
18916 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
18917 @end example
18918 @end quotation
18920 As we see the traceback lists a sequence of addresses for the unhandled
18921 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
18922 guess that this exception come from procedure P1. To translate these
18923 addresses into the source lines where the calls appear, the
18924 @code{addr2line} tool, described below, is invaluable. The use of this tool
18925 requires the program to be compiled with debug information.
18927 @quotation
18929 @example
18930 $ gnatmake -g stb -bargs -E
18931 $ stb
18933 Execution terminated by unhandled exception
18934 Exception name: CONSTRAINT_ERROR
18935 Message: stb.adb:5
18936 Call stack traceback locations:
18937 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
18939 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
18940    0x4011f1 0x77e892a4
18942 00401373 at d:/stb/stb.adb:5
18943 0040138B at d:/stb/stb.adb:10
18944 0040139C at d:/stb/stb.adb:14
18945 00401335 at d:/stb/b~stb.adb:104
18946 004011C4 at /build/.../crt1.c:200
18947 004011F1 at /build/.../crt1.c:222
18948 77E892A4 in ?? at ??:0
18949 @end example
18950 @end quotation
18952 The @code{addr2line} tool has several other useful options:
18954 @quotation
18957 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
18958 @item
18960 @code{--functions}
18962 @tab
18964 to get the function name corresponding to any location
18966 @item
18968 @code{--demangle=gnat}
18970 @tab
18972 to use the gnat decoding mode for the function names.
18973 Note that for binutils version 2.9.x the option is
18974 simply @code{--demangle}.
18976 @end multitable
18979 @example
18980 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
18981    0x40139c 0x401335 0x4011c4 0x4011f1
18983 00401373 in stb.p1 at d:/stb/stb.adb:5
18984 0040138B in stb.p2 at d:/stb/stb.adb:10
18985 0040139C in stb at d:/stb/stb.adb:14
18986 00401335 in main at d:/stb/b~stb.adb:104
18987 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
18988 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
18989 @end example
18990 @end quotation
18992 From this traceback we can see that the exception was raised in
18993 @code{stb.adb} at line 5, which was reached from a procedure call in
18994 @code{stb.adb} at line 10, and so on. The @code{b~std.adb} is the binder file,
18995 which contains the call to the main program.
18996 @ref{10e,,Running gnatbind}. The remaining entries are assorted runtime routines,
18997 and the output will vary from platform to platform.
18999 It is also possible to use @code{GDB} with these traceback addresses to debug
19000 the program. For example, we can break at a given code location, as reported
19001 in the stack traceback:
19003 @quotation
19005 @example
19006 $ gdb -nw stb
19007 @end example
19008 @end quotation
19010 Furthermore, this feature is not implemented inside Windows DLL. Only
19011 the non-symbolic traceback is reported in this case.
19013 @quotation
19015 @example
19016 (gdb) break *0x401373
19017 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19018 @end example
19019 @end quotation
19021 It is important to note that the stack traceback addresses
19022 do not change when debug information is included. This is particularly useful
19023 because it makes it possible to release software without debug information (to
19024 minimize object size), get a field report that includes a stack traceback
19025 whenever an internal bug occurs, and then be able to retrieve the sequence
19026 of calls with the same program compiled with debug information.
19028 @subsubheading Tracebacks From Exception Occurrences
19031 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
19032 The stack traceback is attached to the exception information string, and can
19033 be retrieved in an exception handler within the Ada program, by means of the
19034 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19036 @quotation
19038 @example
19039 with Ada.Text_IO;
19040 with Ada.Exceptions;
19042 procedure STB is
19044    use Ada;
19045    use Ada.Exceptions;
19047    procedure P1 is
19048       K : Positive := 1;
19049    begin
19050       K := K - 1;
19051    exception
19052       when E : others =>
19053          Text_IO.Put_Line (Exception_Information (E));
19054    end P1;
19056    procedure P2 is
19057    begin
19058       P1;
19059    end P2;
19061 begin
19062    P2;
19063 end STB;
19064 @end example
19065 @end quotation
19067 This program will output:
19069 @quotation
19071 @example
19072 $ stb
19074 Exception name: CONSTRAINT_ERROR
19075 Message: stb.adb:12
19076 Call stack traceback locations:
19077 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19078 @end example
19079 @end quotation
19081 @subsubheading Tracebacks From Anywhere in a Program
19084 It is also possible to retrieve a stack traceback from anywhere in a
19085 program. For this you need to
19086 use the @code{GNAT.Traceback} API. This package includes a procedure called
19087 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19088 display procedures described below. It is not necessary to use the
19089 @code{-E} @code{gnatbind} option in this case, because the stack traceback mechanism
19090 is invoked explicitly.
19092 In the following example we compute a traceback at a specific location in
19093 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19094 convert addresses to strings:
19096 @quotation
19098 @example
19099 with Ada.Text_IO;
19100 with GNAT.Traceback;
19101 with GNAT.Debug_Utilities;
19103 procedure STB is
19105    use Ada;
19106    use GNAT;
19107    use GNAT.Traceback;
19109    procedure P1 is
19110       TB  : Tracebacks_Array (1 .. 10);
19111       --  We are asking for a maximum of 10 stack frames.
19112       Len : Natural;
19113       --  Len will receive the actual number of stack frames returned.
19114    begin
19115       Call_Chain (TB, Len);
19117       Text_IO.Put ("In STB.P1 : ");
19119       for K in 1 .. Len loop
19120          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19121          Text_IO.Put (' ');
19122       end loop;
19124       Text_IO.New_Line;
19125    end P1;
19127    procedure P2 is
19128    begin
19129       P1;
19130    end P2;
19132 begin
19133    P2;
19134 end STB;
19135 @end example
19137 @example
19138 $ gnatmake -g stb
19139 $ stb
19141 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19142 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19143 @end example
19144 @end quotation
19146 You can then get further information by invoking the @code{addr2line}
19147 tool as described earlier (note that the hexadecimal addresses
19148 need to be specified in C format, with a leading ‘0x’).
19150 @geindex traceback
19151 @geindex symbolic
19153 @node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
19154 @anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{16c}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{16d}
19155 @subsubsection Symbolic Traceback
19158 A symbolic traceback is a stack traceback in which procedure names are
19159 associated with each code location.
19161 Note that this feature is not supported on all platforms. See
19162 @code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
19163 list of currently supported platforms.
19165 Note that the symbolic traceback requires that the program be compiled
19166 with debug information. If it is not compiled with debug information
19167 only the non-symbolic information will be valid.
19169 @subsubheading Tracebacks From Exception Occurrences
19172 Here is an example:
19174 @quotation
19176 @example
19177 with Ada.Text_IO;
19178 with GNAT.Traceback.Symbolic;
19180 procedure STB is
19182    procedure P1 is
19183    begin
19184       raise Constraint_Error;
19185    end P1;
19187    procedure P2 is
19188    begin
19189       P1;
19190    end P2;
19192    procedure P3 is
19193    begin
19194       P2;
19195    end P3;
19197 begin
19198    P3;
19199 exception
19200    when E : others =>
19201       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19202 end STB;
19203 @end example
19205 @example
19206 $ gnatmake -g .\stb -bargs -E
19207 $ stb
19209 0040149F in stb.p1 at stb.adb:8
19210 004014B7 in stb.p2 at stb.adb:13
19211 004014CF in stb.p3 at stb.adb:18
19212 004015DD in ada.stb at stb.adb:22
19213 00401461 in main at b~stb.adb:168
19214 004011C4 in __mingw_CRTStartup at crt1.c:200
19215 004011F1 in mainCRTStartup at crt1.c:222
19216 77E892A4 in ?? at ??:0
19217 @end example
19218 @end quotation
19220 In the above example the @code{.\} syntax in the @code{gnatmake} command
19221 is currently required by @code{addr2line} for files that are in
19222 the current working directory.
19223 Moreover, the exact sequence of linker options may vary from platform
19224 to platform.
19225 The above @code{-largs} section is for Windows platforms. By contrast,
19226 under Unix there is no need for the @code{-largs} section.
19227 Differences across platforms are due to details of linker implementation.
19229 @subsubheading Tracebacks From Anywhere in a Program
19232 It is possible to get a symbolic stack traceback
19233 from anywhere in a program, just as for non-symbolic tracebacks.
19234 The first step is to obtain a non-symbolic
19235 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19236 information. Here is an example:
19238 @quotation
19240 @example
19241 with Ada.Text_IO;
19242 with GNAT.Traceback;
19243 with GNAT.Traceback.Symbolic;
19245 procedure STB is
19247    use Ada;
19248    use GNAT.Traceback;
19249    use GNAT.Traceback.Symbolic;
19251    procedure P1 is
19252       TB  : Tracebacks_Array (1 .. 10);
19253       --  We are asking for a maximum of 10 stack frames.
19254       Len : Natural;
19255       --  Len will receive the actual number of stack frames returned.
19256    begin
19257       Call_Chain (TB, Len);
19258       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19259    end P1;
19261    procedure P2 is
19262    begin
19263       P1;
19264    end P2;
19266 begin
19267    P2;
19268 end STB;
19269 @end example
19270 @end quotation
19272 @subsubheading Automatic Symbolic Tracebacks
19275 Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
19276 in @code{gprbuild -g ... -bargs -Es}).
19277 This will cause the Exception_Information to contain a symbolic traceback,
19278 which will also be printed if an unhandled exception terminates the
19279 program.
19281 @node Pretty-Printers for the GNAT runtime,,Stack Traceback,Running and Debugging Ada Programs
19282 @anchor{gnat_ugn/gnat_and_program_execution id19}@anchor{16e}@anchor{gnat_ugn/gnat_and_program_execution pretty-printers-for-the-gnat-runtime}@anchor{16f}
19283 @subsection Pretty-Printers for the GNAT runtime
19286 As discussed in @cite{Calling User-Defined Subprograms}, GDB’s
19287 @code{print} command only knows about the physical layout of program data
19288 structures and therefore normally displays only low-level dumps, which
19289 are often hard to understand.
19291 An example of this is when trying to display the contents of an Ada
19292 standard container, such as @code{Ada.Containers.Ordered_Maps.Map}:
19294 @quotation
19296 @example
19297 with Ada.Containers.Ordered_Maps;
19299 procedure PP is
19300    package Int_To_Nat is
19301       new Ada.Containers.Ordered_Maps (Integer, Natural);
19303    Map : Int_To_Nat.Map;
19304 begin
19305    Map.Insert (1, 10);
19306    Map.Insert (2, 20);
19307    Map.Insert (3, 30);
19309    Map.Clear; --  BREAK HERE
19310 end PP;
19311 @end example
19312 @end quotation
19314 When this program is built with debugging information and run under
19315 GDB up to the @code{Map.Clear} statement, trying to print @code{Map} will
19316 yield information that is only relevant to the developers of our standard
19317 containers:
19319 @quotation
19321 @example
19322 (gdb) print map
19323 $1 = (
19324   tree => (
19325     first => 0x64e010,
19326     last => 0x64e070,
19327     root => 0x64e040,
19328     length => 3,
19329     tc => (
19330       busy => 0,
19331       lock => 0
19332     )
19333   )
19335 @end example
19336 @end quotation
19338 Fortunately, GDB has a feature called pretty-printers@footnote{http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Introduction},
19339 which allows customizing how GDB displays data structures. The GDB
19340 shipped with GNAT embeds such pretty-printers for the most common
19341 containers in the standard library.  To enable them, either run the
19342 following command manually under GDB or add it to your @code{.gdbinit} file:
19344 @quotation
19346 @example
19347 python import gnatdbg; gnatdbg.setup()
19348 @end example
19349 @end quotation
19351 Once this is done, GDB’s @code{print} command will automatically use
19352 these pretty-printers when appropriate. Using the previous example:
19354 @quotation
19356 @example
19357 (gdb) print map
19358 $1 = pp.int_to_nat.map of length 3 = @{
19359   [1] = 10,
19360   [2] = 20,
19361   [3] = 30
19363 @end example
19364 @end quotation
19366 Pretty-printers are invoked each time GDB tries to display a value,
19367 including when displaying the arguments of a called subprogram (in
19368 GDB’s @code{backtrace} command) or when printing the value returned by a
19369 function (in GDB’s @code{finish} command).
19371 To display a value without involving pretty-printers, @code{print} can be
19372 invoked with its @code{/r} option:
19374 @quotation
19376 @example
19377 (gdb) print/r map
19378 $1 = (
19379   tree => (...
19380 @end example
19381 @end quotation
19383 Finer control of pretty-printers is also possible: see GDB's online documentation@footnote{http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Commands}
19384 for more information.
19386 @geindex Profiling
19388 @node Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
19389 @anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{170}@anchor{gnat_ugn/gnat_and_program_execution profiling}@anchor{147}
19390 @section Profiling
19393 This section describes how to use the @code{gprof} profiler tool on Ada programs.
19395 @geindex gprof
19397 @geindex Profiling
19399 @menu
19400 * Profiling an Ada Program with gprof:: 
19402 @end menu
19404 @node Profiling an Ada Program with gprof,,,Profiling
19405 @anchor{gnat_ugn/gnat_and_program_execution id21}@anchor{171}@anchor{gnat_ugn/gnat_and_program_execution profiling-an-ada-program-with-gprof}@anchor{172}
19406 @subsection Profiling an Ada Program with gprof
19409 This section is not meant to be an exhaustive documentation of @code{gprof}.
19410 Full documentation for it can be found in the @cite{GNU Profiler User’s Guide}
19411 documentation that is part of this GNAT distribution.
19413 Profiling a program helps determine the parts of a program that are executed
19414 most often, and are therefore the most time-consuming.
19416 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
19417 better handle Ada programs and multitasking.
19418 It is currently supported on the following platforms
19421 @itemize *
19423 @item 
19424 linux x86/x86_64
19426 @item 
19427 windows x86
19428 @end itemize
19430 In order to profile a program using @code{gprof}, several steps are needed:
19433 @enumerate 
19435 @item 
19436 Instrument the code, which requires a full recompilation of the project with the
19437 proper switches.
19439 @item 
19440 Execute the program under the analysis conditions, i.e. with the desired
19441 input.
19443 @item 
19444 Analyze the results using the @code{gprof} tool.
19445 @end enumerate
19447 The following sections detail the different steps, and indicate how
19448 to interpret the results.
19450 @menu
19451 * Compilation for profiling:: 
19452 * Program execution:: 
19453 * Running gprof:: 
19454 * Interpretation of profiling results:: 
19456 @end menu
19458 @node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
19459 @anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{173}@anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{174}
19460 @subsubsection Compilation for profiling
19463 @geindex -pg (gcc)
19464 @geindex for profiling
19466 @geindex -pg (gnatlink)
19467 @geindex for profiling
19469 In order to profile a program the first step is to tell the compiler
19470 to generate the necessary profiling information. The compiler switch to be used
19471 is @code{-pg}, which must be added to other compilation switches. This
19472 switch needs to be specified both during compilation and link stages, and can
19473 be specified once when using gnatmake:
19475 @quotation
19477 @example
19478 $ gnatmake -f -pg -P my_project
19479 @end example
19480 @end quotation
19482 Note that only the objects that were compiled with the @code{-pg} switch will
19483 be profiled; if you need to profile your whole project, use the @code{-f}
19484 gnatmake switch to force full recompilation.
19486 @node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
19487 @anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{175}@anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{176}
19488 @subsubsection Program execution
19491 Once the program has been compiled for profiling, you can run it as usual.
19493 The only constraint imposed by profiling is that the program must terminate
19494 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
19495 properly analyzed.
19497 Once the program completes execution, a data file called @code{gmon.out} is
19498 generated in the directory where the program was launched from. If this file
19499 already exists, it will be overwritten.
19501 @node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
19502 @anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{177}@anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{178}
19503 @subsubsection Running gprof
19506 The @code{gprof} tool is called as follow:
19508 @quotation
19510 @example
19511 $ gprof my_prog gmon.out
19512 @end example
19513 @end quotation
19515 or simply:
19517 @quotation
19519 @example
19520 $ gprof my_prog
19521 @end example
19522 @end quotation
19524 The complete form of the gprof command line is the following:
19526 @quotation
19528 @example
19529 $ gprof [switches] [executable [data-file]]
19530 @end example
19531 @end quotation
19533 @code{gprof} supports numerous switches. The order of these
19534 switch does not matter. The full list of options can be found in
19535 the GNU Profiler User’s Guide documentation that comes with this documentation.
19537 The following is the subset of those switches that is most relevant:
19539 @geindex --demangle (gprof)
19542 @table @asis
19544 @item @code{--demangle[=@emph{style}]}, @code{--no-demangle}
19546 These options control whether symbol names should be demangled when
19547 printing output.  The default is to demangle C++ symbols.  The
19548 @code{--no-demangle} option may be used to turn off demangling. Different
19549 compilers have different mangling styles.  The optional demangling style
19550 argument can be used to choose an appropriate demangling style for your
19551 compiler, in particular Ada symbols generated by GNAT can be demangled using
19552 @code{--demangle=gnat}.
19553 @end table
19555 @geindex -e (gprof)
19558 @table @asis
19560 @item @code{-e @emph{function_name}}
19562 The @code{-e @emph{function}} option tells @code{gprof} not to print
19563 information about the function @code{function_name} (and its
19564 children…) in the call graph.  The function will still be listed
19565 as a child of any functions that call it, but its index number will be
19566 shown as @code{[not printed]}.  More than one @code{-e} option may be
19567 given; only one @code{function_name} may be indicated with each @code{-e}
19568 option.
19569 @end table
19571 @geindex -E (gprof)
19574 @table @asis
19576 @item @code{-E @emph{function_name}}
19578 The @code{-E @emph{function}} option works like the @code{-e} option, but
19579 execution time spent in the function (and children who were not called from
19580 anywhere else), will not be used to compute the percentages-of-time for
19581 the call graph.  More than one @code{-E} option may be given; only one
19582 @code{function_name} may be indicated with each @code{-E`} option.
19583 @end table
19585 @geindex -f (gprof)
19588 @table @asis
19590 @item @code{-f @emph{function_name}}
19592 The @code{-f @emph{function}} option causes @code{gprof} to limit the
19593 call graph to the function @code{function_name} and its children (and
19594 their children…).  More than one @code{-f} option may be given;
19595 only one @code{function_name} may be indicated with each @code{-f}
19596 option.
19597 @end table
19599 @geindex -F (gprof)
19602 @table @asis
19604 @item @code{-F @emph{function_name}}
19606 The @code{-F @emph{function}} option works like the @code{-f} option, but
19607 only time spent in the function and its children (and their
19608 children…) will be used to determine total-time and
19609 percentages-of-time for the call graph.  More than one @code{-F} option
19610 may be given; only one @code{function_name} may be indicated with each
19611 @code{-F} option.  The @code{-F} option overrides the @code{-E} option.
19612 @end table
19614 @node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
19615 @anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{179}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{17a}
19616 @subsubsection Interpretation of profiling results
19619 The results of the profiling analysis are represented by two arrays: the
19620 ‘flat profile’ and the ‘call graph’. Full documentation of those outputs
19621 can be found in the GNU Profiler User’s Guide.
19623 The flat profile shows the time spent in each function of the program, and how
19624 many time it has been called. This allows you to locate easily the most
19625 time-consuming functions.
19627 The call graph shows, for each subprogram, the subprograms that call it,
19628 and the subprograms that it calls. It also provides an estimate of the time
19629 spent in each of those callers/called subprograms.
19631 @node Improving Performance,Overflow Check Handling in GNAT,Profiling,GNAT and Program Execution
19632 @anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{148}@anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{17b}
19633 @section Improving Performance
19636 @geindex Improving performance
19638 This section presents several topics related to program performance.
19639 It first describes some of the tradeoffs that need to be considered
19640 and some of the techniques for making your program run faster.
19642 It then documents the unused subprogram/data elimination feature,
19643 which can reduce the size of program executables.
19645 @menu
19646 * Performance Considerations:: 
19647 * Text_IO Suggestions:: 
19648 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
19650 @end menu
19652 @node Performance Considerations,Text_IO Suggestions,,Improving Performance
19653 @anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{17c}@anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{17d}
19654 @subsection Performance Considerations
19657 The GNAT system provides a number of options that allow a trade-off
19658 between
19661 @itemize *
19663 @item 
19664 performance of the generated code
19666 @item 
19667 speed of compilation
19669 @item 
19670 minimization of dependences and recompilation
19672 @item 
19673 the degree of run-time checking.
19674 @end itemize
19676 The defaults (if no options are selected) aim at improving the speed
19677 of compilation and minimizing dependences, at the expense of performance
19678 of the generated code:
19681 @itemize *
19683 @item 
19684 no optimization
19686 @item 
19687 no inlining of subprogram calls
19689 @item 
19690 all run-time checks enabled except overflow and elaboration checks
19691 @end itemize
19693 These options are suitable for most program development purposes. This
19694 section describes how you can modify these choices, and also provides
19695 some guidelines on debugging optimized code.
19697 @menu
19698 * Controlling Run-Time Checks:: 
19699 * Use of Restrictions:: 
19700 * Optimization Levels:: 
19701 * Debugging Optimized Code:: 
19702 * Inlining of Subprograms:: 
19703 * Floating Point Operations:: 
19704 * Vectorization of loops:: 
19705 * Other Optimization Switches:: 
19706 * Optimization and Strict Aliasing:: 
19707 * Aliased Variables and Optimization:: 
19708 * Atomic Variables and Optimization:: 
19709 * Passive Task Optimization:: 
19711 @end menu
19713 @node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
19714 @anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{17e}@anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{17f}
19715 @subsubsection Controlling Run-Time Checks
19718 By default, GNAT generates all run-time checks, except stack overflow
19719 checks, and checks for access before elaboration on subprogram
19720 calls. The latter are not required in default mode, because all
19721 necessary checking is done at compile time.
19723 @geindex -gnatp (gcc)
19725 @geindex -gnato (gcc)
19727 The gnat switch, @code{-gnatp} allows this default to be modified. See
19728 @ref{ea,,Run-Time Checks}.
19730 Our experience is that the default is suitable for most development
19731 purposes.
19733 Elaboration checks are off by default, and also not needed by default, since
19734 GNAT uses a static elaboration analysis approach that avoids the need for
19735 run-time checking. This manual contains a full chapter discussing the issue
19736 of elaboration checks, and if the default is not satisfactory for your use,
19737 you should read this chapter.
19739 For validity checks, the minimal checks required by the Ada Reference
19740 Manual (for case statements and assignments to array elements) are on
19741 by default. These can be suppressed by use of the @code{-gnatVn} switch.
19742 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
19743 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
19744 it may be reasonable to routinely use @code{-gnatVn}. Validity checks
19745 are also suppressed entirely if @code{-gnatp} is used.
19747 @geindex Overflow checks
19749 @geindex Checks
19750 @geindex overflow
19752 @geindex Suppress
19754 @geindex Unsuppress
19756 @geindex pragma Suppress
19758 @geindex pragma Unsuppress
19760 Note that the setting of the switches controls the default setting of
19761 the checks. They may be modified using either @code{pragma Suppress} (to
19762 remove checks) or @code{pragma Unsuppress} (to add back suppressed
19763 checks) in the program source.
19765 @node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
19766 @anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{180}@anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{181}
19767 @subsubsection Use of Restrictions
19770 The use of pragma Restrictions allows you to control which features are
19771 permitted in your program. Apart from the obvious point that if you avoid
19772 relatively expensive features like finalization (enforceable by the use
19773 of pragma Restrictions (No_Finalization)), the use of this pragma does not
19774 affect the generated code in most cases.
19776 One notable exception to this rule is that the possibility of task abort
19777 results in some distributed overhead, particularly if finalization or
19778 exception handlers are used. The reason is that certain sections of code
19779 have to be marked as non-abortable.
19781 If you use neither the @code{abort} statement, nor asynchronous transfer
19782 of control (@code{select ... then abort}), then this distributed overhead
19783 is removed, which may have a general positive effect in improving
19784 overall performance.  Especially code involving frequent use of tasking
19785 constructs and controlled types will show much improved performance.
19786 The relevant restrictions pragmas are
19788 @quotation
19790 @example
19791 pragma Restrictions (No_Abort_Statements);
19792 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
19793 @end example
19794 @end quotation
19796 It is recommended that these restriction pragmas be used if possible. Note
19797 that this also means that you can write code without worrying about the
19798 possibility of an immediate abort at any point.
19800 @node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
19801 @anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{182}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{ed}
19802 @subsubsection Optimization Levels
19805 @geindex -O (gcc)
19807 Without any optimization option,
19808 the compiler’s goal is to reduce the cost of
19809 compilation and to make debugging produce the expected results.
19810 Statements are independent: if you stop the program with a breakpoint between
19811 statements, you can then assign a new value to any variable or change
19812 the program counter to any other statement in the subprogram and get exactly
19813 the results you would expect from the source code.
19815 Turning on optimization makes the compiler attempt to improve the
19816 performance and/or code size at the expense of compilation time and
19817 possibly the ability to debug the program.
19819 If you use multiple
19820 -O options, with or without level numbers,
19821 the last such option is the one that is effective.
19823 The default is optimization off. This results in the fastest compile
19824 times, but GNAT makes absolutely no attempt to optimize, and the
19825 generated programs are considerably larger and slower than when
19826 optimization is enabled. You can use the
19827 @code{-O} switch (the permitted forms are @code{-O0}, @code{-O1}
19828 @code{-O2}, @code{-O3}, and @code{-Os})
19829 to @code{gcc} to control the optimization level:
19832 @itemize *
19834 @item 
19836 @table @asis
19838 @item @code{-O0}
19840 No optimization (the default);
19841 generates unoptimized code but has
19842 the fastest compilation time.
19844 Note that many other compilers do substantial optimization even
19845 if ‘no optimization’ is specified. With gcc, it is very unusual
19846 to use @code{-O0} for production if execution time is of any concern,
19847 since @code{-O0} means (almost) no optimization. This difference
19848 between gcc and other compilers should be kept in mind when
19849 doing performance comparisons.
19850 @end table
19852 @item 
19854 @table @asis
19856 @item @code{-O1}
19858 Moderate optimization;
19859 optimizes reasonably well but does not
19860 degrade compilation time significantly.
19861 @end table
19863 @item 
19865 @table @asis
19867 @item @code{-O2}
19869 Full optimization;
19870 generates highly optimized code and has
19871 the slowest compilation time.
19872 @end table
19874 @item 
19876 @table @asis
19878 @item @code{-O3}
19880 Full optimization as in @code{-O2};
19881 also uses more aggressive automatic inlining of subprograms within a unit
19882 (@ref{100,,Inlining of Subprograms}) and attempts to vectorize loops.
19883 @end table
19885 @item 
19887 @table @asis
19889 @item @code{-Os}
19891 Optimize space usage (code and data) of resulting program.
19892 @end table
19893 @end itemize
19895 Higher optimization levels perform more global transformations on the
19896 program and apply more expensive analysis algorithms in order to generate
19897 faster and more compact code. The price in compilation time, and the
19898 resulting improvement in execution time,
19899 both depend on the particular application and the hardware environment.
19900 You should experiment to find the best level for your application.
19902 Since the precise set of optimizations done at each level will vary from
19903 release to release (and sometime from target to target), it is best to think
19904 of the optimization settings in general terms.
19905 See the @emph{Options That Control Optimization} section in
19906 @cite{Using the GNU Compiler Collection (GCC)}
19907 for details about
19908 the @code{-O} settings and a number of @code{-f} options that
19909 individually enable or disable specific optimizations.
19911 Unlike some other compilation systems, @code{gcc} has
19912 been tested extensively at all optimization levels. There are some bugs
19913 which appear only with optimization turned on, but there have also been
19914 bugs which show up only in @emph{unoptimized} code. Selecting a lower
19915 level of optimization does not improve the reliability of the code
19916 generator, which in practice is highly reliable at all optimization
19917 levels.
19919 Note regarding the use of @code{-O3}: The use of this optimization level
19920 ought not to be automatically preferred over that of level @code{-O2},
19921 since it often results in larger executables which may run more slowly.
19922 See further discussion of this point in @ref{100,,Inlining of Subprograms}.
19924 @node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
19925 @anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{183}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{184}
19926 @subsubsection Debugging Optimized Code
19929 @geindex Debugging optimized code
19931 @geindex Optimization and debugging
19933 Although it is possible to do a reasonable amount of debugging at
19934 nonzero optimization levels,
19935 the higher the level the more likely that
19936 source-level constructs will have been eliminated by optimization.
19937 For example, if a loop is strength-reduced, the loop
19938 control variable may be completely eliminated and thus cannot be
19939 displayed in the debugger.
19940 This can only happen at @code{-O2} or @code{-O3}.
19941 Explicit temporary variables that you code might be eliminated at
19942 level @code{-O1} or higher.
19944 @geindex -g (gcc)
19946 The use of the @code{-g} switch,
19947 which is needed for source-level debugging,
19948 affects the size of the program executable on disk,
19949 and indeed the debugging information can be quite large.
19950 However, it has no effect on the generated code (and thus does not
19951 degrade performance)
19953 Since the compiler generates debugging tables for a compilation unit before
19954 it performs optimizations, the optimizing transformations may invalidate some
19955 of the debugging data.  You therefore need to anticipate certain
19956 anomalous situations that may arise while debugging optimized code.
19957 These are the most common cases:
19960 @itemize *
19962 @item 
19963 @emph{The ‘hopping Program Counter’:}  Repeated @code{step} or @code{next}
19964 commands show
19965 the PC bouncing back and forth in the code.  This may result from any of
19966 the following optimizations:
19969 @itemize -
19971 @item 
19972 @emph{Common subexpression elimination:} using a single instance of code for a
19973 quantity that the source computes several times.  As a result you
19974 may not be able to stop on what looks like a statement.
19976 @item 
19977 @emph{Invariant code motion:} moving an expression that does not change within a
19978 loop, to the beginning of the loop.
19980 @item 
19981 @emph{Instruction scheduling:} moving instructions so as to
19982 overlap loads and stores (typically) with other code, or in
19983 general to move computations of values closer to their uses. Often
19984 this causes you to pass an assignment statement without the assignment
19985 happening and then later bounce back to the statement when the
19986 value is actually needed.  Placing a breakpoint on a line of code
19987 and then stepping over it may, therefore, not always cause all the
19988 expected side-effects.
19989 @end itemize
19991 @item 
19992 @emph{The ‘big leap’:} More commonly known as @emph{cross-jumping}, in which
19993 two identical pieces of code are merged and the program counter suddenly
19994 jumps to a statement that is not supposed to be executed, simply because
19995 it (and the code following) translates to the same thing as the code
19996 that @emph{was} supposed to be executed.  This effect is typically seen in
19997 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
19998 a @code{break} in a C @code{switch} statement.
20000 @item 
20001 @emph{The ‘roving variable’:} The symptom is an unexpected value in a variable.
20002 There are various reasons for this effect:
20005 @itemize -
20007 @item 
20008 In a subprogram prologue, a parameter may not yet have been moved to its
20009 ‘home’.
20011 @item 
20012 A variable may be dead, and its register re-used.  This is
20013 probably the most common cause.
20015 @item 
20016 As mentioned above, the assignment of a value to a variable may
20017 have been moved.
20019 @item 
20020 A variable may be eliminated entirely by value propagation or
20021 other means.  In this case, GCC may incorrectly generate debugging
20022 information for the variable
20023 @end itemize
20025 In general, when an unexpected value appears for a local variable or parameter
20026 you should first ascertain if that value was actually computed by
20027 your program, as opposed to being incorrectly reported by the debugger.
20028 Record fields or
20029 array elements in an object designated by an access value
20030 are generally less of a problem, once you have ascertained that the access
20031 value is sensible.
20032 Typically, this means checking variables in the preceding code and in the
20033 calling subprogram to verify that the value observed is explainable from other
20034 values (one must apply the procedure recursively to those
20035 other values); or re-running the code and stopping a little earlier
20036 (perhaps before the call) and stepping to better see how the variable obtained
20037 the value in question; or continuing to step @emph{from} the point of the
20038 strange value to see if code motion had simply moved the variable’s
20039 assignments later.
20040 @end itemize
20042 In light of such anomalies, a recommended technique is to use @code{-O0}
20043 early in the software development cycle, when extensive debugging capabilities
20044 are most needed, and then move to @code{-O1} and later @code{-O2} as
20045 the debugger becomes less critical.
20046 Whether to use the @code{-g} switch in the release version is
20047 a release management issue.
20048 Note that if you use @code{-g} you can then use the @code{strip} program
20049 on the resulting executable,
20050 which removes both debugging information and global symbols.
20052 @node Inlining of Subprograms,Floating Point Operations,Debugging Optimized Code,Performance Considerations
20053 @anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{185}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{100}
20054 @subsubsection Inlining of Subprograms
20057 A call to a subprogram in the current unit is inlined if all the
20058 following conditions are met:
20061 @itemize *
20063 @item 
20064 The optimization level is at least @code{-O1}.
20066 @item 
20067 The called subprogram is suitable for inlining: It must be small enough
20068 and not contain something that @code{gcc} cannot support in inlined
20069 subprograms.
20071 @geindex pragma Inline
20073 @geindex Inline
20075 @item 
20076 Any one of the following applies: @code{pragma Inline} is applied to the
20077 subprogram; the subprogram is local to the unit and called once from
20078 within it; the subprogram is small and optimization level @code{-O2} is
20079 specified; optimization level @code{-O3} is specified.
20080 @end itemize
20082 Calls to subprograms in @emph{with}ed units are normally not inlined.
20083 To achieve actual inlining (that is, replacement of the call by the code
20084 in the body of the subprogram), the following conditions must all be true:
20087 @itemize *
20089 @item 
20090 The optimization level is at least @code{-O1}.
20092 @item 
20093 The called subprogram is suitable for inlining: It must be small enough
20094 and not contain something that @code{gcc} cannot support in inlined
20095 subprograms.
20097 @item 
20098 There is a @code{pragma Inline} for the subprogram.
20100 @item 
20101 The @code{-gnatn} switch is used on the command line.
20102 @end itemize
20104 Even if all these conditions are met, it may not be possible for
20105 the compiler to inline the call, due to the length of the body,
20106 or features in the body that make it impossible for the compiler
20107 to do the inlining.
20109 Note that specifying the @code{-gnatn} switch causes additional
20110 compilation dependencies. Consider the following:
20112 @quotation
20114 @example
20115 package R is
20116    procedure Q;
20117    pragma Inline (Q);
20118 end R;
20119 package body R is
20120    ...
20121 end R;
20123 with R;
20124 procedure Main is
20125 begin
20126    ...
20127    R.Q;
20128 end Main;
20129 @end example
20130 @end quotation
20132 With the default behavior (no @code{-gnatn} switch specified), the
20133 compilation of the @code{Main} procedure depends only on its own source,
20134 @code{main.adb}, and the spec of the package in file @code{r.ads}. This
20135 means that editing the body of @code{R} does not require recompiling
20136 @code{Main}.
20138 On the other hand, the call @code{R.Q} is not inlined under these
20139 circumstances. If the @code{-gnatn} switch is present when @code{Main}
20140 is compiled, the call will be inlined if the body of @code{Q} is small
20141 enough, but now @code{Main} depends on the body of @code{R} in
20142 @code{r.adb} as well as on the spec. This means that if this body is edited,
20143 the main program must be recompiled. Note that this extra dependency
20144 occurs whether or not the call is in fact inlined by @code{gcc}.
20146 The use of front end inlining with @code{-gnatN} generates similar
20147 additional dependencies.
20149 @geindex -fno-inline (gcc)
20151 Note: The @code{-fno-inline} switch overrides all other conditions and ensures that
20152 no inlining occurs, unless requested with pragma Inline_Always for @code{gcc}
20153 back-ends. The extra dependences resulting from @code{-gnatn} will still be active,
20154 even if this switch is used to suppress the resulting inlining actions.
20156 @geindex -fno-inline-functions (gcc)
20158 Note: The @code{-fno-inline-functions} switch can be used to prevent
20159 automatic inlining of subprograms if @code{-O3} is used.
20161 @geindex -fno-inline-small-functions (gcc)
20163 Note: The @code{-fno-inline-small-functions} switch can be used to prevent
20164 automatic inlining of small subprograms if @code{-O2} is used.
20166 @geindex -fno-inline-functions-called-once (gcc)
20168 Note: The @code{-fno-inline-functions-called-once} switch
20169 can be used to prevent inlining of subprograms local to the unit
20170 and called once from within it if @code{-O1} is used.
20172 Note regarding the use of @code{-O3}: @code{-gnatn} is made up of two
20173 sub-switches @code{-gnatn1} and @code{-gnatn2} that can be directly
20174 specified in lieu of it, @code{-gnatn} being translated into one of them
20175 based on the optimization level. With @code{-O2} or below, @code{-gnatn}
20176 is equivalent to @code{-gnatn1} which activates pragma @code{Inline} with
20177 moderate inlining across modules. With @code{-O3}, @code{-gnatn} is
20178 equivalent to @code{-gnatn2} which activates pragma @code{Inline} with
20179 full inlining across modules. If you have used pragma @code{Inline} in
20180 appropriate cases, then it is usually much better to use @code{-O2}
20181 and @code{-gnatn} and avoid the use of @code{-O3} which has the additional
20182 effect of inlining subprograms you did not think should be inlined. We have
20183 found that the use of @code{-O3} may slow down the compilation and increase
20184 the code size by performing excessive inlining, leading to increased
20185 instruction cache pressure from the increased code size and thus minor
20186 performance improvements. So the bottom line here is that you should not
20187 automatically assume that @code{-O3} is better than @code{-O2}, and
20188 indeed you should use @code{-O3} only if tests show that it actually
20189 improves performance for your program.
20191 @node Floating Point Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
20192 @anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{186}@anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{187}
20193 @subsubsection Floating Point Operations
20196 @geindex Floating-Point Operations
20198 On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
20199 64-bit standard IEEE floating-point representations, and operations will
20200 use standard IEEE arithmetic as provided by the processor. On most, but
20201 not all, architectures, the attribute Machine_Overflows is False for these
20202 types, meaning that the semantics of overflow is implementation-defined.
20203 In the case of GNAT, these semantics correspond to the normal IEEE
20204 treatment of infinities and NaN (not a number) values. For example,
20205 1.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
20206 avoiding explicit overflow checks, the performance is greatly improved
20207 on many targets. However, if required, floating-point overflow can be
20208 enabled by the use of the pragma Check_Float_Overflow.
20210 Another consideration that applies specifically to x86 32-bit
20211 architectures is which form of floating-point arithmetic is used.
20212 By default the operations use the old style x86 floating-point,
20213 which implements an 80-bit extended precision form (on these
20214 architectures the type Long_Long_Float corresponds to that form).
20215 In addition, generation of efficient code in this mode means that
20216 the extended precision form will be used for intermediate results.
20217 This may be helpful in improving the final precision of a complex
20218 expression. However it means that the results obtained on the x86
20219 will be different from those on other architectures, and for some
20220 algorithms, the extra intermediate precision can be detrimental.
20222 In addition to this old-style floating-point, all modern x86 chips
20223 implement an alternative floating-point operation model referred
20224 to as SSE2. In this model there is no extended form, and furthermore
20225 execution performance is significantly enhanced. To force GNAT to use
20226 this more modern form, use both of the switches:
20228 @quotation
20230 -msse2 -mfpmath=sse
20231 @end quotation
20233 A unit compiled with these switches will automatically use the more
20234 efficient SSE2 instruction set for Float and Long_Float operations.
20235 Note that the ABI has the same form for both floating-point models,
20236 so it is permissible to mix units compiled with and without these
20237 switches.
20239 @node Vectorization of loops,Other Optimization Switches,Floating Point Operations,Performance Considerations
20240 @anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{188}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{189}
20241 @subsubsection Vectorization of loops
20244 @geindex Optimization Switches
20246 You can take advantage of the auto-vectorizer present in the @code{gcc}
20247 back end to vectorize loops with GNAT.  The corresponding command line switch
20248 is @code{-ftree-vectorize} but, as it is enabled by default at @code{-O3}
20249 and other aggressive optimizations helpful for vectorization also are enabled
20250 by default at this level, using @code{-O3} directly is recommended.
20252 You also need to make sure that the target architecture features a supported
20253 SIMD instruction set.  For example, for the x86 architecture, you should at
20254 least specify @code{-msse2} to get significant vectorization (but you don’t
20255 need to specify it for x86-64 as it is part of the base 64-bit architecture).
20256 Similarly, for the PowerPC architecture, you should specify @code{-maltivec}.
20258 The preferred loop form for vectorization is the @code{for} iteration scheme.
20259 Loops with a @code{while} iteration scheme can also be vectorized if they are
20260 very simple, but the vectorizer will quickly give up otherwise.  With either
20261 iteration scheme, the flow of control must be straight, in particular no
20262 @code{exit} statement may appear in the loop body.  The loop may however
20263 contain a single nested loop, if it can be vectorized when considered alone:
20265 @quotation
20267 @example
20268 A : array (1..4, 1..4) of Long_Float;
20269 S : array (1..4) of Long_Float;
20271 procedure Sum is
20272 begin
20273    for I in A'Range(1) loop
20274       for J in A'Range(2) loop
20275          S (I) := S (I) + A (I, J);
20276       end loop;
20277    end loop;
20278 end Sum;
20279 @end example
20280 @end quotation
20282 The vectorizable operations depend on the targeted SIMD instruction set, but
20283 the adding and some of the multiplying operators are generally supported, as
20284 well as the logical operators for modular types. Note that compiling
20285 with @code{-gnatp} might well reveal cases where some checks do thwart
20286 vectorization.
20288 Type conversions may also prevent vectorization if they involve semantics that
20289 are not directly supported by the code generator or the SIMD instruction set.
20290 A typical example is direct conversion from floating-point to integer types.
20291 The solution in this case is to use the following idiom:
20293 @quotation
20295 @example
20296 Integer (S'Truncation (F))
20297 @end example
20298 @end quotation
20300 if @code{S} is the subtype of floating-point object @code{F}.
20302 In most cases, the vectorizable loops are loops that iterate over arrays.
20303 All kinds of array types are supported, i.e. constrained array types with
20304 static bounds:
20306 @quotation
20308 @example
20309 type Array_Type is array (1 .. 4) of Long_Float;
20310 @end example
20311 @end quotation
20313 constrained array types with dynamic bounds:
20315 @quotation
20317 @example
20318 type Array_Type is array (1 .. Q.N) of Long_Float;
20320 type Array_Type is array (Q.K .. 4) of Long_Float;
20322 type Array_Type is array (Q.K .. Q.N) of Long_Float;
20323 @end example
20324 @end quotation
20326 or unconstrained array types:
20328 @quotation
20330 @example
20331 type Array_Type is array (Positive range <>) of Long_Float;
20332 @end example
20333 @end quotation
20335 The quality of the generated code decreases when the dynamic aspect of the
20336 array type increases, the worst code being generated for unconstrained array
20337 types.  This is so because, the less information the compiler has about the
20338 bounds of the array, the more fallback code it needs to generate in order to
20339 fix things up at run time.
20341 It is possible to specify that a given loop should be subject to vectorization
20342 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
20344 @quotation
20346 @example
20347 pragma Loop_Optimize (Vector);
20348 @end example
20349 @end quotation
20351 placed immediately within the loop will convey the appropriate hint to the
20352 compiler for this loop.
20354 It is also possible to help the compiler generate better vectorized code
20355 for a given loop by asserting that there are no loop-carried dependencies
20356 in the loop.  Consider for example the procedure:
20358 @quotation
20360 @example
20361 type Arr is array (1 .. 4) of Long_Float;
20363 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
20364 begin
20365   for I in Arr'Range loop
20366     R(I) := X(I) + Y(I);
20367   end loop;
20368 end;
20369 @end example
20370 @end quotation
20372 By default, the compiler cannot unconditionally vectorize the loop because
20373 assigning to a component of the array designated by R in one iteration could
20374 change the value read from the components of the array designated by X or Y
20375 in a later iteration.  As a result, the compiler will generate two versions
20376 of the loop in the object code, one vectorized and the other not vectorized,
20377 as well as a test to select the appropriate version at run time.  This can
20378 be overcome by another hint:
20380 @quotation
20382 @example
20383 pragma Loop_Optimize (Ivdep);
20384 @end example
20385 @end quotation
20387 placed immediately within the loop will tell the compiler that it can safely
20388 omit the non-vectorized version of the loop as well as the run-time test.
20390 @node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
20391 @anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{18a}@anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{18b}
20392 @subsubsection Other Optimization Switches
20395 @geindex Optimization Switches
20397 Since GNAT uses the @code{gcc} back end, all the specialized
20398 @code{gcc} optimization switches are potentially usable. These switches
20399 have not been extensively tested with GNAT but can generally be expected
20400 to work. Examples of switches in this category are @code{-funroll-loops}
20401 and the various target-specific @code{-m} options (in particular, it has
20402 been observed that @code{-march=xxx} can significantly improve performance
20403 on appropriate machines). For full details of these switches, see
20404 the @emph{Submodel Options} section in the @emph{Hardware Models and Configurations}
20405 chapter of @cite{Using the GNU Compiler Collection (GCC)}.
20407 @node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
20408 @anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{18c}@anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{e4}
20409 @subsubsection Optimization and Strict Aliasing
20412 @geindex Aliasing
20414 @geindex Strict Aliasing
20416 @geindex No_Strict_Aliasing
20418 The strong typing capabilities of Ada allow an optimizer to generate
20419 efficient code in situations where other languages would be forced to
20420 make worst case assumptions preventing such optimizations. Consider
20421 the following example:
20423 @quotation
20425 @example
20426 procedure R is
20427    type Int1 is new Integer;
20428    type Int2 is new Integer;
20429    type Int1A is access Int1;
20430    type Int2A is access Int2;
20431    Int1V : Int1A;
20432    Int2V : Int2A;
20433    ...
20435 begin
20436    ...
20437    for J in Data'Range loop
20438       if Data (J) = Int1V.all then
20439          Int2V.all := Int2V.all + 1;
20440       end if;
20441    end loop;
20442    ...
20443 end R;
20444 @end example
20445 @end quotation
20447 In this example, since the variable @code{Int1V} can only access objects
20448 of type @code{Int1}, and @code{Int2V} can only access objects of type
20449 @code{Int2}, there is no possibility that the assignment to
20450 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
20451 the compiler optimizer can “know” that the value @code{Int1V.all} is constant
20452 for all iterations of the loop and avoid the extra memory reference
20453 required to dereference it each time through the loop.
20455 This kind of optimization, called strict aliasing analysis, is
20456 triggered by specifying an optimization level of @code{-O2} or
20457 higher or @code{-Os} and allows GNAT to generate more efficient code
20458 when access values are involved.
20460 However, although this optimization is always correct in terms of
20461 the formal semantics of the Ada Reference Manual, difficulties can
20462 arise if features like @code{Unchecked_Conversion} are used to break
20463 the typing system. Consider the following complete program example:
20465 @quotation
20467 @example
20468 package p1 is
20469    type int1 is new integer;
20470    type int2 is new integer;
20471    type a1 is access int1;
20472    type a2 is access int2;
20473 end p1;
20475 with p1; use p1;
20476 package p2 is
20477    function to_a2 (Input : a1) return a2;
20478 end p2;
20480 with Unchecked_Conversion;
20481 package body p2 is
20482    function to_a2 (Input : a1) return a2 is
20483       function to_a2u is
20484         new Unchecked_Conversion (a1, a2);
20485    begin
20486       return to_a2u (Input);
20487    end to_a2;
20488 end p2;
20490 with p2; use p2;
20491 with p1; use p1;
20492 with Text_IO; use Text_IO;
20493 procedure m is
20494    v1 : a1 := new int1;
20495    v2 : a2 := to_a2 (v1);
20496 begin
20497    v1.all := 1;
20498    v2.all := 0;
20499    put_line (int1'image (v1.all));
20500 end;
20501 @end example
20502 @end quotation
20504 This program prints out 0 in @code{-O0} or @code{-O1}
20505 mode, but it prints out 1 in @code{-O2} mode. That’s
20506 because in strict aliasing mode, the compiler can and
20507 does assume that the assignment to @code{v2.all} could not
20508 affect the value of @code{v1.all}, since different types
20509 are involved.
20511 This behavior is not a case of non-conformance with the standard, since
20512 the Ada RM specifies that an unchecked conversion where the resulting
20513 bit pattern is not a correct value of the target type can result in an
20514 abnormal value and attempting to reference an abnormal value makes the
20515 execution of a program erroneous.  That’s the case here since the result
20516 does not point to an object of type @code{int2}.  This means that the
20517 effect is entirely unpredictable.
20519 However, although that explanation may satisfy a language
20520 lawyer, in practice an applications programmer expects an
20521 unchecked conversion involving pointers to create true
20522 aliases and the behavior of printing 1 seems plain wrong.
20523 In this case, the strict aliasing optimization is unwelcome.
20525 Indeed the compiler recognizes this possibility, and the
20526 unchecked conversion generates a warning:
20528 @quotation
20530 @example
20531 p2.adb:5:07: warning: possible aliasing problem with type "a2"
20532 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
20533 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
20534 @end example
20535 @end quotation
20537 Unfortunately the problem is recognized when compiling the body of
20538 package @code{p2}, but the actual “bad” code is generated while
20539 compiling the body of @code{m} and this latter compilation does not see
20540 the suspicious @code{Unchecked_Conversion}.
20542 As implied by the warning message, there are approaches you can use to
20543 avoid the unwanted strict aliasing optimization in a case like this.
20545 One possibility is to simply avoid the use of @code{-O2}, but
20546 that is a bit drastic, since it throws away a number of useful
20547 optimizations that do not involve strict aliasing assumptions.
20549 A less drastic approach is to compile the program using the
20550 option @code{-fno-strict-aliasing}. Actually it is only the
20551 unit containing the dereferencing of the suspicious pointer
20552 that needs to be compiled. So in this case, if we compile
20553 unit @code{m} with this switch, then we get the expected
20554 value of zero printed. Analyzing which units might need
20555 the switch can be painful, so a more reasonable approach
20556 is to compile the entire program with options @code{-O2}
20557 and @code{-fno-strict-aliasing}. If the performance is
20558 satisfactory with this combination of options, then the
20559 advantage is that the entire issue of possible “wrong”
20560 optimization due to strict aliasing is avoided.
20562 To avoid the use of compiler switches, the configuration
20563 pragma @code{No_Strict_Aliasing} with no parameters may be
20564 used to specify that for all access types, the strict
20565 aliasing optimization should be suppressed.
20567 However, these approaches are still overkill, in that they causes
20568 all manipulations of all access values to be deoptimized. A more
20569 refined approach is to concentrate attention on the specific
20570 access type identified as problematic.
20572 First, if a careful analysis of uses of the pointer shows
20573 that there are no possible problematic references, then
20574 the warning can be suppressed by bracketing the
20575 instantiation of @code{Unchecked_Conversion} to turn
20576 the warning off:
20578 @quotation
20580 @example
20581 pragma Warnings (Off);
20582 function to_a2u is
20583   new Unchecked_Conversion (a1, a2);
20584 pragma Warnings (On);
20585 @end example
20586 @end quotation
20588 Of course that approach is not appropriate for this particular
20589 example, since indeed there is a problematic reference. In this
20590 case we can take one of two other approaches.
20592 The first possibility is to move the instantiation of unchecked
20593 conversion to the unit in which the type is declared. In
20594 this example, we would move the instantiation of
20595 @code{Unchecked_Conversion} from the body of package
20596 @code{p2} to the spec of package @code{p1}. Now the
20597 warning disappears. That’s because any use of the
20598 access type knows there is a suspicious unchecked
20599 conversion, and the strict aliasing optimization
20600 is automatically suppressed for the type.
20602 If it is not practical to move the unchecked conversion to the same unit
20603 in which the destination access type is declared (perhaps because the
20604 source type is not visible in that unit), you may use pragma
20605 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
20606 same declarative sequence as the declaration of the access type:
20608 @quotation
20610 @example
20611 type a2 is access int2;
20612 pragma No_Strict_Aliasing (a2);
20613 @end example
20614 @end quotation
20616 Here again, the compiler now knows that the strict aliasing optimization
20617 should be suppressed for any reference to type @code{a2} and the
20618 expected behavior is obtained.
20620 Finally, note that although the compiler can generate warnings for
20621 simple cases of unchecked conversions, there are tricker and more
20622 indirect ways of creating type incorrect aliases which the compiler
20623 cannot detect. Examples are the use of address overlays and unchecked
20624 conversions involving composite types containing access types as
20625 components. In such cases, no warnings are generated, but there can
20626 still be aliasing problems. One safe coding practice is to forbid the
20627 use of address clauses for type overlaying, and to allow unchecked
20628 conversion only for primitive types. This is not really a significant
20629 restriction since any possible desired effect can be achieved by
20630 unchecked conversion of access values.
20632 The aliasing analysis done in strict aliasing mode can certainly
20633 have significant benefits. We have seen cases of large scale
20634 application code where the time is increased by up to 5% by turning
20635 this optimization off. If you have code that includes significant
20636 usage of unchecked conversion, you might want to just stick with
20637 @code{-O1} and avoid the entire issue. If you get adequate
20638 performance at this level of optimization level, that’s probably
20639 the safest approach. If tests show that you really need higher
20640 levels of optimization, then you can experiment with @code{-O2}
20641 and @code{-O2 -fno-strict-aliasing} to see how much effect this
20642 has on size and speed of the code. If you really need to use
20643 @code{-O2} with strict aliasing in effect, then you should
20644 review any uses of unchecked conversion of access types,
20645 particularly if you are getting the warnings described above.
20647 @node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
20648 @anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{18d}@anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{18e}
20649 @subsubsection Aliased Variables and Optimization
20652 @geindex Aliasing
20654 There are scenarios in which programs may
20655 use low level techniques to modify variables
20656 that otherwise might be considered to be unassigned. For example,
20657 a variable can be passed to a procedure by reference, which takes
20658 the address of the parameter and uses the address to modify the
20659 variable’s value, even though it is passed as an IN parameter.
20660 Consider the following example:
20662 @quotation
20664 @example
20665 procedure P is
20666    Max_Length : constant Natural := 16;
20667    type Char_Ptr is access all Character;
20669    procedure Get_String(Buffer: Char_Ptr; Size : Integer);
20670    pragma Import (C, Get_String, "get_string");
20672    Name : aliased String (1 .. Max_Length) := (others => ' ');
20673    Temp : Char_Ptr;
20675    function Addr (S : String) return Char_Ptr is
20676       function To_Char_Ptr is
20677         new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
20678    begin
20679       return To_Char_Ptr (S (S'First)'Address);
20680    end;
20682 begin
20683    Temp := Addr (Name);
20684    Get_String (Temp, Max_Length);
20685 end;
20686 @end example
20687 @end quotation
20689 where Get_String is a C function that uses the address in Temp to
20690 modify the variable @code{Name}. This code is dubious, and arguably
20691 erroneous, and the compiler would be entitled to assume that
20692 @code{Name} is never modified, and generate code accordingly.
20694 However, in practice, this would cause some existing code that
20695 seems to work with no optimization to start failing at high
20696 levels of optimzization.
20698 What the compiler does for such cases is to assume that marking
20699 a variable as aliased indicates that some “funny business” may
20700 be going on. The optimizer recognizes the aliased keyword and
20701 inhibits optimizations that assume the value cannot be assigned.
20702 This means that the above example will in fact “work” reliably,
20703 that is, it will produce the expected results.
20705 @node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
20706 @anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{18f}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{190}
20707 @subsubsection Atomic Variables and Optimization
20710 @geindex Atomic
20712 There are two considerations with regard to performance when
20713 atomic variables are used.
20715 First, the RM only guarantees that access to atomic variables
20716 be atomic, it has nothing to say about how this is achieved,
20717 though there is a strong implication that this should not be
20718 achieved by explicit locking code. Indeed GNAT will never
20719 generate any locking code for atomic variable access (it will
20720 simply reject any attempt to make a variable or type atomic
20721 if the atomic access cannot be achieved without such locking code).
20723 That being said, it is important to understand that you cannot
20724 assume that the entire variable will always be accessed. Consider
20725 this example:
20727 @quotation
20729 @example
20730 type R is record
20731    A,B,C,D : Character;
20732 end record;
20733 for R'Size use 32;
20734 for R'Alignment use 4;
20736 RV : R;
20737 pragma Atomic (RV);
20738 X : Character;
20740 X := RV.B;
20741 @end example
20742 @end quotation
20744 You cannot assume that the reference to @code{RV.B}
20745 will read the entire 32-bit
20746 variable with a single load instruction. It is perfectly legitimate if
20747 the hardware allows it to do a byte read of just the B field. This read
20748 is still atomic, which is all the RM requires. GNAT can and does take
20749 advantage of this, depending on the architecture and optimization level.
20750 Any assumption to the contrary is non-portable and risky. Even if you
20751 examine the assembly language and see a full 32-bit load, this might
20752 change in a future version of the compiler.
20754 If your application requires that all accesses to @code{RV} in this
20755 example be full 32-bit loads, you need to make a copy for the access
20756 as in:
20758 @quotation
20760 @example
20761 declare
20762    RV_Copy : constant R := RV;
20763 begin
20764    X := RV_Copy.B;
20765 end;
20766 @end example
20767 @end quotation
20769 Now the reference to RV must read the whole variable.
20770 Actually one can imagine some compiler which figures
20771 out that the whole copy is not required (because only
20772 the B field is actually accessed), but GNAT
20773 certainly won’t do that, and we don’t know of any
20774 compiler that would not handle this right, and the
20775 above code will in practice work portably across
20776 all architectures (that permit the Atomic declaration).
20778 The second issue with atomic variables has to do with
20779 the possible requirement of generating synchronization
20780 code. For more details on this, consult the sections on
20781 the pragmas Enable/Disable_Atomic_Synchronization in the
20782 GNAT Reference Manual. If performance is critical, and
20783 such synchronization code is not required, it may be
20784 useful to disable it.
20786 @node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
20787 @anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{191}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{192}
20788 @subsubsection Passive Task Optimization
20791 @geindex Passive Task
20793 A passive task is one which is sufficiently simple that
20794 in theory a compiler could recognize it an implement it
20795 efficiently without creating a new thread. The original design
20796 of Ada 83 had in mind this kind of passive task optimization, but
20797 only a few Ada 83 compilers attempted it. The problem was that
20798 it was difficult to determine the exact conditions under which
20799 the optimization was possible. The result is a very fragile
20800 optimization where a very minor change in the program can
20801 suddenly silently make a task non-optimizable.
20803 With the revisiting of this issue in Ada 95, there was general
20804 agreement that this approach was fundamentally flawed, and the
20805 notion of protected types was introduced. When using protected
20806 types, the restrictions are well defined, and you KNOW that the
20807 operations will be optimized, and furthermore this optimized
20808 performance is fully portable.
20810 Although it would theoretically be possible for GNAT to attempt to
20811 do this optimization, but it really doesn’t make sense in the
20812 context of Ada 95, and none of the Ada 95 compilers implement
20813 this optimization as far as we know. In particular GNAT never
20814 attempts to perform this optimization.
20816 In any new Ada 95 code that is written, you should always
20817 use protected types in place of tasks that might be able to
20818 be optimized in this manner.
20819 Of course this does not help if you have legacy Ada 83 code
20820 that depends on this optimization, but it is unusual to encounter
20821 a case where the performance gains from this optimization
20822 are significant.
20824 Your program should work correctly without this optimization. If
20825 you have performance problems, then the most practical
20826 approach is to figure out exactly where these performance problems
20827 arise, and update those particular tasks to be protected types. Note
20828 that typically clients of the tasks who call entries, will not have
20829 to be modified, only the task definition itself.
20831 @node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
20832 @anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{193}@anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{194}
20833 @subsection @code{Text_IO} Suggestions
20836 @geindex Text_IO and performance
20838 The @code{Ada.Text_IO} package has fairly high overheads due in part to
20839 the requirement of maintaining page and line counts. If performance
20840 is critical, a recommendation is to use @code{Stream_IO} instead of
20841 @code{Text_IO} for volume output, since this package has less overhead.
20843 If @code{Text_IO} must be used, note that by default output to the standard
20844 output and standard error files is unbuffered (this provides better
20845 behavior when output statements are used for debugging, or if the
20846 progress of a program is observed by tracking the output, e.g. by
20847 using the Unix @emph{tail -f} command to watch redirected output).
20849 If you are generating large volumes of output with @code{Text_IO} and
20850 performance is an important factor, use a designated file instead
20851 of the standard output file, or change the standard output file to
20852 be buffered using @code{Interfaces.C_Streams.setvbuf}.
20854 @node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
20855 @anchor{gnat_ugn/gnat_and_program_execution id41}@anchor{195}@anchor{gnat_ugn/gnat_and_program_execution reducing-size-of-executables-with-unused-subprogram-data-elimination}@anchor{196}
20856 @subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
20859 @geindex Uunused subprogram/data elimination
20861 This section describes how you can eliminate unused subprograms and data from
20862 your executable just by setting options at compilation time.
20864 @menu
20865 * About unused subprogram/data elimination:: 
20866 * Compilation options:: 
20867 * Example of unused subprogram/data elimination:: 
20869 @end menu
20871 @node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
20872 @anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{197}@anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{198}
20873 @subsubsection About unused subprogram/data elimination
20876 By default, an executable contains all code and data of its composing objects
20877 (directly linked or coming from statically linked libraries), even data or code
20878 never used by this executable.
20880 This feature will allow you to eliminate such unused code from your
20881 executable, making it smaller (in disk and in memory).
20883 This functionality is available on all Linux platforms except for the IA-64
20884 architecture and on all cross platforms using the ELF binary file format.
20885 In both cases GNU binutils version 2.16 or later are required to enable it.
20887 @node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
20888 @anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{199}@anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{19a}
20889 @subsubsection Compilation options
20892 The operation of eliminating the unused code and data from the final executable
20893 is directly performed by the linker.
20895 @geindex -ffunction-sections (gcc)
20897 @geindex -fdata-sections (gcc)
20899 In order to do this, it has to work with objects compiled with the
20900 following options:
20901 @code{-ffunction-sections} @code{-fdata-sections}.
20903 These options are usable with C and Ada files.
20904 They will place respectively each
20905 function or data in a separate section in the resulting object file.
20907 Once the objects and static libraries are created with these options, the
20908 linker can perform the dead code elimination. You can do this by setting
20909 the @code{-Wl,--gc-sections} option to gcc command or in the
20910 @code{-largs} section of @code{gnatmake}. This will perform a
20911 garbage collection of code and data never referenced.
20913 If the linker performs a partial link (@code{-r} linker option), then you
20914 will need to provide the entry point using the @code{-e} / @code{--entry}
20915 linker option.
20917 Note that objects compiled without the @code{-ffunction-sections} and
20918 @code{-fdata-sections} options can still be linked with the executable.
20919 However, no dead code elimination will be performed on those objects (they will
20920 be linked as is).
20922 The GNAT static library is now compiled with -ffunction-sections and
20923 -fdata-sections on some platforms. This allows you to eliminate the unused code
20924 and data of the GNAT library from your executable.
20926 @node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
20927 @anchor{gnat_ugn/gnat_and_program_execution example-of-unused-subprogram-data-elimination}@anchor{19b}@anchor{gnat_ugn/gnat_and_program_execution id44}@anchor{19c}
20928 @subsubsection Example of unused subprogram/data elimination
20931 Here is a simple example:
20933 @quotation
20935 @example
20936 with Aux;
20938 procedure Test is
20939 begin
20940    Aux.Used (10);
20941 end Test;
20943 package Aux is
20944    Used_Data   : Integer;
20945    Unused_Data : Integer;
20947    procedure Used   (Data : Integer);
20948    procedure Unused (Data : Integer);
20949 end Aux;
20951 package body Aux is
20952    procedure Used (Data : Integer) is
20953    begin
20954       Used_Data := Data;
20955    end Used;
20957    procedure Unused (Data : Integer) is
20958    begin
20959       Unused_Data := Data;
20960    end Unused;
20961 end Aux;
20962 @end example
20963 @end quotation
20965 @code{Unused} and @code{Unused_Data} are never referenced in this code
20966 excerpt, and hence they may be safely removed from the final executable.
20968 @quotation
20970 @example
20971 $ gnatmake test
20973 $ nm test | grep used
20974 020015f0 T aux__unused
20975 02005d88 B aux__unused_data
20976 020015cc T aux__used
20977 02005d84 B aux__used_data
20979 $ gnatmake test -cargs -fdata-sections -ffunction-sections \\
20980      -largs -Wl,--gc-sections
20982 $ nm test | grep used
20983 02005350 T aux__used
20984 0201ffe0 B aux__used_data
20985 @end example
20986 @end quotation
20988 It can be observed that the procedure @code{Unused} and the object
20989 @code{Unused_Data} are removed by the linker when using the
20990 appropriate options.
20992 @geindex Overflow checks
20994 @geindex Checks (overflow)
20996 @node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
20997 @anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{149}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{19d}
20998 @section Overflow Check Handling in GNAT
21001 This section explains how to control the handling of overflow checks.
21003 @menu
21004 * Background:: 
21005 * Management of Overflows in GNAT:: 
21006 * Specifying the Desired Mode:: 
21007 * Default Settings:: 
21008 * Implementation Notes:: 
21010 @end menu
21012 @node Background,Management of Overflows in GNAT,,Overflow Check Handling in GNAT
21013 @anchor{gnat_ugn/gnat_and_program_execution background}@anchor{19e}@anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{19f}
21014 @subsection Background
21017 Overflow checks are checks that the compiler may make to ensure
21018 that intermediate results are not out of range. For example:
21020 @quotation
21022 @example
21023 A : Integer;
21025 A := A + 1;
21026 @end example
21027 @end quotation
21029 If @code{A} has the value @code{Integer'Last}, then the addition may cause
21030 overflow since the result is out of range of the type @code{Integer}.
21031 In this case @code{Constraint_Error} will be raised if checks are
21032 enabled.
21034 A trickier situation arises in examples like the following:
21036 @quotation
21038 @example
21039 A, C : Integer;
21041 A := (A + 1) + C;
21042 @end example
21043 @end quotation
21045 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
21046 Now the final result of the expression on the right hand side is
21047 @code{Integer'Last} which is in range, but the question arises whether the
21048 intermediate addition of @code{(A + 1)} raises an overflow error.
21050 The (perhaps surprising) answer is that the Ada language
21051 definition does not answer this question. Instead it leaves
21052 it up to the implementation to do one of two things if overflow
21053 checks are enabled.
21056 @itemize *
21058 @item 
21059 raise an exception (@code{Constraint_Error}), or
21061 @item 
21062 yield the correct mathematical result which is then used in
21063 subsequent operations.
21064 @end itemize
21066 If the compiler chooses the first approach, then the assignment of this
21067 example will indeed raise @code{Constraint_Error} if overflow checking is
21068 enabled, or result in erroneous execution if overflow checks are suppressed.
21070 But if the compiler
21071 chooses the second approach, then it can perform both additions yielding
21072 the correct mathematical result, which is in range, so no exception
21073 will be raised, and the right result is obtained, regardless of whether
21074 overflow checks are suppressed.
21076 Note that in the first example an
21077 exception will be raised in either case, since if the compiler
21078 gives the correct mathematical result for the addition, it will
21079 be out of range of the target type of the assignment, and thus
21080 fails the range check.
21082 This lack of specified behavior in the handling of overflow for
21083 intermediate results is a source of non-portability, and can thus
21084 be problematic when programs are ported. Most typically this arises
21085 in a situation where the original compiler did not raise an exception,
21086 and then the application is moved to a compiler where the check is
21087 performed on the intermediate result and an unexpected exception is
21088 raised.
21090 Furthermore, when using Ada 2012’s preconditions and other
21091 assertion forms, another issue arises. Consider:
21093 @quotation
21095 @example
21096 procedure P (A, B : Integer) with
21097   Pre => A + B <= Integer'Last;
21098 @end example
21099 @end quotation
21101 One often wants to regard arithmetic in a context like this from
21102 a mathematical point of view. So for example, if the two actual parameters
21103 for a call to @code{P} are both @code{Integer'Last}, then
21104 the precondition should be regarded as False. If we are executing
21105 in a mode with run-time checks enabled for preconditions, then we would
21106 like this precondition to fail, rather than raising an exception
21107 because of the intermediate overflow.
21109 However, the language definition leaves the specification of
21110 whether the above condition fails (raising @code{Assert_Error}) or
21111 causes an intermediate overflow (raising @code{Constraint_Error})
21112 up to the implementation.
21114 The situation is worse in a case such as the following:
21116 @quotation
21118 @example
21119 procedure Q (A, B, C : Integer) with
21120   Pre => A + B + C <= Integer'Last;
21121 @end example
21122 @end quotation
21124 Consider the call
21126 @quotation
21128 @example
21129 Q (A => Integer'Last, B => 1, C => -1);
21130 @end example
21131 @end quotation
21133 From a mathematical point of view the precondition
21134 is True, but at run time we may (but are not guaranteed to) get an
21135 exception raised because of the intermediate overflow (and we really
21136 would prefer this precondition to be considered True at run time).
21138 @node Management of Overflows in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
21139 @anchor{gnat_ugn/gnat_and_program_execution id47}@anchor{1a0}@anchor{gnat_ugn/gnat_and_program_execution management-of-overflows-in-gnat}@anchor{1a1}
21140 @subsection Management of Overflows in GNAT
21143 To deal with the portability issue, and with the problem of
21144 mathematical versus run-time interpretation of the expressions in
21145 assertions, GNAT provides comprehensive control over the handling
21146 of intermediate overflow. GNAT can operate in three modes, and
21147 furthemore, permits separate selection of operating modes for
21148 the expressions within assertions (here the term ‘assertions’
21149 is used in the technical sense, which includes preconditions and so forth)
21150 and for expressions appearing outside assertions.
21152 The three modes are:
21155 @itemize *
21157 @item 
21158 @emph{Use base type for intermediate operations} (@code{STRICT})
21160 In this mode, all intermediate results for predefined arithmetic
21161 operators are computed using the base type, and the result must
21162 be in range of the base type. If this is not the
21163 case then either an exception is raised (if overflow checks are
21164 enabled) or the execution is erroneous (if overflow checks are suppressed).
21165 This is the normal default mode.
21167 @item 
21168 @emph{Most intermediate overflows avoided} (@code{MINIMIZED})
21170 In this mode, the compiler attempts to avoid intermediate overflows by
21171 using a larger integer type, typically @code{Long_Long_Integer},
21172 as the type in which arithmetic is
21173 performed for predefined arithmetic operators. This may be slightly more
21174 expensive at
21175 run time (compared to suppressing intermediate overflow checks), though
21176 the cost is negligible on modern 64-bit machines. For the examples given
21177 earlier, no intermediate overflows would have resulted in exceptions,
21178 since the intermediate results are all in the range of
21179 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
21180 of GNAT). In addition, if checks are enabled, this reduces the number of
21181 checks that must be made, so this choice may actually result in an
21182 improvement in space and time behavior.
21184 However, there are cases where @code{Long_Long_Integer} is not large
21185 enough, consider the following example:
21187 @quotation
21189 @example
21190 procedure R (A, B, C, D : Integer) with
21191   Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
21192 @end example
21193 @end quotation
21195 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
21196 Now the intermediate results are
21197 out of the range of @code{Long_Long_Integer} even though the final result
21198 is in range and the precondition is True (from a mathematical point
21199 of view). In such a case, operating in this mode, an overflow occurs
21200 for the intermediate computation (which is why this mode
21201 says @emph{most} intermediate overflows are avoided). In this case,
21202 an exception is raised if overflow checks are enabled, and the
21203 execution is erroneous if overflow checks are suppressed.
21205 @item 
21206 @emph{All intermediate overflows avoided} (@code{ELIMINATED})
21208 In this mode, the compiler  avoids all intermediate overflows
21209 by using arbitrary precision arithmetic as required. In this
21210 mode, the above example with @code{A**2 * B**2} would
21211 not cause intermediate overflow, because the intermediate result
21212 would be evaluated using sufficient precision, and the result
21213 of evaluating the precondition would be True.
21215 This mode has the advantage of avoiding any intermediate
21216 overflows, but at the expense of significant run-time overhead,
21217 including the use of a library (included automatically in this
21218 mode) for multiple-precision arithmetic.
21220 This mode provides cleaner semantics for assertions, since now
21221 the run-time behavior emulates true arithmetic behavior for the
21222 predefined arithmetic operators, meaning that there is never a
21223 conflict between the mathematical view of the assertion, and its
21224 run-time behavior.
21226 Note that in this mode, the behavior is unaffected by whether or
21227 not overflow checks are suppressed, since overflow does not occur.
21228 It is possible for gigantic intermediate expressions to raise
21229 @code{Storage_Error} as a result of attempting to compute the
21230 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
21231 but overflow is impossible.
21232 @end itemize
21234 Note that these modes apply only to the evaluation of predefined
21235 arithmetic, membership, and comparison operators for signed integer
21236 arithmetic.
21238 For fixed-point arithmetic, checks can be suppressed. But if checks
21239 are enabled
21240 then fixed-point values are always checked for overflow against the
21241 base type for intermediate expressions (that is such checks always
21242 operate in the equivalent of @code{STRICT} mode).
21244 For floating-point, on nearly all architectures, @code{Machine_Overflows}
21245 is False, and IEEE infinities are generated, so overflow exceptions
21246 are never raised. If you want to avoid infinities, and check that
21247 final results of expressions are in range, then you can declare a
21248 constrained floating-point type, and range checks will be carried
21249 out in the normal manner (with infinite values always failing all
21250 range checks).
21252 @node Specifying the Desired Mode,Default Settings,Management of Overflows in GNAT,Overflow Check Handling in GNAT
21253 @anchor{gnat_ugn/gnat_and_program_execution id48}@anchor{1a2}@anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{e9}
21254 @subsection Specifying the Desired Mode
21257 @geindex pragma Overflow_Mode
21259 The desired mode of for handling intermediate overflow can be specified using
21260 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
21261 The pragma has the form
21263 @quotation
21265 @example
21266 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
21267 @end example
21268 @end quotation
21270 where @code{MODE} is one of
21273 @itemize *
21275 @item 
21276 @code{STRICT}:  intermediate overflows checked (using base type)
21278 @item 
21279 @code{MINIMIZED}: minimize intermediate overflows
21281 @item 
21282 @code{ELIMINATED}: eliminate intermediate overflows
21283 @end itemize
21285 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
21286 @code{minimized} all have the same effect.
21288 If only the @code{General} parameter is present, then the given @code{MODE} applies
21289 to expressions both within and outside assertions. If both arguments
21290 are present, then @code{General} applies to expressions outside assertions,
21291 and @code{Assertions} applies to expressions within assertions. For example:
21293 @quotation
21295 @example
21296 pragma Overflow_Mode
21297   (General => Minimized, Assertions => Eliminated);
21298 @end example
21299 @end quotation
21301 specifies that general expressions outside assertions be evaluated
21302 in ‘minimize intermediate overflows’ mode, and expressions within
21303 assertions be evaluated in ‘eliminate intermediate overflows’ mode.
21304 This is often a reasonable choice, avoiding excessive overhead
21305 outside assertions, but assuring a high degree of portability
21306 when importing code from another compiler, while incurring
21307 the extra overhead for assertion expressions to ensure that
21308 the behavior at run time matches the expected mathematical
21309 behavior.
21311 The @code{Overflow_Mode} pragma has the same scoping and placement
21312 rules as pragma @code{Suppress}, so it can occur either as a
21313 configuration pragma, specifying a default for the whole
21314 program, or in a declarative scope, where it applies to the
21315 remaining declarations and statements in that scope.
21317 Note that pragma @code{Overflow_Mode} does not affect whether
21318 overflow checks are enabled or suppressed. It only controls the
21319 method used to compute intermediate values. To control whether
21320 overflow checking is enabled or suppressed, use pragma @code{Suppress}
21321 or @code{Unsuppress} in the usual manner.
21323 @geindex -gnato? (gcc)
21325 @geindex -gnato?? (gcc)
21327 Additionally, a compiler switch @code{-gnato?} or @code{-gnato??}
21328 can be used to control the checking mode default (which can be subsequently
21329 overridden using pragmas).
21331 Here @code{?} is one of the digits @code{1} through @code{3}:
21333 @quotation
21336 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
21337 @item
21339 @code{1}
21341 @tab
21343 use base type for intermediate operations (@code{STRICT})
21345 @item
21347 @code{2}
21349 @tab
21351 minimize intermediate overflows (@code{MINIMIZED})
21353 @item
21355 @code{3}
21357 @tab
21359 eliminate intermediate overflows (@code{ELIMINATED})
21361 @end multitable
21363 @end quotation
21365 As with the pragma, if only one digit appears then it applies to all
21366 cases; if two digits are given, then the first applies outside
21367 assertions, and the second within assertions. Thus the equivalent
21368 of the example pragma above would be
21369 @code{-gnato23}.
21371 If no digits follow the @code{-gnato}, then it is equivalent to
21372 @code{-gnato11},
21373 causing all intermediate operations to be computed using the base
21374 type (@code{STRICT} mode).
21376 @node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
21377 @anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{1a3}@anchor{gnat_ugn/gnat_and_program_execution id49}@anchor{1a4}
21378 @subsection Default Settings
21381 The default mode for overflow checks is
21383 @quotation
21385 @example
21386 General => Strict
21387 @end example
21388 @end quotation
21390 which causes all computations both inside and outside assertions to use
21391 the base type.
21393 This retains compatibility with previous versions of
21394 GNAT which suppressed overflow checks by default and always
21395 used the base type for computation of intermediate results.
21397 @c Sphinx allows no emphasis within :index: role. As a workaround we
21398 @c point the index to "switch" and use emphasis for "-gnato".
21400 The 
21401 @geindex -gnato (gcc)
21402 switch @code{-gnato} (with no digits following)
21403 is equivalent to
21405 @quotation
21407 @example
21408 General => Strict
21409 @end example
21410 @end quotation
21412 which causes overflow checking of all intermediate overflows
21413 both inside and outside assertions against the base type.
21415 The pragma @code{Suppress (Overflow_Check)} disables overflow
21416 checking, but it has no effect on the method used for computing
21417 intermediate results.
21419 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
21420 checking, but it has no effect on the method used for computing
21421 intermediate results.
21423 @node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
21424 @anchor{gnat_ugn/gnat_and_program_execution id50}@anchor{1a5}@anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{1a6}
21425 @subsection Implementation Notes
21428 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
21429 reasonably efficient, and can be generally used. It also helps
21430 to ensure compatibility with code imported from some other
21431 compiler to GNAT.
21433 Setting all intermediate overflows checking (@code{CHECKED} mode)
21434 makes sense if you want to
21435 make sure that your code is compatible with any other possible
21436 Ada implementation. This may be useful in ensuring portability
21437 for code that is to be exported to some other compiler than GNAT.
21439 The Ada standard allows the reassociation of expressions at
21440 the same precedence level if no parentheses are present. For
21441 example, @code{A+B+C} parses as though it were @code{(A+B)+C}, but
21442 the compiler can reintepret this as @code{A+(B+C)}, possibly
21443 introducing or eliminating an overflow exception. The GNAT
21444 compiler never takes advantage of this freedom, and the
21445 expression @code{A+B+C} will be evaluated as @code{(A+B)+C}.
21446 If you need the other order, you can write the parentheses
21447 explicitly @code{A+(B+C)} and GNAT will respect this order.
21449 The use of @code{ELIMINATED} mode will cause the compiler to
21450 automatically include an appropriate arbitrary precision
21451 integer arithmetic package. The compiler will make calls
21452 to this package, though only in cases where it cannot be
21453 sure that @code{Long_Long_Integer} is sufficient to guard against
21454 intermediate overflows. This package does not use dynamic
21455 allocation, but it does use the secondary stack, so an
21456 appropriate secondary stack package must be present (this
21457 is always true for standard full Ada, but may require
21458 specific steps for restricted run times such as ZFP).
21460 Although @code{ELIMINATED} mode causes expressions to use arbitrary
21461 precision arithmetic, avoiding overflow, the final result
21462 must be in an appropriate range. This is true even if the
21463 final result is of type @code{[Long_[Long_]]Integer'Base}, which
21464 still has the same bounds as its associated constrained
21465 type at run-time.
21467 Currently, the @code{ELIMINATED} mode is only available on target
21468 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
21469 platforms).
21471 @node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
21472 @anchor{gnat_ugn/gnat_and_program_execution id51}@anchor{14a}@anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{1a7}
21473 @section Performing Dimensionality Analysis in GNAT
21476 @geindex Dimensionality analysis
21478 The GNAT compiler supports dimensionality checking. The user can
21479 specify physical units for objects, and the compiler will verify that uses
21480 of these objects are compatible with their dimensions, in a fashion that is
21481 familiar to engineering practice. The dimensions of algebraic expressions
21482 (including powers with static exponents) are computed from their constituents.
21484 @geindex Dimension_System aspect
21486 @geindex Dimension aspect
21488 This feature depends on Ada 2012 aspect specifications, and is available from
21489 version 7.0.1 of GNAT onwards.
21490 The GNAT-specific aspect @code{Dimension_System}
21491 allows you to define a system of units; the aspect @code{Dimension}
21492 then allows the user to declare dimensioned quantities within a given system.
21493 (These aspects are described in the @emph{Implementation Defined Aspects}
21494 chapter of the @emph{GNAT Reference Manual}).
21496 The major advantage of this model is that it does not require the declaration of
21497 multiple operators for all possible combinations of types: it is only necessary
21498 to use the proper subtypes in object declarations.
21500 @geindex System.Dim.Mks package (GNAT library)
21502 @geindex MKS_Type type
21504 The simplest way to impose dimensionality checking on a computation is to make
21505 use of one of the instantiations of the package @code{System.Dim.Generic_Mks}, which
21506 are part of the GNAT library. This generic package defines a floating-point
21507 type @code{MKS_Type}, for which a sequence of dimension names are specified,
21508 together with their conventional abbreviations.  The following should be read
21509 together with the full specification of the package, in file
21510 @code{s-digemk.ads}.
21512 @quotation
21514 @geindex s-digemk.ads file
21516 @example
21517 type Mks_Type is new Float_Type
21518   with
21519    Dimension_System => (
21520      (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
21521      (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
21522      (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
21523      (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
21524      (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
21525      (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
21526      (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
21527 @end example
21528 @end quotation
21530 The package then defines a series of subtypes that correspond to these
21531 conventional units. For example:
21533 @quotation
21535 @example
21536 subtype Length is Mks_Type
21537   with
21538    Dimension => (Symbol => 'm', Meter  => 1, others => 0);
21539 @end example
21540 @end quotation
21542 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
21543 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
21544 @code{Luminous_Intensity} (the standard set of units of the SI system).
21546 The package also defines conventional names for values of each unit, for
21547 example:
21549 @quotation
21551 @example
21552 m   : constant Length           := 1.0;
21553 kg  : constant Mass             := 1.0;
21554 s   : constant Time             := 1.0;
21555 A   : constant Electric_Current := 1.0;
21556 @end example
21557 @end quotation
21559 as well as useful multiples of these units:
21561 @quotation
21563 @example
21564  cm  : constant Length := 1.0E-02;
21565  g   : constant Mass   := 1.0E-03;
21566  min : constant Time   := 60.0;
21567  day : constant Time   := 60.0 * 24.0 * min;
21569 @end example
21570 @end quotation
21572 There are three instantiations of @code{System.Dim.Generic_Mks} defined in the
21573 GNAT library:
21576 @itemize *
21578 @item 
21579 @code{System.Dim.Float_Mks} based on @code{Float} defined in @code{s-diflmk.ads}.
21581 @item 
21582 @code{System.Dim.Long_Mks} based on @code{Long_Float} defined in @code{s-dilomk.ads}.
21584 @item 
21585 @code{System.Dim.Mks} based on @code{Long_Long_Float} defined in @code{s-dimmks.ads}.
21586 @end itemize
21588 Using one of these packages, you can then define a derived unit by providing
21589 the aspect that specifies its dimensions within the MKS system, as well as the
21590 string to be used for output of a value of that unit:
21592 @quotation
21594 @example
21595 subtype Acceleration is Mks_Type
21596   with Dimension => ("m/sec^2",
21597                      Meter => 1,
21598                      Second => -2,
21599                      others => 0);
21600 @end example
21601 @end quotation
21603 Here is a complete example of use:
21605 @quotation
21607 @example
21608 with System.Dim.MKS; use System.Dim.Mks;
21609 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
21610 with Text_IO; use Text_IO;
21611 procedure Free_Fall is
21612   subtype Acceleration is Mks_Type
21613     with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
21614   G : constant acceleration := 9.81 * m / (s ** 2);
21615   T : Time := 10.0*s;
21616   Distance : Length;
21618 begin
21619   Put ("Gravitational constant: ");
21620   Put (G, Aft => 2, Exp => 0); Put_Line ("");
21621   Distance := 0.5 * G * T ** 2;
21622   Put ("distance travelled in 10 seconds of free fall ");
21623   Put (Distance, Aft => 2, Exp => 0);
21624   Put_Line ("");
21625 end Free_Fall;
21626 @end example
21627 @end quotation
21629 Execution of this program yields:
21631 @quotation
21633 @example
21634 Gravitational constant:  9.81 m/sec^2
21635 distance travelled in 10 seconds of free fall 490.50 m
21636 @end example
21637 @end quotation
21639 However, incorrect assignments such as:
21641 @quotation
21643 @example
21644 Distance := 5.0;
21645 Distance := 5.0 * kg;
21646 @end example
21647 @end quotation
21649 are rejected with the following diagnoses:
21651 @quotation
21653 @example
21654 Distance := 5.0;
21655    >>> dimensions mismatch in assignment
21656    >>> left-hand side has dimension [L]
21657    >>> right-hand side is dimensionless
21659 Distance := 5.0 * kg:
21660    >>> dimensions mismatch in assignment
21661    >>> left-hand side has dimension [L]
21662    >>> right-hand side has dimension [M]
21663 @end example
21664 @end quotation
21666 The dimensions of an expression are properly displayed, even if there is
21667 no explicit subtype for it. If we add to the program:
21669 @quotation
21671 @example
21672 Put ("Final velocity: ");
21673 Put (G * T, Aft =>2, Exp =>0);
21674 Put_Line ("");
21675 @end example
21676 @end quotation
21678 then the output includes:
21680 @quotation
21682 @example
21683 Final velocity: 98.10 m.s**(-1)
21684 @end example
21686 @geindex Dimensionable type
21688 @geindex Dimensioned subtype
21689 @end quotation
21691 The type @code{Mks_Type} is said to be a @emph{dimensionable type} since it has a
21692 @code{Dimension_System} aspect, and the subtypes @code{Length}, @code{Mass}, etc.,
21693 are said to be @emph{dimensioned subtypes} since each one has a @code{Dimension}
21694 aspect.
21696 @quotation
21698 @geindex Dimension Vector (for a dimensioned subtype)
21700 @geindex Dimension aspect
21702 @geindex Dimension_System aspect
21703 @end quotation
21705 The @code{Dimension} aspect of a dimensioned subtype @code{S} defines a mapping
21706 from the base type’s Unit_Names to integer (or, more generally, rational)
21707 values. This mapping is the @emph{dimension vector} (also referred to as the
21708 @emph{dimensionality}) for that subtype, denoted by @code{DV(S)}, and thus for each
21709 object of that subtype. Intuitively, the value specified for each
21710 @code{Unit_Name} is the exponent associated with that unit; a zero value
21711 means that the unit is not used. For example:
21713 @quotation
21715 @example
21716 declare
21717    Acc : Acceleration;
21718    ...
21719 begin
21720    ...
21721 end;
21722 @end example
21723 @end quotation
21725 Here @code{DV(Acc)} = @code{DV(Acceleration)} =
21726 @code{(Meter=>1, Kilogram=>0, Second=>-2, Ampere=>0, Kelvin=>0, Mole=>0, Candela=>0)}.
21727 Symbolically, we can express this as @code{Meter / Second**2}.
21729 The dimension vector of an arithmetic expression is synthesized from the
21730 dimension vectors of its components, with compile-time dimensionality checks
21731 that help prevent mismatches such as using an @code{Acceleration} where a
21732 @code{Length} is required.
21734 The dimension vector of the result of an arithmetic expression @emph{expr}, or
21735 @code{DV(@emph{expr})}, is defined as follows, assuming conventional
21736 mathematical definitions for the vector operations that are used:
21739 @itemize *
21741 @item 
21742 If @emph{expr} is of the type @emph{universal_real}, or is not of a dimensioned subtype,
21743 then @emph{expr} is dimensionless; @code{DV(@emph{expr})} is the empty vector.
21745 @item 
21746 @code{DV(@emph{op expr})}, where @emph{op} is a unary operator, is @code{DV(@emph{expr})}
21748 @item 
21749 @code{DV(@emph{expr1 op expr2})} where @emph{op} is “+” or “-” is @code{DV(@emph{expr1})}
21750 provided that @code{DV(@emph{expr1})} = @code{DV(@emph{expr2})}.
21751 If this condition is not met then the construct is illegal.
21753 @item 
21754 @code{DV(@emph{expr1} * @emph{expr2})} is @code{DV(@emph{expr1})} + @code{DV(@emph{expr2})},
21755 and @code{DV(@emph{expr1} / @emph{expr2})} = @code{DV(@emph{expr1})} - @code{DV(@emph{expr2})}.
21756 In this context if one of the @emph{expr}s is dimensionless then its empty
21757 dimension vector is treated as @code{(others => 0)}.
21759 @item 
21760 @code{DV(@emph{expr} ** @emph{power})} is @emph{power} * @code{DV(@emph{expr})},
21761 provided that @emph{power} is a static rational value. If this condition is not
21762 met then the construct is illegal.
21763 @end itemize
21765 Note that, by the above rules, it is illegal to use binary “+” or “-” to
21766 combine a dimensioned and dimensionless value.  Thus an expression such as
21767 @code{acc-10.0} is illegal, where @code{acc} is an object of subtype
21768 @code{Acceleration}.
21770 The dimensionality checks for relationals use the same rules as
21771 for “+” and “-“, except when comparing to a literal; thus
21773 @quotation
21775 @example
21776 acc > len
21777 @end example
21778 @end quotation
21780 is equivalent to
21782 @quotation
21784 @example
21785 acc-len > 0.0
21786 @end example
21787 @end quotation
21789 and is thus illegal, but
21791 @quotation
21793 @example
21794 acc > 10.0
21795 @end example
21796 @end quotation
21798 is accepted with a warning. Analogously a conditional expression requires the
21799 same dimension vector for each branch (with no exception for literals).
21801 The dimension vector of a type conversion @code{T(@emph{expr})} is defined
21802 as follows, based on the nature of @code{T}:
21805 @itemize *
21807 @item 
21808 If @code{T} is a dimensioned subtype then @code{DV(T(@emph{expr}))} is @code{DV(T)}
21809 provided that either @emph{expr} is dimensionless or
21810 @code{DV(T)} = @code{DV(@emph{expr})}. The conversion is illegal
21811 if @emph{expr} is dimensioned and @code{DV(@emph{expr})} /= @code{DV(T)}.
21812 Note that vector equality does not require that the corresponding
21813 Unit_Names be the same.
21815 As a consequence of the above rule, it is possible to convert between
21816 different dimension systems that follow the same international system
21817 of units, with the seven physical components given in the standard order
21818 (length, mass, time, etc.). Thus a length in meters can be converted to
21819 a length in inches (with a suitable conversion factor) but cannot be
21820 converted, for example, to a mass in pounds.
21822 @item 
21823 If @code{T} is the base type for @emph{expr} (and the dimensionless root type of
21824 the dimension system), then @code{DV(T(@emph{expr}))} is @code{DV(expr)}.
21825 Thus, if @emph{expr} is of a dimensioned subtype of @code{T}, the conversion may
21826 be regarded as a “view conversion” that preserves dimensionality.
21828 This rule makes it possible to write generic code that can be instantiated
21829 with compatible dimensioned subtypes.  The generic unit will contain
21830 conversions that will consequently be present in instantiations, but
21831 conversions to the base type will preserve dimensionality and make it
21832 possible to write generic code that is correct with respect to
21833 dimensionality.
21835 @item 
21836 Otherwise (i.e., @code{T} is neither a dimensioned subtype nor a dimensionable
21837 base type), @code{DV(T(@emph{expr}))} is the empty vector. Thus a dimensioned
21838 value can be explicitly converted to a non-dimensioned subtype, which
21839 of course then escapes dimensionality analysis.
21840 @end itemize
21842 The dimension vector for a type qualification @code{T'(@emph{expr})} is the same
21843 as for the type conversion @code{T(@emph{expr})}.
21845 An assignment statement
21847 @quotation
21849 @example
21850 Source := Target;
21851 @end example
21852 @end quotation
21854 requires @code{DV(Source)} = @code{DV(Target)}, and analogously for parameter
21855 passing (the dimension vector for the actual parameter must be equal to the
21856 dimension vector for the formal parameter).
21858 @node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
21859 @anchor{gnat_ugn/gnat_and_program_execution id52}@anchor{14b}@anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{1a8}
21860 @section Stack Related Facilities
21863 This section describes some useful tools associated with stack
21864 checking and analysis. In
21865 particular, it deals with dynamic and static stack usage measurements.
21867 @menu
21868 * Stack Overflow Checking:: 
21869 * Static Stack Usage Analysis:: 
21870 * Dynamic Stack Usage Analysis:: 
21872 @end menu
21874 @node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
21875 @anchor{gnat_ugn/gnat_and_program_execution id53}@anchor{1a9}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{e5}
21876 @subsection Stack Overflow Checking
21879 @geindex Stack Overflow Checking
21881 @geindex -fstack-check (gcc)
21883 For most operating systems, @code{gcc} does not perform stack overflow
21884 checking by default. This means that if the main environment task or
21885 some other task exceeds the available stack space, then unpredictable
21886 behavior will occur. Most native systems offer some level of protection by
21887 adding a guard page at the end of each task stack. This mechanism is usually
21888 not enough for dealing properly with stack overflow situations because
21889 a large local variable could “jump” above the guard page.
21890 Furthermore, when the
21891 guard page is hit, there may not be any space left on the stack for executing
21892 the exception propagation code. Enabling stack checking avoids
21893 such situations.
21895 To activate stack checking, compile all units with the @code{gcc} option
21896 @code{-fstack-check}. For example:
21898 @quotation
21900 @example
21901 $ gcc -c -fstack-check package1.adb
21902 @end example
21903 @end quotation
21905 Units compiled with this option will generate extra instructions to check
21906 that any use of the stack (for procedure calls or for declaring local
21907 variables in declare blocks) does not exceed the available stack space.
21908 If the space is exceeded, then a @code{Storage_Error} exception is raised.
21910 For declared tasks, the default stack size is defined by the GNAT runtime,
21911 whose size may be modified at bind time through the @code{-d} bind switch
21912 (@ref{110,,Switches for gnatbind}). Task specific stack sizes may be set using the
21913 @code{Storage_Size} pragma.
21915 For the environment task, the stack size is determined by the operating system.
21916 Consequently, to modify the size of the environment task please refer to your
21917 operating system documentation.
21919 @node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
21920 @anchor{gnat_ugn/gnat_and_program_execution id54}@anchor{1aa}@anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{e6}
21921 @subsection Static Stack Usage Analysis
21924 @geindex Static Stack Usage Analysis
21926 @geindex -fstack-usage
21928 A unit compiled with @code{-fstack-usage} will generate an extra file
21929 that specifies
21930 the maximum amount of stack used, on a per-function basis.
21931 The file has the same
21932 basename as the target object file with a @code{.su} extension.
21933 Each line of this file is made up of three fields:
21936 @itemize *
21938 @item 
21939 The name of the function.
21941 @item 
21942 A number of bytes.
21944 @item 
21945 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
21946 @end itemize
21948 The second field corresponds to the size of the known part of the function
21949 frame.
21951 The qualifier @code{static} means that the function frame size
21952 is purely static.
21953 It usually means that all local variables have a static size.
21954 In this case, the second field is a reliable measure of the function stack
21955 utilization.
21957 The qualifier @code{dynamic} means that the function frame size is not static.
21958 It happens mainly when some local variables have a dynamic size. When this
21959 qualifier appears alone, the second field is not a reliable measure
21960 of the function stack analysis. When it is qualified with  @code{bounded}, it
21961 means that the second field is a reliable maximum of the function stack
21962 utilization.
21964 A unit compiled with @code{-Wstack-usage} will issue a warning for each
21965 subprogram whose stack usage might be larger than the specified amount of
21966 bytes.  The wording is in keeping with the qualifier documented above.
21968 @node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
21969 @anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{113}@anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{1ab}
21970 @subsection Dynamic Stack Usage Analysis
21973 It is possible to measure the maximum amount of stack used by a task, by
21974 adding a switch to @code{gnatbind}, as:
21976 @quotation
21978 @example
21979 $ gnatbind -u0 file
21980 @end example
21981 @end quotation
21983 With this option, at each task termination, its stack usage is output on
21984 @code{stderr}.
21985 Note that this switch is not compatible with tools like
21986 Valgrind and DrMemory; they will report errors.
21988 It is not always convenient to output the stack usage when the program
21989 is still running. Hence, it is possible to delay this output until program
21990 termination. for a given number of tasks specified as the argument of the
21991 @code{-u} option. For instance:
21993 @quotation
21995 @example
21996 $ gnatbind -u100 file
21997 @end example
21998 @end quotation
22000 will buffer the stack usage information of the first 100 tasks to terminate and
22001 output this info at program termination. Results are displayed in four
22002 columns:
22004 @quotation
22006 @example
22007 Index | Task Name | Stack Size | Stack Usage
22008 @end example
22009 @end quotation
22011 where:
22014 @itemize *
22016 @item 
22017 @emph{Index} is a number associated with each task.
22019 @item 
22020 @emph{Task Name} is the name of the task analyzed.
22022 @item 
22023 @emph{Stack Size} is the maximum size for the stack.
22025 @item 
22026 @emph{Stack Usage} is the measure done by the stack analyzer.
22027 In order to prevent overflow, the stack
22028 is not entirely analyzed, and it’s not possible to know exactly how
22029 much has actually been used.
22030 @end itemize
22032 By default the environment task stack, the stack that contains the main unit,
22033 is not processed. To enable processing of the environment task stack, the
22034 environment variable GNAT_STACK_LIMIT needs to be set to the maximum size of
22035 the environment task stack. This amount is given in kilobytes. For example:
22037 @quotation
22039 @example
22040 $ set GNAT_STACK_LIMIT 1600
22041 @end example
22042 @end quotation
22044 would specify to the analyzer that the environment task stack has a limit
22045 of 1.6 megabytes. Any stack usage beyond this will be ignored by the analysis.
22047 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
22048 stack-usage reports at run time. See its body for the details.
22050 @node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
22051 @anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{14c}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{1ac}
22052 @section Memory Management Issues
22055 This section describes some useful memory pools provided in the GNAT library
22056 and in particular the GNAT Debug Pool facility, which can be used to detect
22057 incorrect uses of access values (including ‘dangling references’).
22060 @menu
22061 * Some Useful Memory Pools:: 
22062 * The GNAT Debug Pool Facility:: 
22064 @end menu
22066 @node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
22067 @anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{1ad}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{1ae}
22068 @subsection Some Useful Memory Pools
22071 @geindex Memory Pool
22073 @geindex storage
22074 @geindex pool
22076 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
22077 storage pool. Allocations use the standard system call @code{malloc} while
22078 deallocations use the standard system call @code{free}. No reclamation is
22079 performed when the pool goes out of scope. For performance reasons, the
22080 standard default Ada allocators/deallocators do not use any explicit storage
22081 pools but if they did, they could use this storage pool without any change in
22082 behavior. That is why this storage pool is used  when the user
22083 manages to make the default implicit allocator explicit as in this example:
22085 @quotation
22087 @example
22088 type T1 is access Something;
22089  -- no Storage pool is defined for T2
22091 type T2 is access Something_Else;
22092 for T2'Storage_Pool use T1'Storage_Pool;
22093 -- the above is equivalent to
22094 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
22095 @end example
22096 @end quotation
22098 The @code{System.Pool_Local} package offers the @code{Unbounded_Reclaim_Pool} storage
22099 pool. The allocation strategy is similar to @code{Pool_Local}
22100 except that the all
22101 storage allocated with this pool is reclaimed when the pool object goes out of
22102 scope. This pool provides a explicit mechanism similar to the implicit one
22103 provided by several Ada 83 compilers for allocations performed through a local
22104 access type and whose purpose was to reclaim memory when exiting the
22105 scope of a given local access. As an example, the following program does not
22106 leak memory even though it does not perform explicit deallocation:
22108 @quotation
22110 @example
22111 with System.Pool_Local;
22112 procedure Pooloc1 is
22113    procedure Internal is
22114       type A is access Integer;
22115       X : System.Pool_Local.Unbounded_Reclaim_Pool;
22116       for A'Storage_Pool use X;
22117       v : A;
22118    begin
22119       for I in  1 .. 50 loop
22120          v := new Integer;
22121       end loop;
22122    end Internal;
22123 begin
22124    for I in  1 .. 100 loop
22125       Internal;
22126    end loop;
22127 end Pooloc1;
22128 @end example
22129 @end quotation
22131 The @code{System.Pool_Size} package implements the @code{Stack_Bounded_Pool} used when
22132 @code{Storage_Size} is specified for an access type.
22133 The whole storage for the pool is
22134 allocated at once, usually on the stack at the point where the access type is
22135 elaborated. It is automatically reclaimed when exiting the scope where the
22136 access type is defined. This package is not intended to be used directly by the
22137 user and it is implicitly used for each such declaration:
22139 @quotation
22141 @example
22142 type T1 is access Something;
22143 for T1'Storage_Size use 10_000;
22144 @end example
22145 @end quotation
22147 @node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
22148 @anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{1af}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{1b0}
22149 @subsection The GNAT Debug Pool Facility
22152 @geindex Debug Pool
22154 @geindex storage
22155 @geindex pool
22156 @geindex memory corruption
22158 The use of unchecked deallocation and unchecked conversion can easily
22159 lead to incorrect memory references. The problems generated by such
22160 references are usually difficult to tackle because the symptoms can be
22161 very remote from the origin of the problem. In such cases, it is
22162 very helpful to detect the problem as early as possible. This is the
22163 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
22165 In order to use the GNAT specific debugging pool, the user must
22166 associate a debug pool object with each of the access types that may be
22167 related to suspected memory problems. See Ada Reference Manual 13.11.
22169 @quotation
22171 @example
22172 type Ptr is access Some_Type;
22173 Pool : GNAT.Debug_Pools.Debug_Pool;
22174 for Ptr'Storage_Pool use Pool;
22175 @end example
22176 @end quotation
22178 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
22179 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
22180 allow the user to redefine allocation and deallocation strategies. They
22181 also provide a checkpoint for each dereference, through the use of
22182 the primitive operation @code{Dereference} which is implicitly called at
22183 each dereference of an access value.
22185 Once an access type has been associated with a debug pool, operations on
22186 values of the type may raise four distinct exceptions,
22187 which correspond to four potential kinds of memory corruption:
22190 @itemize *
22192 @item 
22193 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
22195 @item 
22196 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
22198 @item 
22199 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
22201 @item 
22202 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
22203 @end itemize
22205 For types associated with a Debug_Pool, dynamic allocation is performed using
22206 the standard GNAT allocation routine. References to all allocated chunks of
22207 memory are kept in an internal dictionary. Several deallocation strategies are
22208 provided, whereupon the user can choose to release the memory to the system,
22209 keep it allocated for further invalid access checks, or fill it with an easily
22210 recognizable pattern for debug sessions. The memory pattern is the old IBM
22211 hexadecimal convention: @code{16#DEADBEEF#}.
22213 See the documentation in the file g-debpoo.ads for more information on the
22214 various strategies.
22216 Upon each dereference, a check is made that the access value denotes a
22217 properly allocated memory location. Here is a complete example of use of
22218 @code{Debug_Pools}, that includes typical instances of  memory corruption:
22220 @quotation
22222 @example
22223 with Gnat.Io; use Gnat.Io;
22224 with Unchecked_Deallocation;
22225 with Unchecked_Conversion;
22226 with GNAT.Debug_Pools;
22227 with System.Storage_Elements;
22228 with Ada.Exceptions; use Ada.Exceptions;
22229 procedure Debug_Pool_Test is
22231    type T is access Integer;
22232    type U is access all T;
22234    P : GNAT.Debug_Pools.Debug_Pool;
22235    for T'Storage_Pool use P;
22237    procedure Free is new Unchecked_Deallocation (Integer, T);
22238    function UC is new Unchecked_Conversion (U, T);
22239    A, B : aliased T;
22241    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
22243 begin
22244    Info (P);
22245    A := new Integer;
22246    B := new Integer;
22247    B := A;
22248    Info (P);
22249    Free (A);
22250    begin
22251       Put_Line (Integer'Image(B.all));
22252    exception
22253       when E : others => Put_Line ("raised: " & Exception_Name (E));
22254    end;
22255    begin
22256       Free (B);
22257    exception
22258       when E : others => Put_Line ("raised: " & Exception_Name (E));
22259    end;
22260    B := UC(A'Access);
22261    begin
22262       Put_Line (Integer'Image(B.all));
22263    exception
22264       when E : others => Put_Line ("raised: " & Exception_Name (E));
22265    end;
22266    begin
22267       Free (B);
22268    exception
22269       when E : others => Put_Line ("raised: " & Exception_Name (E));
22270    end;
22271    Info (P);
22272 end Debug_Pool_Test;
22273 @end example
22274 @end quotation
22276 The debug pool mechanism provides the following precise diagnostics on the
22277 execution of this erroneous program:
22279 @quotation
22281 @example
22282 Debug Pool info:
22283   Total allocated bytes :  0
22284   Total deallocated bytes :  0
22285   Current Water Mark:  0
22286   High Water Mark:  0
22288 Debug Pool info:
22289   Total allocated bytes :  8
22290   Total deallocated bytes :  0
22291   Current Water Mark:  8
22292   High Water Mark:  8
22294 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
22295 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
22296 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
22297 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
22298 Debug Pool info:
22299   Total allocated bytes :  8
22300   Total deallocated bytes :  4
22301   Current Water Mark:  4
22302   High Water Mark:  8
22303 @end example
22304 @end quotation
22307 @c -- Non-breaking space in running text
22308 @c -- E.g. Ada |nbsp| 95
22310 @node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
22311 @anchor{gnat_ugn/platform_specific_information doc}@anchor{1b1}@anchor{gnat_ugn/platform_specific_information id1}@anchor{1b2}@anchor{gnat_ugn/platform_specific_information platform-specific-information}@anchor{d}
22312 @chapter Platform-Specific Information
22315 This appendix contains information relating to the implementation
22316 of run-time libraries on various platforms and also covers
22317 topics related to the GNAT implementation on Windows and Mac OS.
22319 @menu
22320 * Run-Time Libraries:: 
22321 * Specifying a Run-Time Library:: 
22322 * GNU/Linux Topics:: 
22323 * Microsoft Windows Topics:: 
22324 * Mac OS Topics:: 
22326 @end menu
22328 @node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
22329 @anchor{gnat_ugn/platform_specific_information id2}@anchor{1b3}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{1b4}
22330 @section Run-Time Libraries
22333 @geindex Tasking and threads libraries
22335 @geindex Threads libraries and tasking
22337 @geindex Run-time libraries (platform-specific information)
22339 The GNAT run-time implementation may vary with respect to both the
22340 underlying threads library and the exception-handling scheme.
22341 For threads support, the default run-time will bind to the thread
22342 package of the underlying operating system.
22344 For exception handling, either or both of two models are supplied:
22346 @quotation
22348 @geindex Zero-Cost Exceptions
22350 @geindex ZCX (Zero-Cost Exceptions)
22351 @end quotation
22354 @itemize *
22356 @item 
22357 @strong{Zero-Cost Exceptions} (“ZCX”),
22358 which uses binder-generated tables that
22359 are interrogated at run time to locate a handler.
22361 @geindex setjmp/longjmp Exception Model
22363 @geindex SJLJ (setjmp/longjmp Exception Model)
22365 @item 
22366 @strong{setjmp / longjmp} (‘SJLJ’),
22367 which uses dynamically-set data to establish
22368 the set of handlers
22369 @end itemize
22371 Most programs should experience a substantial speed improvement by
22372 being compiled with a ZCX run-time.
22373 This is especially true for
22374 tasking applications or applications with many exception handlers.
22375 Note however that the ZCX run-time does not support asynchronous abort
22376 of tasks (@code{abort} and @code{select-then-abort} constructs) and will instead
22377 implement abort by polling points in the runtime. You can also add additional
22378 polling points explicitly if needed in your application via @code{pragma
22379 Abort_Defer}.
22381 This section summarizes which combinations of threads and exception support
22382 are supplied on various GNAT platforms.
22384 @menu
22385 * Summary of Run-Time Configurations:: 
22387 @end menu
22389 @node Summary of Run-Time Configurations,,,Run-Time Libraries
22390 @anchor{gnat_ugn/platform_specific_information id3}@anchor{1b5}@anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{1b6}
22391 @subsection Summary of Run-Time Configurations
22395 @multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
22396 @headitem
22398 Platform
22400 @tab
22402 Run-Time
22404 @tab
22406 Tasking
22408 @tab
22410 Exceptions
22412 @item
22414 GNU/Linux
22416 @tab
22418 rts-native
22419 (default)
22421 @tab
22423 pthread library
22425 @tab
22429 @item
22431 rts-sjlj
22433 @tab
22435 pthread library
22437 @tab
22439 SJLJ
22441 @item
22443 Windows
22445 @tab
22447 rts-native
22448 (default)
22450 @tab
22452 native Win32 threads
22454 @tab
22458 @item
22460 rts-sjlj
22462 @tab
22464 native Win32 threads
22466 @tab
22468 SJLJ
22470 @item
22472 Mac OS
22474 @tab
22476 rts-native
22478 @tab
22480 pthread library
22482 @tab
22486 @end multitable
22489 @node Specifying a Run-Time Library,GNU/Linux Topics,Run-Time Libraries,Platform-Specific Information
22490 @anchor{gnat_ugn/platform_specific_information id4}@anchor{1b7}@anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{1b8}
22491 @section Specifying a Run-Time Library
22494 The @code{adainclude} subdirectory containing the sources of the GNAT
22495 run-time library, and the @code{adalib} subdirectory containing the
22496 @code{ALI} files and the static and/or shared GNAT library, are located
22497 in the gcc target-dependent area:
22499 @quotation
22501 @example
22502 target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
22503 @end example
22504 @end quotation
22506 As indicated above, on some platforms several run-time libraries are supplied.
22507 These libraries are installed in the target dependent area and
22508 contain a complete source and binary subdirectory. The detailed description
22509 below explains the differences between the different libraries in terms of
22510 their thread support.
22512 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22513 This default run-time is selected by the means of soft links.
22514 For example on x86-linux:
22516 @c --
22517 @c --  $(target-dir)
22518 @c --      |
22519 @c --      +--- adainclude----------+
22520 @c --      |                        |
22521 @c --      +--- adalib-----------+  |
22522 @c --      |                     |  |
22523 @c --      +--- rts-native       |  |
22524 @c --      |    |                |  |
22525 @c --      |    +--- adainclude <---+
22526 @c --      |    |                |
22527 @c --      |    +--- adalib <----+
22528 @c --      |
22529 @c --      +--- rts-sjlj
22530 @c --           |
22531 @c --           +--- adainclude
22532 @c --           |
22533 @c --           +--- adalib
22536 @example
22537                $(target-dir)
22538               __/ /      \ \___
22539       _______/   /        \    \_________________
22540      /          /          \                     \
22541     /          /            \                     \
22542 ADAINCLUDE  ADALIB      rts-native             rts-sjlj
22543    :          :            /    \                 /   \
22544    :          :           /      \               /     \
22545    :          :          /        \             /       \
22546    :          :         /          \           /         \
22547    +-------------> adainclude     adalib   adainclude   adalib
22548               :                     ^
22549               :                     :
22550               +---------------------+
22552               Run-Time Library Directory Structure
22553    (Upper-case names and dotted/dashed arrows represent soft links)
22554 @end example
22556 If the @emph{rts-sjlj} library is to be selected on a permanent basis,
22557 these soft links can be modified with the following commands:
22559 @quotation
22561 @example
22562 $ cd $target
22563 $ rm -f adainclude adalib
22564 $ ln -s rts-sjlj/adainclude adainclude
22565 $ ln -s rts-sjlj/adalib adalib
22566 @end example
22567 @end quotation
22569 Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
22570 @code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
22571 @code{$target/ada_object_path}.
22573 @geindex --RTS option
22575 Selecting another run-time library temporarily can be
22576 achieved by using the @code{--RTS} switch, e.g., @code{--RTS=sjlj}
22577 @anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{1b9}
22578 @geindex SCHED_FIFO scheduling policy
22580 @geindex SCHED_RR scheduling policy
22582 @geindex SCHED_OTHER scheduling policy
22584 @menu
22585 * Choosing the Scheduling Policy:: 
22587 @end menu
22589 @node Choosing the Scheduling Policy,,,Specifying a Run-Time Library
22590 @anchor{gnat_ugn/platform_specific_information id5}@anchor{1ba}
22591 @subsection Choosing the Scheduling Policy
22594 When using a POSIX threads implementation, you have a choice of several
22595 scheduling policies: @code{SCHED_FIFO}, @code{SCHED_RR} and @code{SCHED_OTHER}.
22597 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22598 or @code{SCHED_RR} requires special (e.g., root) privileges.
22600 @geindex pragma Time_Slice
22602 @geindex -T0 option
22604 @geindex pragma Task_Dispatching_Policy
22606 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22607 @code{SCHED_FIFO},
22608 you can use one of the following:
22611 @itemize *
22613 @item 
22614 @code{pragma Time_Slice (0.0)}
22616 @item 
22617 the corresponding binder option @code{-T0}
22619 @item 
22620 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22621 @end itemize
22623 To specify @code{SCHED_RR},
22624 you should use @code{pragma Time_Slice} with a
22625 value greater than 0.0, or else use the corresponding @code{-T}
22626 binder option.
22628 To make sure a program is running as root, you can put something like
22629 this in a library package body in your application:
22631 @quotation
22633 @example
22634 function geteuid return Integer;
22635 pragma Import (C, geteuid, "geteuid");
22636 Ignore : constant Boolean :=
22637   (if geteuid = 0 then True else raise Program_Error with "must be root");
22638 @end example
22639 @end quotation
22641 It gets the effective user id, and if it’s not 0 (i.e. root), it raises
22642 Program_Error. Note that if you re running the code in a container, this may
22643 not be sufficient, as you may have sufficient priviledge on the container,
22644 but not on the host machine running the container, so check that you also
22645 have sufficient priviledge for running the container image.
22647 @geindex Linux
22649 @geindex GNU/Linux
22651 @node GNU/Linux Topics,Microsoft Windows Topics,Specifying a Run-Time Library,Platform-Specific Information
22652 @anchor{gnat_ugn/platform_specific_information gnu-linux-topics}@anchor{1bb}@anchor{gnat_ugn/platform_specific_information id6}@anchor{1bc}
22653 @section GNU/Linux Topics
22656 This section describes topics that are specific to GNU/Linux platforms.
22658 @menu
22659 * Required Packages on GNU/Linux:: 
22660 * A GNU/Linux Debug Quirk:: 
22662 @end menu
22664 @node Required Packages on GNU/Linux,A GNU/Linux Debug Quirk,,GNU/Linux Topics
22665 @anchor{gnat_ugn/platform_specific_information id7}@anchor{1bd}@anchor{gnat_ugn/platform_specific_information required-packages-on-gnu-linux}@anchor{1be}
22666 @subsection Required Packages on GNU/Linux
22669 GNAT requires the C library developer’s package to be installed.
22670 The name of of that package depends on your GNU/Linux distribution:
22673 @itemize *
22675 @item 
22676 RedHat, SUSE: @code{glibc-devel};
22678 @item 
22679 Debian, Ubuntu: @code{libc6-dev} (normally installed by default).
22680 @end itemize
22682 If using the 32-bit version of GNAT on a 64-bit version of GNU/Linux,
22683 you’ll need the 32-bit version of the following packages:
22686 @itemize *
22688 @item 
22689 RedHat, SUSE: @code{glibc.i686}, @code{glibc-devel.i686}, @code{ncurses-libs.i686}
22691 @item 
22692 SUSE: @code{glibc-locale-base-32bit}
22694 @item 
22695 Debian, Ubuntu: @code{libc6:i386}, @code{libc6-dev:i386}, @code{lib32ncursesw5}
22696 @end itemize
22698 Other GNU/Linux distributions might be choosing a different name
22699 for those packages.
22701 @node A GNU/Linux Debug Quirk,,Required Packages on GNU/Linux,GNU/Linux Topics
22702 @anchor{gnat_ugn/platform_specific_information a-gnu-linux-debug-quirk}@anchor{1bf}@anchor{gnat_ugn/platform_specific_information id8}@anchor{1c0}
22703 @subsection A GNU/Linux Debug Quirk
22706 On SuSE 15, some kernels have a defect causing issues when debugging
22707 programs using threads or Ada tasks. Due to the lack of documentation
22708 found regarding this kernel issue, we can only provide limited
22709 information about which kernels are impacted: kernel version 5.3.18 is
22710 known to be impacted, and kernels in the 5.14 range or newer are
22711 believed to fix this problem.
22713 The bug affects the debugging of 32-bit processes on a 64-bit system.
22714 Symptoms can vary: Unexpected @code{SIGABRT} signals being received by
22715 the program, “The futex facility returned an unexpected error code”
22716 error message, and inferior programs hanging indefinitely range among
22717 the symptoms most commonly observed.
22719 @geindex Windows
22721 @node Microsoft Windows Topics,Mac OS Topics,GNU/Linux Topics,Platform-Specific Information
22722 @anchor{gnat_ugn/platform_specific_information id9}@anchor{1c1}@anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{1c2}
22723 @section Microsoft Windows Topics
22726 This section describes topics that are specific to the Microsoft Windows
22727 platforms.
22730 @menu
22731 * Using GNAT on Windows:: 
22732 * Using a network installation of GNAT:: 
22733 * CONSOLE and WINDOWS subsystems:: 
22734 * Temporary Files:: 
22735 * Disabling Command Line Argument Expansion:: 
22736 * Windows Socket Timeouts:: 
22737 * Mixed-Language Programming on Windows:: 
22738 * Windows Specific Add-Ons:: 
22740 @end menu
22742 @node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
22743 @anchor{gnat_ugn/platform_specific_information id10}@anchor{1c3}@anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{1c4}
22744 @subsection Using GNAT on Windows
22747 One of the strengths of the GNAT technology is that its tool set
22748 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
22749 @code{gdb} debugger, etc.) is used in the same way regardless of the
22750 platform.
22752 On Windows this tool set is complemented by a number of Microsoft-specific
22753 tools that have been provided to facilitate interoperability with Windows
22754 when this is required. With these tools:
22757 @itemize *
22759 @item 
22760 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
22761 subsystems.
22763 @item 
22764 You can use any Dynamically Linked Library (DLL) in your Ada code (both
22765 relocatable and non-relocatable DLLs are supported).
22767 @item 
22768 You can build Ada DLLs for use in other applications. These applications
22769 can be written in a language other than Ada (e.g., C, C++, etc). Again both
22770 relocatable and non-relocatable Ada DLLs are supported.
22772 @item 
22773 You can include Windows resources in your Ada application.
22775 @item 
22776 You can use or create COM/DCOM objects.
22777 @end itemize
22779 Immediately below are listed all known general GNAT-for-Windows restrictions.
22780 Other restrictions about specific features like Windows Resources and DLLs
22781 are listed in separate sections below.
22784 @itemize *
22786 @item 
22787 It is not possible to use @code{GetLastError} and @code{SetLastError}
22788 when tasking, protected records, or exceptions are used. In these
22789 cases, in order to implement Ada semantics, the GNAT run-time system
22790 calls certain Win32 routines that set the last error variable to 0 upon
22791 success. It should be possible to use @code{GetLastError} and
22792 @code{SetLastError} when tasking, protected record, and exception
22793 features are not used, but it is not guaranteed to work.
22795 @item 
22796 It is not possible to link against Microsoft C++ libraries except for
22797 import libraries. Interfacing must be done by the mean of DLLs.
22799 @item 
22800 It is possible to link against Microsoft C libraries. Yet the preferred
22801 solution is to use C/C++ compiler that comes with GNAT, since it
22802 doesn’t require having two different development environments and makes the
22803 inter-language debugging experience smoother.
22805 @item 
22806 When the compilation environment is located on FAT32 drives, users may
22807 experience recompilations of the source files that have not changed if
22808 Daylight Saving Time (DST) state has changed since the last time files
22809 were compiled. NTFS drives do not have this problem.
22811 @item 
22812 No components of the GNAT toolset use any entries in the Windows
22813 registry. The only entries that can be created are file associations and
22814 PATH settings, provided the user has chosen to create them at installation
22815 time, as well as some minimal book-keeping information needed to correctly
22816 uninstall or integrate different GNAT products.
22817 @end itemize
22819 @node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
22820 @anchor{gnat_ugn/platform_specific_information id11}@anchor{1c5}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{1c6}
22821 @subsection Using a network installation of GNAT
22824 Make sure the system on which GNAT is installed is accessible from the
22825 current machine, i.e., the install location is shared over the network.
22826 Shared resources are accessed on Windows by means of UNC paths, which
22827 have the format @code{\\\\server\\sharename\\path}
22829 In order to use such a network installation, simply add the UNC path of the
22830 @code{bin} directory of your GNAT installation in front of your PATH. For
22831 example, if GNAT is installed in @code{\GNAT} directory of a share location
22832 called @code{c-drive} on a machine @code{LOKI}, the following command will
22833 make it available:
22835 @quotation
22837 @example
22838 $ path \\loki\c-drive\gnat\bin;%path%`
22839 @end example
22840 @end quotation
22842 Be aware that every compilation using the network installation results in the
22843 transfer of large amounts of data across the network and will likely cause
22844 serious performance penalty.
22846 @node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
22847 @anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{1c7}@anchor{gnat_ugn/platform_specific_information id12}@anchor{1c8}
22848 @subsection CONSOLE and WINDOWS subsystems
22851 @geindex CONSOLE Subsystem
22853 @geindex WINDOWS Subsystem
22855 @geindex -mwindows
22857 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
22858 (which is the default subsystem) will always create a console when
22859 launching the application. This is not something desirable when the
22860 application has a Windows GUI. To get rid of this console the
22861 application must be using the @code{WINDOWS} subsystem. To do so
22862 the @code{-mwindows} linker option must be specified.
22864 @quotation
22866 @example
22867 $ gnatmake winprog -largs -mwindows
22868 @end example
22869 @end quotation
22871 @node Temporary Files,Disabling Command Line Argument Expansion,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
22872 @anchor{gnat_ugn/platform_specific_information id13}@anchor{1c9}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{1ca}
22873 @subsection Temporary Files
22876 @geindex Temporary files
22878 It is possible to control where temporary files gets created by setting
22879 the 
22880 @geindex TMP
22881 @geindex environment variable; TMP
22882 @code{TMP} environment variable. The file will be created:
22885 @itemize *
22887 @item 
22888 Under the directory pointed to by the 
22889 @geindex TMP
22890 @geindex environment variable; TMP
22891 @code{TMP} environment variable if
22892 this directory exists.
22894 @item 
22895 Under @code{c:\temp}, if the 
22896 @geindex TMP
22897 @geindex environment variable; TMP
22898 @code{TMP} environment variable is not
22899 set (or not pointing to a directory) and if this directory exists.
22901 @item 
22902 Under the current working directory otherwise.
22903 @end itemize
22905 This allows you to determine exactly where the temporary
22906 file will be created. This is particularly useful in networked
22907 environments where you may not have write access to some
22908 directories.
22910 @node Disabling Command Line Argument Expansion,Windows Socket Timeouts,Temporary Files,Microsoft Windows Topics
22911 @anchor{gnat_ugn/platform_specific_information disabling-command-line-argument-expansion}@anchor{1cb}
22912 @subsection Disabling Command Line Argument Expansion
22915 @geindex Command Line Argument Expansion
22917 By default, an executable compiled for the Windows platform will do
22918 the following postprocessing on the arguments passed on the command
22919 line:
22922 @itemize *
22924 @item 
22925 If the argument contains the characters @code{*} and/or @code{?}, then
22926 file expansion will be attempted. For example, if the current directory
22927 contains @code{a.txt} and @code{b.txt}, then when calling:
22929 @example
22930 $ my_ada_program *.txt
22931 @end example
22933 The following arguments will effectively be passed to the main program
22934 (for example when using @code{Ada.Command_Line.Argument}):
22936 @example
22937 Ada.Command_Line.Argument (1) -> "a.txt"
22938 Ada.Command_Line.Argument (2) -> "b.txt"
22939 @end example
22941 @item 
22942 Filename expansion can be disabled for a given argument by using single
22943 quotes. Thus, calling:
22945 @example
22946 $ my_ada_program '*.txt'
22947 @end example
22949 will result in:
22951 @example
22952 Ada.Command_Line.Argument (1) -> "*.txt"
22953 @end example
22954 @end itemize
22956 Note that if the program is launched from a shell such as Cygwin Bash
22957 then quote removal might be performed by the shell.
22959 In some contexts it might be useful to disable this feature (for example if
22960 the program performs its own argument expansion). In order to do this, a C
22961 symbol needs to be defined and set to @code{0}. You can do this by
22962 adding the following code fragment in one of your Ada units:
22964 @example
22965 Do_Argv_Expansion : Integer := 0;
22966 pragma Export (C, Do_Argv_Expansion, "__gnat_do_argv_expansion");
22967 @end example
22969 The results of previous examples will be respectively:
22971 @example
22972 Ada.Command_Line.Argument (1) -> "*.txt"
22973 @end example
22975 and:
22977 @example
22978 Ada.Command_Line.Argument (1) -> "'*.txt'"
22979 @end example
22981 @node Windows Socket Timeouts,Mixed-Language Programming on Windows,Disabling Command Line Argument Expansion,Microsoft Windows Topics
22982 @anchor{gnat_ugn/platform_specific_information windows-socket-timeouts}@anchor{1cc}
22983 @subsection Windows Socket Timeouts
22986 Microsoft Windows desktops older than @code{8.0} and Microsoft Windows Servers
22987 older than @code{2019} set a socket timeout 500 milliseconds longer than the value
22988 set by setsockopt with @code{SO_RCVTIMEO} and @code{SO_SNDTIMEO} options. The GNAT
22989 runtime makes a correction for the difference in the corresponding Windows
22990 versions. For Windows Server starting with version @code{2019}, the user must
22991 provide a manifest file for the GNAT runtime to be able to recognize that
22992 the Windows version does not need the timeout correction. The manifest file
22993 should be located in the same directory as the executable file, and its file
22994 name must match the executable name suffixed by @code{.manifest}. For example,
22995 if the executable name is @code{sock_wto.exe}, then the manifest file name
22996 has to be @code{sock_wto.exe.manifest}. The manifest file must contain at
22997 least the following data:
22999 @example
23000 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
23001 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
23002 <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
23003 <application>
23004    <!-- Windows Vista -->
23005    <supportedOS Id="@{e2011457-1546-43c5-a5fe-008deee3d3f0@}"/>
23006    <!-- Windows 7 -->
23007    <supportedOS Id="@{35138b9a-5d96-4fbd-8e2d-a2440225f93a@}"/>
23008    <!-- Windows 8 -->
23009    <supportedOS Id="@{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38@}"/>
23010    <!-- Windows 8.1 -->
23011    <supportedOS Id="@{1f676c76-80e1-4239-95bb-83d0f6d0da78@}"/>
23012    <!-- Windows 10 -->
23013    <supportedOS Id="@{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a@}"/>
23014 </application>
23015 </compatibility>
23016 </assembly>
23017 @end example
23019 Without the manifest file, the socket timeout is going to be overcorrected on
23020 these Windows Server versions and the actual time is going to be 500
23021 milliseconds shorter than what was set with GNAT.Sockets.Set_Socket_Option.
23022 Note that on Microsoft Windows versions where correction is necessary, there
23023 is no way to set a socket timeout shorter than 500 ms. If a socket timeout
23024 shorter than 500 ms is needed on these Windows versions, a call to
23025 Check_Selector should be added before any socket read or write operations.
23027 @node Mixed-Language Programming on Windows,Windows Specific Add-Ons,Windows Socket Timeouts,Microsoft Windows Topics
23028 @anchor{gnat_ugn/platform_specific_information id14}@anchor{1cd}@anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{1ce}
23029 @subsection Mixed-Language Programming on Windows
23032 Developing pure Ada applications on Windows is no different than on
23033 other GNAT-supported platforms. However, when developing or porting an
23034 application that contains a mix of Ada and C/C++, the choice of your
23035 Windows C/C++ development environment conditions your overall
23036 interoperability strategy.
23038 If you use @code{gcc} or Microsoft C to compile the non-Ada part of
23039 your application, there are no Windows-specific restrictions that
23040 affect the overall interoperability with your Ada code. If you do want
23041 to use the Microsoft tools for your C++ code, you have two choices:
23044 @itemize *
23046 @item 
23047 Encapsulate your C++ code in a DLL to be linked with your Ada
23048 application. In this case, use the Microsoft or whatever environment to
23049 build the DLL and use GNAT to build your executable
23050 (@ref{1cf,,Using DLLs with GNAT}).
23052 @item 
23053 Or you can encapsulate your Ada code in a DLL to be linked with the
23054 other part of your application. In this case, use GNAT to build the DLL
23055 (@ref{1d0,,Building DLLs with GNAT Project files}) and use the Microsoft
23056 or whatever environment to build your executable.
23057 @end itemize
23059 In addition to the description about C main in
23060 @ref{2c,,Mixed Language Programming} section, if the C main uses a
23061 stand-alone library it is required on x86-windows to
23062 setup the SEH context. For this the C main must looks like this:
23064 @quotation
23066 @example
23067 /* main.c */
23068 extern void adainit (void);
23069 extern void adafinal (void);
23070 extern void __gnat_initialize(void*);
23071 extern void call_to_ada (void);
23073 int main (int argc, char *argv[])
23075   int SEH [2];
23077   /* Initialize the SEH context */
23078   __gnat_initialize (&SEH);
23080   adainit();
23082   /* Then call Ada services in the stand-alone library */
23084   call_to_ada();
23086   adafinal();
23088 @end example
23089 @end quotation
23091 Note that this is not needed on x86_64-windows where the Windows
23092 native SEH support is used.
23094 @menu
23095 * Windows Calling Conventions:: 
23096 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
23097 * Using DLLs with GNAT:: 
23098 * Building DLLs with GNAT Project files:: 
23099 * Building DLLs with GNAT:: 
23100 * Building DLLs with gnatdll:: 
23101 * Ada DLLs and Finalization:: 
23102 * Creating a Spec for Ada DLLs:: 
23103 * GNAT and Windows Resources:: 
23104 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
23105 * Debugging a DLL:: 
23106 * Setting Stack Size from gnatlink:: 
23107 * Setting Heap Size from gnatlink:: 
23109 @end menu
23111 @node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
23112 @anchor{gnat_ugn/platform_specific_information id15}@anchor{1d1}@anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{1d2}
23113 @subsubsection Windows Calling Conventions
23116 @geindex Stdcall
23118 @geindex APIENTRY
23120 This section pertain only to Win32. On Win64 there is a single native
23121 calling convention. All convention specifiers are ignored on this
23122 platform.
23124 When a subprogram @code{F} (caller) calls a subprogram @code{G}
23125 (callee), there are several ways to push @code{G}‘s parameters on the
23126 stack and there are several possible scenarios to clean up the stack
23127 upon @code{G}‘s return. A calling convention is an agreed upon software
23128 protocol whereby the responsibilities between the caller (@code{F}) and
23129 the callee (@code{G}) are clearly defined. Several calling conventions
23130 are available for Windows:
23133 @itemize *
23135 @item 
23136 @code{C} (Microsoft defined)
23138 @item 
23139 @code{Stdcall} (Microsoft defined)
23141 @item 
23142 @code{Win32} (GNAT specific)
23144 @item 
23145 @code{DLL} (GNAT specific)
23146 @end itemize
23148 @menu
23149 * C Calling Convention:: 
23150 * Stdcall Calling Convention:: 
23151 * Win32 Calling Convention:: 
23152 * DLL Calling Convention:: 
23154 @end menu
23156 @node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
23157 @anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{1d3}@anchor{gnat_ugn/platform_specific_information id16}@anchor{1d4}
23158 @subsubsection @code{C} Calling Convention
23161 This is the default calling convention used when interfacing to C/C++
23162 routines compiled with either @code{gcc} or Microsoft Visual C++.
23164 In the @code{C} calling convention subprogram parameters are pushed on the
23165 stack by the caller from right to left. The caller itself is in charge of
23166 cleaning up the stack after the call. In addition, the name of a routine
23167 with @code{C} calling convention is mangled by adding a leading underscore.
23169 The name to use on the Ada side when importing (or exporting) a routine
23170 with @code{C} calling convention is the name of the routine. For
23171 instance the C function:
23173 @quotation
23175 @example
23176 int get_val (long);
23177 @end example
23178 @end quotation
23180 should be imported from Ada as follows:
23182 @quotation
23184 @example
23185 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23186 pragma Import (C, Get_Val, External_Name => "get_val");
23187 @end example
23188 @end quotation
23190 Note that in this particular case the @code{External_Name} parameter could
23191 have been omitted since, when missing, this parameter is taken to be the
23192 name of the Ada entity in lower case. When the @code{Link_Name} parameter
23193 is missing, as in the above example, this parameter is set to be the
23194 @code{External_Name} with a leading underscore.
23196 When importing a variable defined in C, you should always use the @code{C}
23197 calling convention unless the object containing the variable is part of a
23198 DLL (in which case you should use the @code{Stdcall} calling
23199 convention, @ref{1d5,,Stdcall Calling Convention}).
23201 @node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
23202 @anchor{gnat_ugn/platform_specific_information id17}@anchor{1d6}@anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{1d5}
23203 @subsubsection @code{Stdcall} Calling Convention
23206 This convention, which was the calling convention used for Pascal
23207 programs, is used by Microsoft for all the routines in the Win32 API for
23208 efficiency reasons. It must be used to import any routine for which this
23209 convention was specified.
23211 In the @code{Stdcall} calling convention subprogram parameters are pushed
23212 on the stack by the caller from right to left. The callee (and not the
23213 caller) is in charge of cleaning the stack on routine exit. In addition,
23214 the name of a routine with @code{Stdcall} calling convention is mangled by
23215 adding a leading underscore (as for the @code{C} calling convention) and a
23216 trailing @code{@@@emph{nn}}, where @code{nn} is the overall size (in
23217 bytes) of the parameters passed to the routine.
23219 The name to use on the Ada side when importing a C routine with a
23220 @code{Stdcall} calling convention is the name of the C routine. The leading
23221 underscore and trailing @code{@@@emph{nn}} are added automatically by
23222 the compiler. For instance the Win32 function:
23224 @quotation
23226 @example
23227 APIENTRY int get_val (long);
23228 @end example
23229 @end quotation
23231 should be imported from Ada as follows:
23233 @quotation
23235 @example
23236 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23237 pragma Import (Stdcall, Get_Val);
23238 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
23239 @end example
23240 @end quotation
23242 As for the @code{C} calling convention, when the @code{External_Name}
23243 parameter is missing, it is taken to be the name of the Ada entity in lower
23244 case. If instead of writing the above import pragma you write:
23246 @quotation
23248 @example
23249 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23250 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
23251 @end example
23252 @end quotation
23254 then the imported routine is @code{_retrieve_val@@4}. However, if instead
23255 of specifying the @code{External_Name} parameter you specify the
23256 @code{Link_Name} as in the following example:
23258 @quotation
23260 @example
23261 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23262 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
23263 @end example
23264 @end quotation
23266 then the imported routine is @code{retrieve_val}, that is, there is no
23267 decoration at all. No leading underscore and no Stdcall suffix
23268 @code{@@@emph{nn}}.
23270 This is especially important as in some special cases a DLL’s entry
23271 point name lacks a trailing @code{@@@emph{nn}} while the exported
23272 name generated for a call has it.
23274 It is also possible to import variables defined in a DLL by using an
23275 import pragma for a variable. As an example, if a DLL contains a
23276 variable defined as:
23278 @quotation
23280 @example
23281 int my_var;
23282 @end example
23283 @end quotation
23285 then, to access this variable from Ada you should write:
23287 @quotation
23289 @example
23290 My_Var : Interfaces.C.int;
23291 pragma Import (Stdcall, My_Var);
23292 @end example
23293 @end quotation
23295 Note that to ease building cross-platform bindings this convention
23296 will be handled as a @code{C} calling convention on non-Windows platforms.
23298 @node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
23299 @anchor{gnat_ugn/platform_specific_information id18}@anchor{1d7}@anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{1d8}
23300 @subsubsection @code{Win32} Calling Convention
23303 This convention, which is GNAT-specific is fully equivalent to the
23304 @code{Stdcall} calling convention described above.
23306 @node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
23307 @anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{1d9}@anchor{gnat_ugn/platform_specific_information id19}@anchor{1da}
23308 @subsubsection @code{DLL} Calling Convention
23311 This convention, which is GNAT-specific is fully equivalent to the
23312 @code{Stdcall} calling convention described above.
23314 @node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
23315 @anchor{gnat_ugn/platform_specific_information id20}@anchor{1db}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{1dc}
23316 @subsubsection Introduction to Dynamic Link Libraries (DLLs)
23319 @geindex DLL
23321 A Dynamically Linked Library (DLL) is a library that can be shared by
23322 several applications running under Windows. A DLL can contain any number of
23323 routines and variables.
23325 One advantage of DLLs is that you can change and enhance them without
23326 forcing all the applications that depend on them to be relinked or
23327 recompiled. However, you should be aware than all calls to DLL routines are
23328 slower since, as you will understand below, such calls are indirect.
23330 To illustrate the remainder of this section, suppose that an application
23331 wants to use the services of a DLL @code{API.dll}. To use the services
23332 provided by @code{API.dll} you must statically link against the DLL or
23333 an import library which contains a jump table with an entry for each
23334 routine and variable exported by the DLL. In the Microsoft world this
23335 import library is called @code{API.lib}. When using GNAT this import
23336 library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
23337 @code{libAPI.a} or @code{libapi.a} (names are case insensitive).
23339 After you have linked your application with the DLL or the import library
23340 and you run your application, here is what happens:
23343 @itemize *
23345 @item 
23346 Your application is loaded into memory.
23348 @item 
23349 The DLL @code{API.dll} is mapped into the address space of your
23350 application. This means that:
23353 @itemize -
23355 @item 
23356 The DLL will use the stack of the calling thread.
23358 @item 
23359 The DLL will use the virtual address space of the calling process.
23361 @item 
23362 The DLL will allocate memory from the virtual address space of the calling
23363 process.
23365 @item 
23366 Handles (pointers) can be safely exchanged between routines in the DLL
23367 routines and routines in the application using the DLL.
23368 @end itemize
23370 @item 
23371 The entries in the jump table (from the import library @code{libAPI.dll.a}
23372 or @code{API.lib} or automatically created when linking against a DLL)
23373 which is part of your application are initialized with the addresses
23374 of the routines and variables in @code{API.dll}.
23376 @item 
23377 If present in @code{API.dll}, routines @code{DllMain} or
23378 @code{DllMainCRTStartup} are invoked. These routines typically contain
23379 the initialization code needed for the well-being of the routines and
23380 variables exported by the DLL.
23381 @end itemize
23383 There is an additional point which is worth mentioning. In the Windows
23384 world there are two kind of DLLs: relocatable and non-relocatable
23385 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
23386 in the target application address space. If the addresses of two
23387 non-relocatable DLLs overlap and these happen to be used by the same
23388 application, a conflict will occur and the application will run
23389 incorrectly. Hence, when possible, it is always preferable to use and
23390 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
23391 supported by GNAT. Note that the @code{-s} linker option (see GNU Linker
23392 User’s Guide) removes the debugging symbols from the DLL but the DLL can
23393 still be relocated.
23395 As a side note, an interesting difference between Microsoft DLLs and
23396 Unix shared libraries, is the fact that on most Unix systems all public
23397 routines are exported by default in a Unix shared library, while under
23398 Windows it is possible (but not required) to list exported routines in
23399 a definition file (see @ref{1dd,,The Definition File}).
23401 @node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
23402 @anchor{gnat_ugn/platform_specific_information id21}@anchor{1de}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{1cf}
23403 @subsubsection Using DLLs with GNAT
23406 To use the services of a DLL, say @code{API.dll}, in your Ada application
23407 you must have:
23410 @itemize *
23412 @item 
23413 The Ada spec for the routines and/or variables you want to access in
23414 @code{API.dll}. If not available this Ada spec must be built from the C/C++
23415 header files provided with the DLL.
23417 @item 
23418 The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
23419 mentioned an import library is a statically linked library containing the
23420 import table which will be filled at load time to point to the actual
23421 @code{API.dll} routines. Sometimes you don’t have an import library for the
23422 DLL you want to use. The following sections will explain how to build
23423 one. Note that this is optional.
23425 @item 
23426 The actual DLL, @code{API.dll}.
23427 @end itemize
23429 Once you have all the above, to compile an Ada application that uses the
23430 services of @code{API.dll} and whose main subprogram is @code{My_Ada_App},
23431 you simply issue the command
23433 @quotation
23435 @example
23436 $ gnatmake my_ada_app -largs -lAPI
23437 @end example
23438 @end quotation
23440 The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
23441 tells the GNAT linker to look for an import library. The linker will
23442 look for a library name in this specific order:
23445 @itemize *
23447 @item 
23448 @code{libAPI.dll.a}
23450 @item 
23451 @code{API.dll.a}
23453 @item 
23454 @code{libAPI.a}
23456 @item 
23457 @code{API.lib}
23459 @item 
23460 @code{libAPI.dll}
23462 @item 
23463 @code{API.dll}
23464 @end itemize
23466 The first three are the GNU style import libraries. The third is the
23467 Microsoft style import libraries. The last two are the actual DLL names.
23469 Note that if the Ada package spec for @code{API.dll} contains the
23470 following pragma
23472 @quotation
23474 @example
23475 pragma Linker_Options ("-lAPI");
23476 @end example
23477 @end quotation
23479 you do not have to add @code{-largs -lAPI} at the end of the
23480 @code{gnatmake} command.
23482 If any one of the items above is missing you will have to create it
23483 yourself. The following sections explain how to do so using as an
23484 example a fictitious DLL called @code{API.dll}.
23486 @menu
23487 * Creating an Ada Spec for the DLL Services:: 
23488 * Creating an Import Library:: 
23490 @end menu
23492 @node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
23493 @anchor{gnat_ugn/platform_specific_information creating-an-ada-spec-for-the-dll-services}@anchor{1df}@anchor{gnat_ugn/platform_specific_information id22}@anchor{1e0}
23494 @subsubsection Creating an Ada Spec for the DLL Services
23497 A DLL typically comes with a C/C++ header file which provides the
23498 definitions of the routines and variables exported by the DLL. The Ada
23499 equivalent of this header file is a package spec that contains definitions
23500 for the imported entities. If the DLL you intend to use does not come with
23501 an Ada spec you have to generate one such spec yourself. For example if
23502 the header file of @code{API.dll} is a file @code{api.h} containing the
23503 following two definitions:
23505 @quotation
23507 @example
23508 int some_var;
23509 int get (char *);
23510 @end example
23511 @end quotation
23513 then the equivalent Ada spec could be:
23515 @quotation
23517 @example
23518 with Interfaces.C.Strings;
23519 package API is
23520    use Interfaces;
23522    Some_Var : C.int;
23523    function Get (Str : C.Strings.Chars_Ptr) return C.int;
23525 private
23526    pragma Import (C, Get);
23527    pragma Import (DLL, Some_Var);
23528 end API;
23529 @end example
23530 @end quotation
23532 @node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
23533 @anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{1e1}@anchor{gnat_ugn/platform_specific_information id23}@anchor{1e2}
23534 @subsubsection Creating an Import Library
23537 @geindex Import library
23539 If a Microsoft-style import library @code{API.lib} or a GNAT-style
23540 import library @code{libAPI.dll.a} or @code{libAPI.a} is available
23541 with @code{API.dll} you can skip this section. You can also skip this
23542 section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
23543 as in this case it is possible to link directly against the
23544 DLL. Otherwise read on.
23546 @geindex Definition file
23547 @anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{1dd}
23548 @subsubheading The Definition File
23551 As previously mentioned, and unlike Unix systems, the list of symbols
23552 that are exported from a DLL must be provided explicitly in Windows.
23553 The main goal of a definition file is precisely that: list the symbols
23554 exported by a DLL. A definition file (usually a file with a @code{.def}
23555 suffix) has the following structure:
23557 @quotation
23559 @example
23560 [LIBRARY `@w{`}name`@w{`}]
23561 [DESCRIPTION `@w{`}string`@w{`}]
23562 EXPORTS
23563    `@w{`}symbol1`@w{`}
23564    `@w{`}symbol2`@w{`}
23565    ...
23566 @end example
23567 @end quotation
23570 @table @asis
23572 @item @emph{LIBRARY name}
23574 This section, which is optional, gives the name of the DLL.
23576 @item @emph{DESCRIPTION string}
23578 This section, which is optional, gives a description string that will be
23579 embedded in the import library.
23581 @item @emph{EXPORTS}
23583 This section gives the list of exported symbols (procedures, functions or
23584 variables). For instance in the case of @code{API.dll} the @code{EXPORTS}
23585 section of @code{API.def} looks like:
23587 @example
23588 EXPORTS
23589    some_var
23590    get
23591 @end example
23592 @end table
23594 Note that you must specify the correct suffix (@code{@@@emph{nn}})
23595 (see @ref{1d2,,Windows Calling Conventions}) for a Stdcall
23596 calling convention function in the exported symbols list.
23598 There can actually be other sections in a definition file, but these
23599 sections are not relevant to the discussion at hand.
23600 @anchor{gnat_ugn/platform_specific_information create-def-file-automatically}@anchor{1e3}
23601 @subsubheading Creating a Definition File Automatically
23604 You can automatically create the definition file @code{API.def}
23605 (see @ref{1dd,,The Definition File}) from a DLL.
23606 For that use the @code{dlltool} program as follows:
23608 @quotation
23610 @example
23611 $ dlltool API.dll -z API.def --export-all-symbols
23612 @end example
23614 Note that if some routines in the DLL have the @code{Stdcall} convention
23615 (@ref{1d2,,Windows Calling Conventions}) with stripped @code{@@@emph{nn}}
23616 suffix then you’ll have to edit @code{api.def} to add it, and specify
23617 @code{-k} to @code{gnatdll} when creating the import library.
23619 Here are some hints to find the right @code{@@@emph{nn}} suffix.
23622 @itemize -
23624 @item 
23625 If you have the Microsoft import library (.lib), it is possible to get
23626 the right symbols by using Microsoft @code{dumpbin} tool (see the
23627 corresponding Microsoft documentation for further details).
23629 @example
23630 $ dumpbin /exports api.lib
23631 @end example
23633 @item 
23634 If you have a message about a missing symbol at link time the compiler
23635 tells you what symbol is expected. You just have to go back to the
23636 definition file and add the right suffix.
23637 @end itemize
23638 @end quotation
23639 @anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{1e4}
23640 @subsubheading GNAT-Style Import Library
23643 To create a static import library from @code{API.dll} with the GNAT tools
23644 you should create the .def file, then use @code{gnatdll} tool
23645 (see @ref{1e5,,Using gnatdll}) as follows:
23647 @quotation
23649 @example
23650 $ gnatdll -e API.def -d API.dll
23651 @end example
23653 @code{gnatdll} takes as input a definition file @code{API.def} and the
23654 name of the DLL containing the services listed in the definition file
23655 @code{API.dll}. The name of the static import library generated is
23656 computed from the name of the definition file as follows: if the
23657 definition file name is @code{xyz.def}, the import library name will
23658 be @code{libxyz.a}. Note that in the previous example option
23659 @code{-e} could have been removed because the name of the definition
23660 file (before the @code{.def} suffix) is the same as the name of the
23661 DLL (@ref{1e5,,Using gnatdll} for more information about @code{gnatdll}).
23662 @end quotation
23663 @anchor{gnat_ugn/platform_specific_information msvs-style-import-library}@anchor{1e6}
23664 @subsubheading Microsoft-Style Import Library
23667 A Microsoft import library is needed only if you plan to make an
23668 Ada DLL available to applications developed with Microsoft
23669 tools (@ref{1ce,,Mixed-Language Programming on Windows}).
23671 To create a Microsoft-style import library for @code{API.dll} you
23672 should create the .def file, then build the actual import library using
23673 Microsoft’s @code{lib} utility:
23675 @quotation
23677 @example
23678 $ lib -machine:IX86 -def:API.def -out:API.lib
23679 @end example
23681 If you use the above command the definition file @code{API.def} must
23682 contain a line giving the name of the DLL:
23684 @example
23685 LIBRARY      "API"
23686 @end example
23688 See the Microsoft documentation for further details about the usage of
23689 @code{lib}.
23690 @end quotation
23692 @node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
23693 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{1d0}@anchor{gnat_ugn/platform_specific_information id24}@anchor{1e7}
23694 @subsubsection Building DLLs with GNAT Project files
23697 @geindex DLLs
23698 @geindex building
23700 There is nothing specific to Windows in the build process.
23701 See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
23702 chapter of the @emph{GPRbuild User’s Guide}.
23704 Due to a system limitation, it is not possible under Windows to create threads
23705 when inside the @code{DllMain} routine which is used for auto-initialization
23706 of shared libraries, so it is not possible to have library level tasks in SALs.
23708 @node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
23709 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{1e8}@anchor{gnat_ugn/platform_specific_information id25}@anchor{1e9}
23710 @subsubsection Building DLLs with GNAT
23713 @geindex DLLs
23714 @geindex building
23716 This section explain how to build DLLs using the GNAT built-in DLL
23717 support. With the following procedure it is straight forward to build
23718 and use DLLs with GNAT.
23721 @itemize *
23723 @item 
23724 Building object files.
23725 The first step is to build all objects files that are to be included
23726 into the DLL. This is done by using the standard @code{gnatmake} tool.
23728 @item 
23729 Building the DLL.
23730 To build the DLL you must use the @code{gcc} @code{-shared} and
23731 @code{-shared-libgcc} options. It is quite simple to use this method:
23733 @example
23734 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
23735 @end example
23737 It is important to note that in this case all symbols found in the
23738 object files are automatically exported. It is possible to restrict
23739 the set of symbols to export by passing to @code{gcc} a definition
23740 file (see @ref{1dd,,The Definition File}).
23741 For example:
23743 @example
23744 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
23745 @end example
23747 If you use a definition file you must export the elaboration procedures
23748 for every package that required one. Elaboration procedures are named
23749 using the package name followed by “_E”.
23751 @item 
23752 Preparing DLL to be used.
23753 For the DLL to be used by client programs the bodies must be hidden
23754 from it and the .ali set with read-only attribute. This is very important
23755 otherwise GNAT will recompile all packages and will not actually use
23756 the code in the DLL. For example:
23758 @example
23759 $ mkdir apilib
23760 $ copy *.ads *.ali api.dll apilib
23761 $ attrib +R apilib\\*.ali
23762 @end example
23763 @end itemize
23765 At this point it is possible to use the DLL by directly linking
23766 against it. Note that you must use the GNAT shared runtime when using
23767 GNAT shared libraries. This is achieved by using the @code{-shared} binder
23768 option.
23770 @quotation
23772 @example
23773 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
23774 @end example
23775 @end quotation
23777 @node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
23778 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{1ea}@anchor{gnat_ugn/platform_specific_information id26}@anchor{1eb}
23779 @subsubsection Building DLLs with gnatdll
23782 @geindex DLLs
23783 @geindex building
23785 Note that it is preferred to use GNAT Project files
23786 (@ref{1d0,,Building DLLs with GNAT Project files}) or the built-in GNAT
23787 DLL support (@ref{1e8,,Building DLLs with GNAT}) or to build DLLs.
23789 This section explains how to build DLLs containing Ada code using
23790 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
23791 remainder of this section.
23793 The steps required to build an Ada DLL that is to be used by Ada as well as
23794 non-Ada applications are as follows:
23797 @itemize *
23799 @item 
23800 You need to mark each Ada entity exported by the DLL with a @code{C} or
23801 @code{Stdcall} calling convention to avoid any Ada name mangling for the
23802 entities exported by the DLL
23803 (see @ref{1ec,,Exporting Ada Entities}). You can
23804 skip this step if you plan to use the Ada DLL only from Ada applications.
23806 @item 
23807 Your Ada code must export an initialization routine which calls the routine
23808 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
23809 the Ada code in the DLL (@ref{1ed,,Ada DLLs and Elaboration}). The initialization
23810 routine exported by the Ada DLL must be invoked by the clients of the DLL
23811 to initialize the DLL.
23813 @item 
23814 When useful, the DLL should also export a finalization routine which calls
23815 routine @code{adafinal} generated by @code{gnatbind} to perform the
23816 finalization of the Ada code in the DLL (@ref{1ee,,Ada DLLs and Finalization}).
23817 The finalization routine exported by the Ada DLL must be invoked by the
23818 clients of the DLL when the DLL services are no further needed.
23820 @item 
23821 You must provide a spec for the services exported by the Ada DLL in each
23822 of the programming languages to which you plan to make the DLL available.
23824 @item 
23825 You must provide a definition file listing the exported entities
23826 (@ref{1dd,,The Definition File}).
23828 @item 
23829 Finally you must use @code{gnatdll} to produce the DLL and the import
23830 library (@ref{1e5,,Using gnatdll}).
23831 @end itemize
23833 Note that a relocatable DLL stripped using the @code{strip}
23834 binutils tool will not be relocatable anymore. To build a DLL without
23835 debug information pass @code{-largs -s} to @code{gnatdll}. This
23836 restriction does not apply to a DLL built using a Library Project.
23837 See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
23838 chapter of the @emph{GPRbuild User’s Guide}.
23840 @c Limitations_When_Using_Ada_DLLs_from Ada:
23842 @menu
23843 * Limitations When Using Ada DLLs from Ada:: 
23844 * Exporting Ada Entities:: 
23845 * Ada DLLs and Elaboration:: 
23847 @end menu
23849 @node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
23850 @anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{1ef}
23851 @subsubsection Limitations When Using Ada DLLs from Ada
23854 When using Ada DLLs from Ada applications there is a limitation users
23855 should be aware of. Because on Windows the GNAT run-time is not in a DLL of
23856 its own, each Ada DLL includes a part of the GNAT run-time. Specifically,
23857 each Ada DLL includes the services of the GNAT run-time that are necessary
23858 to the Ada code inside the DLL. As a result, when an Ada program uses an
23859 Ada DLL there are two independent GNAT run-times: one in the Ada DLL and
23860 one in the main program.
23862 It is therefore not possible to exchange GNAT run-time objects between the
23863 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
23864 handles (e.g., @code{Text_IO.File_Type}), tasks types, protected objects
23865 types, etc.
23867 It is completely safe to exchange plain elementary, array or record types,
23868 Windows object handles, etc.
23870 @node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
23871 @anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{1ec}@anchor{gnat_ugn/platform_specific_information id27}@anchor{1f0}
23872 @subsubsection Exporting Ada Entities
23875 @geindex Export table
23877 Building a DLL is a way to encapsulate a set of services usable from any
23878 application. As a result, the Ada entities exported by a DLL should be
23879 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
23880 any Ada name mangling. As an example here is an Ada package
23881 @code{API}, spec and body, exporting two procedures, a function, and a
23882 variable:
23884 @quotation
23886 @example
23887 with Interfaces.C; use Interfaces;
23888 package API is
23889    Count : C.int := 0;
23890    function Factorial (Val : C.int) return C.int;
23892    procedure Initialize_API;
23893    procedure Finalize_API;
23894    --  Initialization & Finalization routines. More in the next section.
23895 private
23896    pragma Export (C, Initialize_API);
23897    pragma Export (C, Finalize_API);
23898    pragma Export (C, Count);
23899    pragma Export (C, Factorial);
23900 end API;
23901 @end example
23903 @example
23904 package body API is
23905    function Factorial (Val : C.int) return C.int is
23906       Fact : C.int := 1;
23907    begin
23908       Count := Count + 1;
23909       for K in 1 .. Val loop
23910          Fact := Fact * K;
23911       end loop;
23912       return Fact;
23913    end Factorial;
23915    procedure Initialize_API is
23916       procedure Adainit;
23917       pragma Import (C, Adainit);
23918    begin
23919       Adainit;
23920    end Initialize_API;
23922    procedure Finalize_API is
23923       procedure Adafinal;
23924       pragma Import (C, Adafinal);
23925    begin
23926       Adafinal;
23927    end Finalize_API;
23928 end API;
23929 @end example
23930 @end quotation
23932 If the Ada DLL you are building will only be used by Ada applications
23933 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
23934 convention. As an example, the previous package could be written as
23935 follows:
23937 @quotation
23939 @example
23940 package API is
23941    Count : Integer := 0;
23942    function Factorial (Val : Integer) return Integer;
23944    procedure Initialize_API;
23945    procedure Finalize_API;
23946    --  Initialization and Finalization routines.
23947 end API;
23948 @end example
23950 @example
23951 package body API is
23952    function Factorial (Val : Integer) return Integer is
23953       Fact : Integer := 1;
23954    begin
23955       Count := Count + 1;
23956       for K in 1 .. Val loop
23957          Fact := Fact * K;
23958       end loop;
23959       return Fact;
23960    end Factorial;
23962    ...
23963    --  The remainder of this package body is unchanged.
23964 end API;
23965 @end example
23966 @end quotation
23968 Note that if you do not export the Ada entities with a @code{C} or
23969 @code{Stdcall} convention you will have to provide the mangled Ada names
23970 in the definition file of the Ada DLL
23971 (@ref{1f1,,Creating the Definition File}).
23973 @node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
23974 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{1ed}@anchor{gnat_ugn/platform_specific_information id28}@anchor{1f2}
23975 @subsubsection Ada DLLs and Elaboration
23978 @geindex DLLs and elaboration
23980 The DLL that you are building contains your Ada code as well as all the
23981 routines in the Ada library that are needed by it. The first thing a
23982 user of your DLL must do is elaborate the Ada code
23983 (@ref{f,,Elaboration Order Handling in GNAT}).
23985 To achieve this you must export an initialization routine
23986 (@code{Initialize_API} in the previous example), which must be invoked
23987 before using any of the DLL services. This elaboration routine must call
23988 the Ada elaboration routine @code{adainit} generated by the GNAT binder
23989 (@ref{a0,,Binding with Non-Ada Main Programs}). See the body of
23990 @code{Initialize_Api} for an example. Note that the GNAT binder is
23991 automatically invoked during the DLL build process by the @code{gnatdll}
23992 tool (@ref{1e5,,Using gnatdll}).
23994 When a DLL is loaded, Windows systematically invokes a routine called
23995 @code{DllMain}. It would therefore be possible to call @code{adainit}
23996 directly from @code{DllMain} without having to provide an explicit
23997 initialization routine. Unfortunately, it is not possible to call
23998 @code{adainit} from the @code{DllMain} if your program has library level
23999 tasks because access to the @code{DllMain} entry point is serialized by
24000 the system (that is, only a single thread can execute ‘through’ it at a
24001 time), which means that the GNAT run-time will deadlock waiting for the
24002 newly created task to complete its initialization.
24004 @node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
24005 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{1ee}@anchor{gnat_ugn/platform_specific_information id29}@anchor{1f3}
24006 @subsubsection Ada DLLs and Finalization
24009 @geindex DLLs and finalization
24011 When the services of an Ada DLL are no longer needed, the client code should
24012 invoke the DLL finalization routine, if available. The DLL finalization
24013 routine is in charge of releasing all resources acquired by the DLL. In the
24014 case of the Ada code contained in the DLL, this is achieved by calling
24015 routine @code{adafinal} generated by the GNAT binder
24016 (@ref{a0,,Binding with Non-Ada Main Programs}).
24017 See the body of @code{Finalize_Api} for an
24018 example. As already pointed out the GNAT binder is automatically invoked
24019 during the DLL build process by the @code{gnatdll} tool
24020 (@ref{1e5,,Using gnatdll}).
24022 @node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
24023 @anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{1f4}@anchor{gnat_ugn/platform_specific_information id30}@anchor{1f5}
24024 @subsubsection Creating a Spec for Ada DLLs
24027 To use the services exported by the Ada DLL from another programming
24028 language (e.g., C), you have to translate the specs of the exported Ada
24029 entities in that language. For instance in the case of @code{API.dll},
24030 the corresponding C header file could look like:
24032 @quotation
24034 @example
24035 extern int *_imp__count;
24036 #define count (*_imp__count)
24037 int factorial (int);
24038 @end example
24039 @end quotation
24041 It is important to understand that when building an Ada DLL to be used by
24042 other Ada applications, you need two different specs for the packages
24043 contained in the DLL: one for building the DLL and the other for using
24044 the DLL. This is because the @code{DLL} calling convention is needed to
24045 use a variable defined in a DLL, but when building the DLL, the variable
24046 must have either the @code{Ada} or @code{C} calling convention. As an
24047 example consider a DLL comprising the following package @code{API}:
24049 @quotation
24051 @example
24052 package API is
24053    Count : Integer := 0;
24054    ...
24055    --  Remainder of the package omitted.
24056 end API;
24057 @end example
24058 @end quotation
24060 After producing a DLL containing package @code{API}, the spec that
24061 must be used to import @code{API.Count} from Ada code outside of the
24062 DLL is:
24064 @quotation
24066 @example
24067 package API is
24068    Count : Integer;
24069    pragma Import (DLL, Count);
24070 end API;
24071 @end example
24072 @end quotation
24074 @menu
24075 * Creating the Definition File:: 
24076 * Using gnatdll:: 
24078 @end menu
24080 @node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
24081 @anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{1f1}@anchor{gnat_ugn/platform_specific_information id31}@anchor{1f6}
24082 @subsubsection Creating the Definition File
24085 The definition file is the last file needed to build the DLL. It lists
24086 the exported symbols. As an example, the definition file for a DLL
24087 containing only package @code{API} (where all the entities are exported
24088 with a @code{C} calling convention) is:
24090 @quotation
24092 @example
24093 EXPORTS
24094     count
24095     factorial
24096     finalize_api
24097     initialize_api
24098 @end example
24099 @end quotation
24101 If the @code{C} calling convention is missing from package @code{API},
24102 then the definition file contains the mangled Ada names of the above
24103 entities, which in this case are:
24105 @quotation
24107 @example
24108 EXPORTS
24109     api__count
24110     api__factorial
24111     api__finalize_api
24112     api__initialize_api
24113 @end example
24114 @end quotation
24116 @node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
24117 @anchor{gnat_ugn/platform_specific_information id32}@anchor{1f7}@anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{1e5}
24118 @subsubsection Using @code{gnatdll}
24121 @geindex gnatdll
24123 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
24124 and non-Ada sources that make up your DLL have been compiled.
24125 @code{gnatdll} is actually in charge of two distinct tasks: build the
24126 static import library for the DLL and the actual DLL. The form of the
24127 @code{gnatdll} command is
24129 @quotation
24131 @example
24132 $ gnatdll [ switches ] list-of-files [ -largs opts ]
24133 @end example
24134 @end quotation
24136 where @code{list-of-files} is a list of ALI and object files. The object
24137 file list must be the exact list of objects corresponding to the non-Ada
24138 sources whose services are to be included in the DLL. The ALI file list
24139 must be the exact list of ALI files for the corresponding Ada sources
24140 whose services are to be included in the DLL. If @code{list-of-files} is
24141 missing, only the static import library is generated.
24143 You may specify any of the following switches to @code{gnatdll}:
24145 @quotation
24147 @geindex -a (gnatdll)
24148 @end quotation
24151 @table @asis
24153 @item @code{-a[@emph{address}]}
24155 Build a non-relocatable DLL at @code{address}. If @code{address} is not
24156 specified the default address @code{0x11000000} will be used. By default,
24157 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
24158 advise the reader to build relocatable DLL.
24160 @geindex -b (gnatdll)
24162 @item @code{-b @emph{address}}
24164 Set the relocatable DLL base address. By default the address is
24165 @code{0x11000000}.
24167 @geindex -bargs (gnatdll)
24169 @item @code{-bargs @emph{opts}}
24171 Binder options. Pass @code{opts} to the binder.
24173 @geindex -d (gnatdll)
24175 @item @code{-d @emph{dllfile}}
24177 @code{dllfile} is the name of the DLL. This switch must be present for
24178 @code{gnatdll} to do anything. The name of the generated import library is
24179 obtained algorithmically from @code{dllfile} as shown in the following
24180 example: if @code{dllfile} is @code{xyz.dll}, the import library name is
24181 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
24182 by option @code{-e}) is obtained algorithmically from @code{dllfile}
24183 as shown in the following example:
24184 if @code{dllfile} is @code{xyz.dll}, the definition
24185 file used is @code{xyz.def}.
24187 @geindex -e (gnatdll)
24189 @item @code{-e @emph{deffile}}
24191 @code{deffile} is the name of the definition file.
24193 @geindex -g (gnatdll)
24195 @item @code{-g}
24197 Generate debugging information. This information is stored in the object
24198 file and copied from there to the final DLL file by the linker,
24199 where it can be read by the debugger. You must use the
24200 @code{-g} switch if you plan on using the debugger or the symbolic
24201 stack traceback.
24203 @geindex -h (gnatdll)
24205 @item @code{-h}
24207 Help mode. Displays @code{gnatdll} switch usage information.
24209 @geindex -I (gnatdll)
24211 @item @code{-I@emph{dir}}
24213 Direct @code{gnatdll} to search the @code{dir} directory for source and
24214 object files needed to build the DLL.
24215 (@ref{73,,Search Paths and the Run-Time Library (RTL)}).
24217 @geindex -k (gnatdll)
24219 @item @code{-k}
24221 Removes the @code{@@@emph{nn}} suffix from the import library’s exported
24222 names, but keeps them for the link names. You must specify this
24223 option if you want to use a @code{Stdcall} function in a DLL for which
24224 the @code{@@@emph{nn}} suffix has been removed. This is the case for most
24225 of the Windows NT DLL for example. This option has no effect when
24226 @code{-n} option is specified.
24228 @geindex -l (gnatdll)
24230 @item @code{-l @emph{file}}
24232 The list of ALI and object files used to build the DLL are listed in
24233 @code{file}, instead of being given in the command line. Each line in
24234 @code{file} contains the name of an ALI or object file.
24236 @geindex -n (gnatdll)
24238 @item @code{-n}
24240 No Import. Do not create the import library.
24242 @geindex -q (gnatdll)
24244 @item @code{-q}
24246 Quiet mode. Do not display unnecessary messages.
24248 @geindex -v (gnatdll)
24250 @item @code{-v}
24252 Verbose mode. Display extra information.
24254 @geindex -largs (gnatdll)
24256 @item @code{-largs @emph{opts}}
24258 Linker options. Pass @code{opts} to the linker.
24259 @end table
24261 @subsubheading @code{gnatdll} Example
24264 As an example the command to build a relocatable DLL from @code{api.adb}
24265 once @code{api.adb} has been compiled and @code{api.def} created is
24267 @quotation
24269 @example
24270 $ gnatdll -d api.dll api.ali
24271 @end example
24272 @end quotation
24274 The above command creates two files: @code{libapi.dll.a} (the import
24275 library) and @code{api.dll} (the actual DLL). If you want to create
24276 only the DLL, just type:
24278 @quotation
24280 @example
24281 $ gnatdll -d api.dll -n api.ali
24282 @end example
24283 @end quotation
24285 Alternatively if you want to create just the import library, type:
24287 @quotation
24289 @example
24290 $ gnatdll -d api.dll
24291 @end example
24292 @end quotation
24294 @subsubheading @code{gnatdll} behind the Scenes
24297 This section details the steps involved in creating a DLL. @code{gnatdll}
24298 does these steps for you. Unless you are interested in understanding what
24299 goes on behind the scenes, you should skip this section.
24301 We use the previous example of a DLL containing the Ada package @code{API},
24302 to illustrate the steps necessary to build a DLL. The starting point is a
24303 set of objects that will make up the DLL and the corresponding ALI
24304 files. In the case of this example this means that @code{api.o} and
24305 @code{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
24306 the following:
24309 @itemize *
24311 @item 
24312 @code{gnatdll} builds the base file (@code{api.base}). A base file gives
24313 the information necessary to generate relocation information for the
24314 DLL.
24316 @example
24317 $ gnatbind -n api
24318 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
24319 @end example
24321 In addition to the base file, the @code{gnatlink} command generates an
24322 output file @code{api.jnk} which can be discarded. The @code{-mdll} switch
24323 asks @code{gnatlink} to generate the routines @code{DllMain} and
24324 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
24325 is loaded into memory.
24327 @item 
24328 @code{gnatdll} uses @code{dlltool} (see @ref{1f8,,Using dlltool}) to build the
24329 export table (@code{api.exp}). The export table contains the relocation
24330 information in a form which can be used during the final link to ensure
24331 that the Windows loader is able to place the DLL anywhere in memory.
24333 @example
24334 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
24335           --output-exp api.exp
24336 @end example
24338 @item 
24339 @code{gnatdll} builds the base file using the new export table. Note that
24340 @code{gnatbind} must be called once again since the binder generated file
24341 has been deleted during the previous call to @code{gnatlink}.
24343 @example
24344 $ gnatbind -n api
24345 $ gnatlink api -o api.jnk api.exp -mdll
24346       -Wl,--base-file,api.base
24347 @end example
24349 @item 
24350 @code{gnatdll} builds the new export table using the new base file and
24351 generates the DLL import library @code{libAPI.dll.a}.
24353 @example
24354 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
24355           --output-exp api.exp --output-lib libAPI.a
24356 @end example
24358 @item 
24359 Finally @code{gnatdll} builds the relocatable DLL using the final export
24360 table.
24362 @example
24363 $ gnatbind -n api
24364 $ gnatlink api api.exp -o api.dll -mdll
24365 @end example
24366 @end itemize
24367 @anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{1f8}
24368 @subsubheading Using @code{dlltool}
24371 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
24372 DLLs and static import libraries. This section summarizes the most
24373 common @code{dlltool} switches. The form of the @code{dlltool} command
24376 @quotation
24378 @example
24379 $ dlltool [`switches`]
24380 @end example
24381 @end quotation
24383 @code{dlltool} switches include:
24385 @geindex --base-file (dlltool)
24388 @table @asis
24390 @item @code{--base-file @emph{basefile}}
24392 Read the base file @code{basefile} generated by the linker. This switch
24393 is used to create a relocatable DLL.
24394 @end table
24396 @geindex --def (dlltool)
24399 @table @asis
24401 @item @code{--def @emph{deffile}}
24403 Read the definition file.
24404 @end table
24406 @geindex --dllname (dlltool)
24409 @table @asis
24411 @item @code{--dllname @emph{name}}
24413 Gives the name of the DLL. This switch is used to embed the name of the
24414 DLL in the static import library generated by @code{dlltool} with switch
24415 @code{--output-lib}.
24416 @end table
24418 @geindex -k (dlltool)
24421 @table @asis
24423 @item @code{-k}
24425 Kill @code{@@@emph{nn}} from exported names
24426 (@ref{1d2,,Windows Calling Conventions}
24427 for a discussion about @code{Stdcall}-style symbols).
24428 @end table
24430 @geindex --help (dlltool)
24433 @table @asis
24435 @item @code{--help}
24437 Prints the @code{dlltool} switches with a concise description.
24438 @end table
24440 @geindex --output-exp (dlltool)
24443 @table @asis
24445 @item @code{--output-exp @emph{exportfile}}
24447 Generate an export file @code{exportfile}. The export file contains the
24448 export table (list of symbols in the DLL) and is used to create the DLL.
24449 @end table
24451 @geindex --output-lib (dlltool)
24454 @table @asis
24456 @item @code{--output-lib @emph{libfile}}
24458 Generate a static import library @code{libfile}.
24459 @end table
24461 @geindex -v (dlltool)
24464 @table @asis
24466 @item @code{-v}
24468 Verbose mode.
24469 @end table
24471 @geindex --as (dlltool)
24474 @table @asis
24476 @item @code{--as @emph{assembler-name}}
24478 Use @code{assembler-name} as the assembler. The default is @code{as}.
24479 @end table
24481 @node GNAT and Windows Resources,Using GNAT DLLs from Microsoft Visual Studio Applications,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
24482 @anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{1f9}@anchor{gnat_ugn/platform_specific_information id33}@anchor{1fa}
24483 @subsubsection GNAT and Windows Resources
24486 @geindex Resources
24487 @geindex windows
24489 Resources are an easy way to add Windows specific objects to your
24490 application. The objects that can be added as resources include:
24493 @itemize *
24495 @item 
24496 menus
24498 @item 
24499 accelerators
24501 @item 
24502 dialog boxes
24504 @item 
24505 string tables
24507 @item 
24508 bitmaps
24510 @item 
24511 cursors
24513 @item 
24514 icons
24516 @item 
24517 fonts
24519 @item 
24520 version information
24521 @end itemize
24523 For example, a version information resource can be defined as follow and
24524 embedded into an executable or DLL:
24526 A version information resource can be used to embed information into an
24527 executable or a DLL. These information can be viewed using the file properties
24528 from the Windows Explorer. Here is an example of a version information
24529 resource:
24531 @quotation
24533 @example
24534 1 VERSIONINFO
24535 FILEVERSION     1,0,0,0
24536 PRODUCTVERSION  1,0,0,0
24537 BEGIN
24538   BLOCK "StringFileInfo"
24539   BEGIN
24540     BLOCK "080904E4"
24541     BEGIN
24542       VALUE "CompanyName", "My Company Name"
24543       VALUE "FileDescription", "My application"
24544       VALUE "FileVersion", "1.0"
24545       VALUE "InternalName", "my_app"
24546       VALUE "LegalCopyright", "My Name"
24547       VALUE "OriginalFilename", "my_app.exe"
24548       VALUE "ProductName", "My App"
24549       VALUE "ProductVersion", "1.0"
24550     END
24551   END
24553   BLOCK "VarFileInfo"
24554   BEGIN
24555     VALUE "Translation", 0x809, 1252
24556   END
24558 @end example
24559 @end quotation
24561 The value @code{0809} (langID) is for the U.K English language and
24562 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
24563 multilingual.
24565 This section explains how to build, compile and use resources. Note that this
24566 section does not cover all resource objects, for a complete description see
24567 the corresponding Microsoft documentation.
24569 @menu
24570 * Building Resources:: 
24571 * Compiling Resources:: 
24572 * Using Resources:: 
24574 @end menu
24576 @node Building Resources,Compiling Resources,,GNAT and Windows Resources
24577 @anchor{gnat_ugn/platform_specific_information building-resources}@anchor{1fb}@anchor{gnat_ugn/platform_specific_information id34}@anchor{1fc}
24578 @subsubsection Building Resources
24581 @geindex Resources
24582 @geindex building
24584 A resource file is an ASCII file. By convention resource files have an
24585 @code{.rc} extension.
24586 The easiest way to build a resource file is to use Microsoft tools
24587 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
24588 @code{dlgedit.exe} to build dialogs.
24589 It is always possible to build an @code{.rc} file yourself by writing a
24590 resource script.
24592 It is not our objective to explain how to write a resource file. A
24593 complete description of the resource script language can be found in the
24594 Microsoft documentation.
24596 @node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
24597 @anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{1fd}@anchor{gnat_ugn/platform_specific_information id35}@anchor{1fe}
24598 @subsubsection Compiling Resources
24601 @geindex rc
24603 @geindex windres
24605 @geindex Resources
24606 @geindex compiling
24608 This section describes how to build a GNAT-compatible (COFF) object file
24609 containing the resources. This is done using the Resource Compiler
24610 @code{windres} as follows:
24612 @quotation
24614 @example
24615 $ windres -i myres.rc -o myres.o
24616 @end example
24617 @end quotation
24619 By default @code{windres} will run @code{gcc} to preprocess the @code{.rc}
24620 file. You can specify an alternate preprocessor (usually named
24621 @code{cpp.exe}) using the @code{windres} @code{--preprocessor}
24622 parameter. A list of all possible options may be obtained by entering
24623 the command @code{windres} @code{--help}.
24625 It is also possible to use the Microsoft resource compiler @code{rc.exe}
24626 to produce a @code{.res} file (binary resource file). See the
24627 corresponding Microsoft documentation for further details. In this case
24628 you need to use @code{windres} to translate the @code{.res} file to a
24629 GNAT-compatible object file as follows:
24631 @quotation
24633 @example
24634 $ windres -i myres.res -o myres.o
24635 @end example
24636 @end quotation
24638 @node Using Resources,,Compiling Resources,GNAT and Windows Resources
24639 @anchor{gnat_ugn/platform_specific_information id36}@anchor{1ff}@anchor{gnat_ugn/platform_specific_information using-resources}@anchor{200}
24640 @subsubsection Using Resources
24643 @geindex Resources
24644 @geindex using
24646 To include the resource file in your program just add the
24647 GNAT-compatible object file for the resource(s) to the linker
24648 arguments. With @code{gnatmake} this is done by using the @code{-largs}
24649 option:
24651 @quotation
24653 @example
24654 $ gnatmake myprog -largs myres.o
24655 @end example
24656 @end quotation
24658 @node Using GNAT DLLs from Microsoft Visual Studio Applications,Debugging a DLL,GNAT and Windows Resources,Mixed-Language Programming on Windows
24659 @anchor{gnat_ugn/platform_specific_information using-gnat-dll-from-msvs}@anchor{201}@anchor{gnat_ugn/platform_specific_information using-gnat-dlls-from-microsoft-visual-studio-applications}@anchor{202}
24660 @subsubsection Using GNAT DLLs from Microsoft Visual Studio Applications
24663 @geindex Microsoft Visual Studio
24664 @geindex use with GNAT DLLs
24666 This section describes a common case of mixed GNAT/Microsoft Visual Studio
24667 application development, where the main program is developed using MSVS, and
24668 is linked with a DLL developed using GNAT. Such a mixed application should
24669 be developed following the general guidelines outlined above; below is the
24670 cookbook-style sequence of steps to follow:
24673 @enumerate 
24675 @item 
24676 First develop and build the GNAT shared library using a library project
24677 (let’s assume the project is @code{mylib.gpr}, producing the library @code{libmylib.dll}):
24678 @end enumerate
24680 @quotation
24682 @example
24683 $ gprbuild -p mylib.gpr
24684 @end example
24685 @end quotation
24688 @enumerate 2
24690 @item 
24691 Produce a .def file for the symbols you need to interface with, either by
24692 hand or automatically with possibly some manual adjustments
24693 (see @ref{1e3,,Creating Definition File Automatically}):
24694 @end enumerate
24696 @quotation
24698 @example
24699 $ dlltool libmylib.dll -z libmylib.def --export-all-symbols
24700 @end example
24701 @end quotation
24704 @enumerate 3
24706 @item 
24707 Make sure that MSVS command-line tools are accessible on the path.
24709 @item 
24710 Create the Microsoft-style import library (see @ref{1e6,,MSVS-Style Import Library}):
24711 @end enumerate
24713 @quotation
24715 @example
24716 $ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
24717 @end example
24718 @end quotation
24720 If you are using a 64-bit toolchain, the above becomes…
24722 @quotation
24724 @example
24725 $ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
24726 @end example
24727 @end quotation
24730 @enumerate 5
24732 @item 
24733 Build the C main
24734 @end enumerate
24736 @quotation
24738 @example
24739 $ cl /O2 /MD main.c libmylib.lib
24740 @end example
24741 @end quotation
24744 @enumerate 6
24746 @item 
24747 Before running the executable, make sure you have set the PATH to the DLL,
24748 or copy the DLL into into the directory containing the .exe.
24749 @end enumerate
24751 @node Debugging a DLL,Setting Stack Size from gnatlink,Using GNAT DLLs from Microsoft Visual Studio Applications,Mixed-Language Programming on Windows
24752 @anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{203}@anchor{gnat_ugn/platform_specific_information id37}@anchor{204}
24753 @subsubsection Debugging a DLL
24756 @geindex DLL debugging
24758 Debugging a DLL is similar to debugging a standard program. But
24759 we have to deal with two different executable parts: the DLL and the
24760 program that uses it. We have the following four possibilities:
24763 @itemize *
24765 @item 
24766 The program and the DLL are built with GCC/GNAT.
24768 @item 
24769 The program is built with foreign tools and the DLL is built with
24770 GCC/GNAT.
24772 @item 
24773 The program is built with GCC/GNAT and the DLL is built with
24774 foreign tools.
24775 @end itemize
24777 In this section we address only cases one and two above.
24778 There is no point in trying to debug
24779 a DLL with GNU/GDB, if there is no GDB-compatible debugging
24780 information in it. To do so you must use a debugger compatible with the
24781 tools suite used to build the DLL.
24783 @menu
24784 * Program and DLL Both Built with GCC/GNAT:: 
24785 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
24787 @end menu
24789 @node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
24790 @anchor{gnat_ugn/platform_specific_information id38}@anchor{205}@anchor{gnat_ugn/platform_specific_information program-and-dll-both-built-with-gcc-gnat}@anchor{206}
24791 @subsubsection Program and DLL Both Built with GCC/GNAT
24794 This is the simplest case. Both the DLL and the program have @code{GDB}
24795 compatible debugging information. It is then possible to break anywhere in
24796 the process. Let’s suppose here that the main procedure is named
24797 @code{ada_main} and that in the DLL there is an entry point named
24798 @code{ada_dll}.
24800 The DLL (@ref{1dc,,Introduction to Dynamic Link Libraries (DLLs)}) and
24801 program must have been built with the debugging information (see GNAT -g
24802 switch). Here are the step-by-step instructions for debugging it:
24805 @itemize *
24807 @item 
24808 Launch @code{GDB} on the main program.
24810 @example
24811 $ gdb -nw ada_main
24812 @end example
24814 @item 
24815 Start the program and stop at the beginning of the main procedure
24817 @example
24818 (gdb) start
24819 @end example
24821 This step is required to be able to set a breakpoint inside the DLL. As long
24822 as the program is not run, the DLL is not loaded. This has the
24823 consequence that the DLL debugging information is also not loaded, so it is not
24824 possible to set a breakpoint in the DLL.
24826 @item 
24827 Set a breakpoint inside the DLL
24829 @example
24830 (gdb) break ada_dll
24831 (gdb) cont
24832 @end example
24833 @end itemize
24835 At this stage a breakpoint is set inside the DLL. From there on
24836 you can use the standard approach to debug the whole program
24837 (@ref{14d,,Running and Debugging Ada Programs}).
24839 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
24840 @anchor{gnat_ugn/platform_specific_information id39}@anchor{207}@anchor{gnat_ugn/platform_specific_information program-built-with-foreign-tools-and-dll-built-with-gcc-gnat}@anchor{208}
24841 @subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
24844 In this case things are slightly more complex because it is not possible to
24845 start the main program and then break at the beginning to load the DLL and the
24846 associated DLL debugging information. It is not possible to break at the
24847 beginning of the program because there is no @code{GDB} debugging information,
24848 and therefore there is no direct way of getting initial control. This
24849 section addresses this issue by describing some methods that can be used
24850 to break somewhere in the DLL to debug it.
24852 First suppose that the main procedure is named @code{main} (this is for
24853 example some C code built with Microsoft Visual C) and that there is a
24854 DLL named @code{test.dll} containing an Ada entry point named
24855 @code{ada_dll}.
24857 The DLL (see @ref{1dc,,Introduction to Dynamic Link Libraries (DLLs)}) must have
24858 been built with debugging information (see the GNAT @code{-g} option).
24860 @subsubheading Debugging the DLL Directly
24864 @itemize *
24866 @item 
24867 Find out the executable starting address
24869 @example
24870 $ objdump --file-header main.exe
24871 @end example
24873 The starting address is reported on the last line. For example:
24875 @example
24876 main.exe:     file format pei-i386
24877 architecture: i386, flags 0x0000010a:
24878 EXEC_P, HAS_DEBUG, D_PAGED
24879 start address 0x00401010
24880 @end example
24882 @item 
24883 Launch the debugger on the executable.
24885 @example
24886 $ gdb main.exe
24887 @end example
24889 @item 
24890 Set a breakpoint at the starting address, and launch the program.
24892 @example
24893 $ (gdb) break *0x00401010
24894 $ (gdb) run
24895 @end example
24897 The program will stop at the given address.
24899 @item 
24900 Set a breakpoint on a DLL subroutine.
24902 @example
24903 (gdb) break ada_dll.adb:45
24904 @end example
24906 Or if you want to break using a symbol on the DLL, you need first to
24907 select the Ada language (language used by the DLL).
24909 @example
24910 (gdb) set language ada
24911 (gdb) break ada_dll
24912 @end example
24914 @item 
24915 Continue the program.
24917 @example
24918 (gdb) cont
24919 @end example
24921 This will run the program until it reaches the breakpoint that has been
24922 set. From that point you can use the standard way to debug a program
24923 as described in (@ref{14d,,Running and Debugging Ada Programs}).
24924 @end itemize
24926 It is also possible to debug the DLL by attaching to a running process.
24928 @subsubheading Attaching to a Running Process
24931 @geindex DLL debugging
24932 @geindex attach to process
24934 With @code{GDB} it is always possible to debug a running process by
24935 attaching to it. It is possible to debug a DLL this way. The limitation
24936 of this approach is that the DLL must run long enough to perform the
24937 attach operation. It may be useful for instance to insert a time wasting
24938 loop in the code of the DLL to meet this criterion.
24941 @itemize *
24943 @item 
24944 Launch the main program @code{main.exe}.
24946 @example
24947 $ main
24948 @end example
24950 @item 
24951 Use the Windows @emph{Task Manager} to find the process ID. Let’s say
24952 that the process PID for @code{main.exe} is 208.
24954 @item 
24955 Launch gdb.
24957 @example
24958 $ gdb
24959 @end example
24961 @item 
24962 Attach to the running process to be debugged.
24964 @example
24965 (gdb) attach 208
24966 @end example
24968 @item 
24969 Load the process debugging information.
24971 @example
24972 (gdb) symbol-file main.exe
24973 @end example
24975 @item 
24976 Break somewhere in the DLL.
24978 @example
24979 (gdb) break ada_dll
24980 @end example
24982 @item 
24983 Continue process execution.
24985 @example
24986 (gdb) cont
24987 @end example
24988 @end itemize
24990 This last step will resume the process execution, and stop at
24991 the breakpoint we have set. From there you can use the standard
24992 approach to debug a program as described in
24993 @ref{14d,,Running and Debugging Ada Programs}.
24995 @node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
24996 @anchor{gnat_ugn/platform_specific_information id40}@anchor{209}@anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{127}
24997 @subsubsection Setting Stack Size from @code{gnatlink}
25000 It is possible to specify the program stack size at link time. On modern
25001 versions of Windows, starting with XP, this is mostly useful to set the size of
25002 the main stack (environment task). The other task stacks are set with pragma
25003 Storage_Size or with the @emph{gnatbind -d} command.
25005 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
25006 reserve size of individual tasks, the link-time stack size applies to all
25007 tasks, and pragma Storage_Size has no effect.
25008 In particular, Stack Overflow checks are made against this
25009 link-time specified size.
25011 This setting can be done with @code{gnatlink} using either of the following:
25014 @itemize *
25016 @item 
25017 @code{-Xlinker} linker option
25019 @example
25020 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
25021 @end example
25023 This sets the stack reserve size to 0x10000 bytes and the stack commit
25024 size to 0x1000 bytes.
25026 @item 
25027 @code{-Wl} linker option
25029 @example
25030 $ gnatlink hello -Wl,--stack=0x1000000
25031 @end example
25033 This sets the stack reserve size to 0x1000000 bytes. Note that with
25034 @code{-Wl} option it is not possible to set the stack commit size
25035 because the comma is a separator for this option.
25036 @end itemize
25038 @node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
25039 @anchor{gnat_ugn/platform_specific_information id41}@anchor{20a}@anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{128}
25040 @subsubsection Setting Heap Size from @code{gnatlink}
25043 Under Windows systems, it is possible to specify the program heap size from
25044 @code{gnatlink} using either of the following:
25047 @itemize *
25049 @item 
25050 @code{-Xlinker} linker option
25052 @example
25053 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
25054 @end example
25056 This sets the heap reserve size to 0x10000 bytes and the heap commit
25057 size to 0x1000 bytes.
25059 @item 
25060 @code{-Wl} linker option
25062 @example
25063 $ gnatlink hello -Wl,--heap=0x1000000
25064 @end example
25066 This sets the heap reserve size to 0x1000000 bytes. Note that with
25067 @code{-Wl} option it is not possible to set the heap commit size
25068 because the comma is a separator for this option.
25069 @end itemize
25071 @node Windows Specific Add-Ons,,Mixed-Language Programming on Windows,Microsoft Windows Topics
25072 @anchor{gnat_ugn/platform_specific_information win32-specific-addons}@anchor{20b}@anchor{gnat_ugn/platform_specific_information windows-specific-add-ons}@anchor{20c}
25073 @subsection Windows Specific Add-Ons
25076 This section describes the Windows specific add-ons.
25078 @menu
25079 * Win32Ada:: 
25080 * wPOSIX:: 
25082 @end menu
25084 @node Win32Ada,wPOSIX,,Windows Specific Add-Ons
25085 @anchor{gnat_ugn/platform_specific_information id42}@anchor{20d}@anchor{gnat_ugn/platform_specific_information win32ada}@anchor{20e}
25086 @subsubsection Win32Ada
25089 Win32Ada is a binding for the Microsoft Win32 API. This binding can be
25090 easily installed from the provided installer. To use the Win32Ada
25091 binding you need to use a project file, and adding a single with_clause
25092 will give you full access to the Win32Ada binding sources and ensure
25093 that the proper libraries are passed to the linker.
25095 @quotation
25097 @example
25098 with "win32ada";
25099 project P is
25100    for Sources use ...;
25101 end P;
25102 @end example
25103 @end quotation
25105 To build the application you just need to call gprbuild for the
25106 application’s project, here p.gpr:
25108 @quotation
25110 @example
25111 gprbuild p.gpr
25112 @end example
25113 @end quotation
25115 @node wPOSIX,,Win32Ada,Windows Specific Add-Ons
25116 @anchor{gnat_ugn/platform_specific_information id43}@anchor{20f}@anchor{gnat_ugn/platform_specific_information wposix}@anchor{210}
25117 @subsubsection wPOSIX
25120 wPOSIX is a minimal POSIX binding whose goal is to help with building
25121 cross-platforms applications. This binding is not complete though, as
25122 the Win32 API does not provide the necessary support for all POSIX APIs.
25124 To use the wPOSIX binding you need to use a project file, and adding
25125 a single with_clause will give you full access to the wPOSIX binding
25126 sources and ensure that the proper libraries are passed to the linker.
25128 @quotation
25130 @example
25131 with "wposix";
25132 project P is
25133    for Sources use ...;
25134 end P;
25135 @end example
25136 @end quotation
25138 To build the application you just need to call gprbuild for the
25139 application’s project, here p.gpr:
25141 @quotation
25143 @example
25144 gprbuild p.gpr
25145 @end example
25146 @end quotation
25148 @node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
25149 @anchor{gnat_ugn/platform_specific_information id44}@anchor{211}@anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{212}
25150 @section Mac OS Topics
25153 @geindex OS X
25155 This section describes topics that are specific to Apple’s OS X
25156 platform.
25158 @menu
25159 * Codesigning the Debugger:: 
25161 @end menu
25163 @node Codesigning the Debugger,,,Mac OS Topics
25164 @anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{213}
25165 @subsection Codesigning the Debugger
25168 The Darwin Kernel requires the debugger to have special permissions
25169 before it is allowed to control other processes. These permissions
25170 are granted by codesigning the GDB executable. Without these
25171 permissions, the debugger will report error messages such as:
25173 @example
25174 Starting program: /x/y/foo
25175 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
25176 (please check gdb is codesigned - see taskgated(8))
25177 @end example
25179 Codesigning requires a certificate.  The following procedure explains
25180 how to create one:
25183 @itemize *
25185 @item 
25186 Start the Keychain Access application (in
25187 /Applications/Utilities/Keychain Access.app)
25189 @item 
25190 Select the Keychain Access -> Certificate Assistant ->
25191 Create a Certificate… menu
25193 @item 
25194 Then:
25197 @itemize *
25199 @item 
25200 Choose a name for the new certificate (this procedure will use
25201 “gdb-cert” as an example)
25203 @item 
25204 Set “Identity Type” to “Self Signed Root”
25206 @item 
25207 Set “Certificate Type” to “Code Signing”
25209 @item 
25210 Activate the “Let me override defaults” option
25211 @end itemize
25213 @item 
25214 Click several times on “Continue” until the “Specify a Location
25215 For The Certificate” screen appears, then set “Keychain” to “System”
25217 @item 
25218 Click on “Continue” until the certificate is created
25220 @item 
25221 Finally, in the view, double-click on the new certificate,
25222 and set “When using this certificate” to “Always Trust”
25224 @item 
25225 Exit the Keychain Access application and restart the computer
25226 (this is unfortunately required)
25227 @end itemize
25229 Once a certificate has been created, the debugger can be codesigned
25230 as follow. In a Terminal, run the following command:
25232 @quotation
25234 @example
25235 $ codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
25236 @end example
25237 @end quotation
25239 where “gdb-cert” should be replaced by the actual certificate
25240 name chosen above, and <gnat_install_prefix> should be replaced by
25241 the location where you installed GNAT.  Also, be sure that users are
25242 in the Unix group @code{_developer}.
25244 @node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
25245 @anchor{gnat_ugn/example_of_binder_output doc}@anchor{214}@anchor{gnat_ugn/example_of_binder_output example-of-binder-output-file}@anchor{e}@anchor{gnat_ugn/example_of_binder_output id1}@anchor{215}
25246 @chapter Example of Binder Output File
25249 @geindex Binder output (example)
25251 This Appendix displays the source code for the output file
25252 generated by @emph{gnatbind} for a simple ‘Hello World’ program.
25253 Comments have been added for clarification purposes.
25255 @example
25256 --  The package is called Ada_Main unless this name is actually used
25257 --  as a unit name in the partition, in which case some other unique
25258 --  name is used.
25260 pragma Ada_95;
25261 with System;
25262 package ada_main is
25263    pragma Warnings (Off);
25265    --  The main program saves the parameters (argument count,
25266    --  argument values, environment pointer) in global variables
25267    --  for later access by other units including
25268    --  Ada.Command_Line.
25270    gnat_argc : Integer;
25271    gnat_argv : System.Address;
25272    gnat_envp : System.Address;
25274    --  The actual variables are stored in a library routine. This
25275    --  is useful for some shared library situations, where there
25276    --  are problems if variables are not in the library.
25278    pragma Import (C, gnat_argc);
25279    pragma Import (C, gnat_argv);
25280    pragma Import (C, gnat_envp);
25282    --  The exit status is similarly an external location
25284    gnat_exit_status : Integer;
25285    pragma Import (C, gnat_exit_status);
25287    GNAT_Version : constant String :=
25288                     "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
25289    pragma Export (C, GNAT_Version, "__gnat_version");
25291    Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
25292    pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
25294    --  This is the generated adainit routine that performs
25295    --  initialization at the start of execution. In the case
25296    --  where Ada is the main program, this main program makes
25297    --  a call to adainit at program startup.
25299    procedure adainit;
25300    pragma Export (C, adainit, "adainit");
25302    --  This is the generated adafinal routine that performs
25303    --  finalization at the end of execution. In the case where
25304    --  Ada is the main program, this main program makes a call
25305    --  to adafinal at program termination.
25307    procedure adafinal;
25308    pragma Export (C, adafinal, "adafinal");
25310    --  This routine is called at the start of execution. It is
25311    --  a dummy routine that is used by the debugger to breakpoint
25312    --  at the start of execution.
25314    --  This is the actual generated main program (it would be
25315    --  suppressed if the no main program switch were used). As
25316    --  required by standard system conventions, this program has
25317    --  the external name main.
25319    function main
25320      (argc : Integer;
25321       argv : System.Address;
25322       envp : System.Address)
25323       return Integer;
25324    pragma Export (C, main, "main");
25326    --  The following set of constants give the version
25327    --  identification values for every unit in the bound
25328    --  partition. This identification is computed from all
25329    --  dependent semantic units, and corresponds to the
25330    --  string that would be returned by use of the
25331    --  Body_Version or Version attributes.
25333    --  The following Export pragmas export the version numbers
25334    --  with symbolic names ending in B (for body) or S
25335    --  (for spec) so that they can be located in a link. The
25336    --  information provided here is sufficient to track down
25337    --  the exact versions of units used in a given build.
25339    type Version_32 is mod 2 ** 32;
25340    u00001 : constant Version_32 := 16#8ad6e54a#;
25341    pragma Export (C, u00001, "helloB");
25342    u00002 : constant Version_32 := 16#fbff4c67#;
25343    pragma Export (C, u00002, "system__standard_libraryB");
25344    u00003 : constant Version_32 := 16#1ec6fd90#;
25345    pragma Export (C, u00003, "system__standard_libraryS");
25346    u00004 : constant Version_32 := 16#3ffc8e18#;
25347    pragma Export (C, u00004, "adaS");
25348    u00005 : constant Version_32 := 16#28f088c2#;
25349    pragma Export (C, u00005, "ada__text_ioB");
25350    u00006 : constant Version_32 := 16#f372c8ac#;
25351    pragma Export (C, u00006, "ada__text_ioS");
25352    u00007 : constant Version_32 := 16#2c143749#;
25353    pragma Export (C, u00007, "ada__exceptionsB");
25354    u00008 : constant Version_32 := 16#f4f0cce8#;
25355    pragma Export (C, u00008, "ada__exceptionsS");
25356    u00009 : constant Version_32 := 16#a46739c0#;
25357    pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
25358    u00010 : constant Version_32 := 16#3aac8c92#;
25359    pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
25360    u00011 : constant Version_32 := 16#1d274481#;
25361    pragma Export (C, u00011, "systemS");
25362    u00012 : constant Version_32 := 16#a207fefe#;
25363    pragma Export (C, u00012, "system__soft_linksB");
25364    u00013 : constant Version_32 := 16#467d9556#;
25365    pragma Export (C, u00013, "system__soft_linksS");
25366    u00014 : constant Version_32 := 16#b01dad17#;
25367    pragma Export (C, u00014, "system__parametersB");
25368    u00015 : constant Version_32 := 16#630d49fe#;
25369    pragma Export (C, u00015, "system__parametersS");
25370    u00016 : constant Version_32 := 16#b19b6653#;
25371    pragma Export (C, u00016, "system__secondary_stackB");
25372    u00017 : constant Version_32 := 16#b6468be8#;
25373    pragma Export (C, u00017, "system__secondary_stackS");
25374    u00018 : constant Version_32 := 16#39a03df9#;
25375    pragma Export (C, u00018, "system__storage_elementsB");
25376    u00019 : constant Version_32 := 16#30e40e85#;
25377    pragma Export (C, u00019, "system__storage_elementsS");
25378    u00020 : constant Version_32 := 16#41837d1e#;
25379    pragma Export (C, u00020, "system__stack_checkingB");
25380    u00021 : constant Version_32 := 16#93982f69#;
25381    pragma Export (C, u00021, "system__stack_checkingS");
25382    u00022 : constant Version_32 := 16#393398c1#;
25383    pragma Export (C, u00022, "system__exception_tableB");
25384    u00023 : constant Version_32 := 16#b33e2294#;
25385    pragma Export (C, u00023, "system__exception_tableS");
25386    u00024 : constant Version_32 := 16#ce4af020#;
25387    pragma Export (C, u00024, "system__exceptionsB");
25388    u00025 : constant Version_32 := 16#75442977#;
25389    pragma Export (C, u00025, "system__exceptionsS");
25390    u00026 : constant Version_32 := 16#37d758f1#;
25391    pragma Export (C, u00026, "system__exceptions__machineS");
25392    u00027 : constant Version_32 := 16#b895431d#;
25393    pragma Export (C, u00027, "system__exceptions_debugB");
25394    u00028 : constant Version_32 := 16#aec55d3f#;
25395    pragma Export (C, u00028, "system__exceptions_debugS");
25396    u00029 : constant Version_32 := 16#570325c8#;
25397    pragma Export (C, u00029, "system__img_intB");
25398    u00030 : constant Version_32 := 16#1ffca443#;
25399    pragma Export (C, u00030, "system__img_intS");
25400    u00031 : constant Version_32 := 16#b98c3e16#;
25401    pragma Export (C, u00031, "system__tracebackB");
25402    u00032 : constant Version_32 := 16#831a9d5a#;
25403    pragma Export (C, u00032, "system__tracebackS");
25404    u00033 : constant Version_32 := 16#9ed49525#;
25405    pragma Export (C, u00033, "system__traceback_entriesB");
25406    u00034 : constant Version_32 := 16#1d7cb2f1#;
25407    pragma Export (C, u00034, "system__traceback_entriesS");
25408    u00035 : constant Version_32 := 16#8c33a517#;
25409    pragma Export (C, u00035, "system__wch_conB");
25410    u00036 : constant Version_32 := 16#065a6653#;
25411    pragma Export (C, u00036, "system__wch_conS");
25412    u00037 : constant Version_32 := 16#9721e840#;
25413    pragma Export (C, u00037, "system__wch_stwB");
25414    u00038 : constant Version_32 := 16#2b4b4a52#;
25415    pragma Export (C, u00038, "system__wch_stwS");
25416    u00039 : constant Version_32 := 16#92b797cb#;
25417    pragma Export (C, u00039, "system__wch_cnvB");
25418    u00040 : constant Version_32 := 16#09eddca0#;
25419    pragma Export (C, u00040, "system__wch_cnvS");
25420    u00041 : constant Version_32 := 16#6033a23f#;
25421    pragma Export (C, u00041, "interfacesS");
25422    u00042 : constant Version_32 := 16#ece6fdb6#;
25423    pragma Export (C, u00042, "system__wch_jisB");
25424    u00043 : constant Version_32 := 16#899dc581#;
25425    pragma Export (C, u00043, "system__wch_jisS");
25426    u00044 : constant Version_32 := 16#10558b11#;
25427    pragma Export (C, u00044, "ada__streamsB");
25428    u00045 : constant Version_32 := 16#2e6701ab#;
25429    pragma Export (C, u00045, "ada__streamsS");
25430    u00046 : constant Version_32 := 16#db5c917c#;
25431    pragma Export (C, u00046, "ada__io_exceptionsS");
25432    u00047 : constant Version_32 := 16#12c8cd7d#;
25433    pragma Export (C, u00047, "ada__tagsB");
25434    u00048 : constant Version_32 := 16#ce72c228#;
25435    pragma Export (C, u00048, "ada__tagsS");
25436    u00049 : constant Version_32 := 16#c3335bfd#;
25437    pragma Export (C, u00049, "system__htableB");
25438    u00050 : constant Version_32 := 16#99e5f76b#;
25439    pragma Export (C, u00050, "system__htableS");
25440    u00051 : constant Version_32 := 16#089f5cd0#;
25441    pragma Export (C, u00051, "system__string_hashB");
25442    u00052 : constant Version_32 := 16#3bbb9c15#;
25443    pragma Export (C, u00052, "system__string_hashS");
25444    u00053 : constant Version_32 := 16#807fe041#;
25445    pragma Export (C, u00053, "system__unsigned_typesS");
25446    u00054 : constant Version_32 := 16#d27be59e#;
25447    pragma Export (C, u00054, "system__val_lluB");
25448    u00055 : constant Version_32 := 16#fa8db733#;
25449    pragma Export (C, u00055, "system__val_lluS");
25450    u00056 : constant Version_32 := 16#27b600b2#;
25451    pragma Export (C, u00056, "system__val_utilB");
25452    u00057 : constant Version_32 := 16#b187f27f#;
25453    pragma Export (C, u00057, "system__val_utilS");
25454    u00058 : constant Version_32 := 16#d1060688#;
25455    pragma Export (C, u00058, "system__case_utilB");
25456    u00059 : constant Version_32 := 16#392e2d56#;
25457    pragma Export (C, u00059, "system__case_utilS");
25458    u00060 : constant Version_32 := 16#84a27f0d#;
25459    pragma Export (C, u00060, "interfaces__c_streamsB");
25460    u00061 : constant Version_32 := 16#8bb5f2c0#;
25461    pragma Export (C, u00061, "interfaces__c_streamsS");
25462    u00062 : constant Version_32 := 16#6db6928f#;
25463    pragma Export (C, u00062, "system__crtlS");
25464    u00063 : constant Version_32 := 16#4e6a342b#;
25465    pragma Export (C, u00063, "system__file_ioB");
25466    u00064 : constant Version_32 := 16#ba56a5e4#;
25467    pragma Export (C, u00064, "system__file_ioS");
25468    u00065 : constant Version_32 := 16#b7ab275c#;
25469    pragma Export (C, u00065, "ada__finalizationB");
25470    u00066 : constant Version_32 := 16#19f764ca#;
25471    pragma Export (C, u00066, "ada__finalizationS");
25472    u00067 : constant Version_32 := 16#95817ed8#;
25473    pragma Export (C, u00067, "system__finalization_rootB");
25474    u00068 : constant Version_32 := 16#52d53711#;
25475    pragma Export (C, u00068, "system__finalization_rootS");
25476    u00069 : constant Version_32 := 16#769e25e6#;
25477    pragma Export (C, u00069, "interfaces__cB");
25478    u00070 : constant Version_32 := 16#4a38bedb#;
25479    pragma Export (C, u00070, "interfaces__cS");
25480    u00071 : constant Version_32 := 16#07e6ee66#;
25481    pragma Export (C, u00071, "system__os_libB");
25482    u00072 : constant Version_32 := 16#d7b69782#;
25483    pragma Export (C, u00072, "system__os_libS");
25484    u00073 : constant Version_32 := 16#1a817b8e#;
25485    pragma Export (C, u00073, "system__stringsB");
25486    u00074 : constant Version_32 := 16#639855e7#;
25487    pragma Export (C, u00074, "system__stringsS");
25488    u00075 : constant Version_32 := 16#e0b8de29#;
25489    pragma Export (C, u00075, "system__file_control_blockS");
25490    u00076 : constant Version_32 := 16#b5b2aca1#;
25491    pragma Export (C, u00076, "system__finalization_mastersB");
25492    u00077 : constant Version_32 := 16#69316dc1#;
25493    pragma Export (C, u00077, "system__finalization_mastersS");
25494    u00078 : constant Version_32 := 16#57a37a42#;
25495    pragma Export (C, u00078, "system__address_imageB");
25496    u00079 : constant Version_32 := 16#bccbd9bb#;
25497    pragma Export (C, u00079, "system__address_imageS");
25498    u00080 : constant Version_32 := 16#7268f812#;
25499    pragma Export (C, u00080, "system__img_boolB");
25500    u00081 : constant Version_32 := 16#e8fe356a#;
25501    pragma Export (C, u00081, "system__img_boolS");
25502    u00082 : constant Version_32 := 16#d7aac20c#;
25503    pragma Export (C, u00082, "system__ioB");
25504    u00083 : constant Version_32 := 16#8365b3ce#;
25505    pragma Export (C, u00083, "system__ioS");
25506    u00084 : constant Version_32 := 16#6d4d969a#;
25507    pragma Export (C, u00084, "system__storage_poolsB");
25508    u00085 : constant Version_32 := 16#e87cc305#;
25509    pragma Export (C, u00085, "system__storage_poolsS");
25510    u00086 : constant Version_32 := 16#e34550ca#;
25511    pragma Export (C, u00086, "system__pool_globalB");
25512    u00087 : constant Version_32 := 16#c88d2d16#;
25513    pragma Export (C, u00087, "system__pool_globalS");
25514    u00088 : constant Version_32 := 16#9d39c675#;
25515    pragma Export (C, u00088, "system__memoryB");
25516    u00089 : constant Version_32 := 16#445a22b5#;
25517    pragma Export (C, u00089, "system__memoryS");
25518    u00090 : constant Version_32 := 16#6a859064#;
25519    pragma Export (C, u00090, "system__storage_pools__subpoolsB");
25520    u00091 : constant Version_32 := 16#e3b008dc#;
25521    pragma Export (C, u00091, "system__storage_pools__subpoolsS");
25522    u00092 : constant Version_32 := 16#63f11652#;
25523    pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
25524    u00093 : constant Version_32 := 16#fe2f4b3a#;
25525    pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
25527    --  BEGIN ELABORATION ORDER
25528    --  ada%s
25529    --  interfaces%s
25530    --  system%s
25531    --  system.case_util%s
25532    --  system.case_util%b
25533    --  system.htable%s
25534    --  system.img_bool%s
25535    --  system.img_bool%b
25536    --  system.img_int%s
25537    --  system.img_int%b
25538    --  system.io%s
25539    --  system.io%b
25540    --  system.parameters%s
25541    --  system.parameters%b
25542    --  system.crtl%s
25543    --  interfaces.c_streams%s
25544    --  interfaces.c_streams%b
25545    --  system.standard_library%s
25546    --  system.exceptions_debug%s
25547    --  system.exceptions_debug%b
25548    --  system.storage_elements%s
25549    --  system.storage_elements%b
25550    --  system.stack_checking%s
25551    --  system.stack_checking%b
25552    --  system.string_hash%s
25553    --  system.string_hash%b
25554    --  system.htable%b
25555    --  system.strings%s
25556    --  system.strings%b
25557    --  system.os_lib%s
25558    --  system.traceback_entries%s
25559    --  system.traceback_entries%b
25560    --  ada.exceptions%s
25561    --  system.soft_links%s
25562    --  system.unsigned_types%s
25563    --  system.val_llu%s
25564    --  system.val_util%s
25565    --  system.val_util%b
25566    --  system.val_llu%b
25567    --  system.wch_con%s
25568    --  system.wch_con%b
25569    --  system.wch_cnv%s
25570    --  system.wch_jis%s
25571    --  system.wch_jis%b
25572    --  system.wch_cnv%b
25573    --  system.wch_stw%s
25574    --  system.wch_stw%b
25575    --  ada.exceptions.last_chance_handler%s
25576    --  ada.exceptions.last_chance_handler%b
25577    --  system.address_image%s
25578    --  system.exception_table%s
25579    --  system.exception_table%b
25580    --  ada.io_exceptions%s
25581    --  ada.tags%s
25582    --  ada.streams%s
25583    --  ada.streams%b
25584    --  interfaces.c%s
25585    --  system.exceptions%s
25586    --  system.exceptions%b
25587    --  system.exceptions.machine%s
25588    --  system.finalization_root%s
25589    --  system.finalization_root%b
25590    --  ada.finalization%s
25591    --  ada.finalization%b
25592    --  system.storage_pools%s
25593    --  system.storage_pools%b
25594    --  system.finalization_masters%s
25595    --  system.storage_pools.subpools%s
25596    --  system.storage_pools.subpools.finalization%s
25597    --  system.storage_pools.subpools.finalization%b
25598    --  system.memory%s
25599    --  system.memory%b
25600    --  system.standard_library%b
25601    --  system.pool_global%s
25602    --  system.pool_global%b
25603    --  system.file_control_block%s
25604    --  system.file_io%s
25605    --  system.secondary_stack%s
25606    --  system.file_io%b
25607    --  system.storage_pools.subpools%b
25608    --  system.finalization_masters%b
25609    --  interfaces.c%b
25610    --  ada.tags%b
25611    --  system.soft_links%b
25612    --  system.os_lib%b
25613    --  system.secondary_stack%b
25614    --  system.address_image%b
25615    --  system.traceback%s
25616    --  ada.exceptions%b
25617    --  system.traceback%b
25618    --  ada.text_io%s
25619    --  ada.text_io%b
25620    --  hello%b
25621    --  END ELABORATION ORDER
25623 end ada_main;
25624 @end example
25626 @example
25627 pragma Ada_95;
25628 --  The following source file name pragmas allow the generated file
25629 --  names to be unique for different main programs. They are needed
25630 --  since the package name will always be Ada_Main.
25632 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
25633 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
25635 pragma Suppress (Overflow_Check);
25636 with Ada.Exceptions;
25638 --  Generated package body for Ada_Main starts here
25640 package body ada_main is
25641    pragma Warnings (Off);
25643    --  These values are reference counter associated to units which have
25644    --  been elaborated. It is also used to avoid elaborating the
25645    --  same unit twice.
25647    E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
25648    E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
25649    E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
25650    E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
25651    E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
25652    E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
25653    E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
25654    E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
25655    E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
25656    E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
25657    E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
25658    E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
25659    E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
25660    E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
25661    E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
25662    E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
25663    E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
25664    E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
25666    Local_Priority_Specific_Dispatching : constant String := "";
25667    Local_Interrupt_States : constant String := "";
25669    Is_Elaborated : Boolean := False;
25671    procedure finalize_library is
25672    begin
25673       E06 := E06 - 1;
25674       declare
25675          procedure F1;
25676          pragma Import (Ada, F1, "ada__text_io__finalize_spec");
25677       begin
25678          F1;
25679       end;
25680       E77 := E77 - 1;
25681       E91 := E91 - 1;
25682       declare
25683          procedure F2;
25684          pragma Import (Ada, F2, "system__file_io__finalize_body");
25685       begin
25686          E64 := E64 - 1;
25687          F2;
25688       end;
25689       declare
25690          procedure F3;
25691          pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
25692       begin
25693          E75 := E75 - 1;
25694          F3;
25695       end;
25696       E87 := E87 - 1;
25697       declare
25698          procedure F4;
25699          pragma Import (Ada, F4, "system__pool_global__finalize_spec");
25700       begin
25701          F4;
25702       end;
25703       declare
25704          procedure F5;
25705          pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
25706       begin
25707          F5;
25708       end;
25709       declare
25710          procedure F6;
25711          pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
25712       begin
25713          F6;
25714       end;
25715       declare
25716          procedure Reraise_Library_Exception_If_Any;
25717          pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
25718       begin
25719          Reraise_Library_Exception_If_Any;
25720       end;
25721    end finalize_library;
25723    -------------
25724    -- adainit --
25725    -------------
25727    procedure adainit is
25729       Main_Priority : Integer;
25730       pragma Import (C, Main_Priority, "__gl_main_priority");
25731       Time_Slice_Value : Integer;
25732       pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
25733       WC_Encoding : Character;
25734       pragma Import (C, WC_Encoding, "__gl_wc_encoding");
25735       Locking_Policy : Character;
25736       pragma Import (C, Locking_Policy, "__gl_locking_policy");
25737       Queuing_Policy : Character;
25738       pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
25739       Task_Dispatching_Policy : Character;
25740       pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
25741       Priority_Specific_Dispatching : System.Address;
25742       pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
25743       Num_Specific_Dispatching : Integer;
25744       pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
25745       Main_CPU : Integer;
25746       pragma Import (C, Main_CPU, "__gl_main_cpu");
25747       Interrupt_States : System.Address;
25748       pragma Import (C, Interrupt_States, "__gl_interrupt_states");
25749       Num_Interrupt_States : Integer;
25750       pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
25751       Unreserve_All_Interrupts : Integer;
25752       pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
25753       Detect_Blocking : Integer;
25754       pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
25755       Default_Stack_Size : Integer;
25756       pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
25757       Leap_Seconds_Support : Integer;
25758       pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
25760       procedure Runtime_Initialize;
25761       pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
25763       Finalize_Library_Objects : No_Param_Proc;
25764       pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
25766    --  Start of processing for adainit
25768    begin
25770       --  Record various information for this partition.  The values
25771       --  are derived by the binder from information stored in the ali
25772       --  files by the compiler.
25774       if Is_Elaborated then
25775          return;
25776       end if;
25777       Is_Elaborated := True;
25778       Main_Priority := -1;
25779       Time_Slice_Value := -1;
25780       WC_Encoding := 'b';
25781       Locking_Policy := ' ';
25782       Queuing_Policy := ' ';
25783       Task_Dispatching_Policy := ' ';
25784       Priority_Specific_Dispatching :=
25785         Local_Priority_Specific_Dispatching'Address;
25786       Num_Specific_Dispatching := 0;
25787       Main_CPU := -1;
25788       Interrupt_States := Local_Interrupt_States'Address;
25789       Num_Interrupt_States := 0;
25790       Unreserve_All_Interrupts := 0;
25791       Detect_Blocking := 0;
25792       Default_Stack_Size := -1;
25793       Leap_Seconds_Support := 0;
25795       Runtime_Initialize;
25797       Finalize_Library_Objects := finalize_library'access;
25799       --  Now we have the elaboration calls for all units in the partition.
25800       --  The Elab_Spec and Elab_Body attributes generate references to the
25801       --  implicit elaboration procedures generated by the compiler for
25802       --  each unit that requires elaboration. Increment a counter of
25803       --  reference for each unit.
25805       System.Soft_Links'Elab_Spec;
25806       System.Exception_Table'Elab_Body;
25807       E23 := E23 + 1;
25808       Ada.Io_Exceptions'Elab_Spec;
25809       E46 := E46 + 1;
25810       Ada.Tags'Elab_Spec;
25811       Ada.Streams'Elab_Spec;
25812       E45 := E45 + 1;
25813       Interfaces.C'Elab_Spec;
25814       System.Exceptions'Elab_Spec;
25815       E25 := E25 + 1;
25816       System.Finalization_Root'Elab_Spec;
25817       E68 := E68 + 1;
25818       Ada.Finalization'Elab_Spec;
25819       E66 := E66 + 1;
25820       System.Storage_Pools'Elab_Spec;
25821       E85 := E85 + 1;
25822       System.Finalization_Masters'Elab_Spec;
25823       System.Storage_Pools.Subpools'Elab_Spec;
25824       System.Pool_Global'Elab_Spec;
25825       E87 := E87 + 1;
25826       System.File_Control_Block'Elab_Spec;
25827       E75 := E75 + 1;
25828       System.File_Io'Elab_Body;
25829       E64 := E64 + 1;
25830       E91 := E91 + 1;
25831       System.Finalization_Masters'Elab_Body;
25832       E77 := E77 + 1;
25833       E70 := E70 + 1;
25834       Ada.Tags'Elab_Body;
25835       E48 := E48 + 1;
25836       System.Soft_Links'Elab_Body;
25837       E13 := E13 + 1;
25838       System.Os_Lib'Elab_Body;
25839       E72 := E72 + 1;
25840       System.Secondary_Stack'Elab_Body;
25841       E17 := E17 + 1;
25842       Ada.Text_Io'Elab_Spec;
25843       Ada.Text_Io'Elab_Body;
25844       E06 := E06 + 1;
25845    end adainit;
25847    --------------
25848    -- adafinal --
25849    --------------
25851    procedure adafinal is
25852       procedure s_stalib_adafinal;
25853       pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
25855       procedure Runtime_Finalize;
25856       pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
25858    begin
25859       if not Is_Elaborated then
25860          return;
25861       end if;
25862       Is_Elaborated := False;
25863       Runtime_Finalize;
25864       s_stalib_adafinal;
25865    end adafinal;
25867    --  We get to the main program of the partition by using
25868    --  pragma Import because if we try to with the unit and
25869    --  call it Ada style, then not only do we waste time
25870    --  recompiling it, but also, we don't really know the right
25871    --  switches (e.g.@@: identifier character set) to be used
25872    --  to compile it.
25874    procedure Ada_Main_Program;
25875    pragma Import (Ada, Ada_Main_Program, "_ada_hello");
25877    ----------
25878    -- main --
25879    ----------
25881    --  main is actually a function, as in the ANSI C standard,
25882    --  defined to return the exit status. The three parameters
25883    --  are the argument count, argument values and environment
25884    --  pointer.
25886    function main
25887      (argc : Integer;
25888       argv : System.Address;
25889       envp : System.Address)
25890       return Integer
25891    is
25892       --  The initialize routine performs low level system
25893       --  initialization using a standard library routine which
25894       --  sets up signal handling and performs any other
25895       --  required setup. The routine can be found in file
25896       --  a-init.c.
25898       procedure initialize;
25899       pragma Import (C, initialize, "__gnat_initialize");
25901       --  The finalize routine performs low level system
25902       --  finalization using a standard library routine. The
25903       --  routine is found in file a-final.c and in the standard
25904       --  distribution is a dummy routine that does nothing, so
25905       --  really this is a hook for special user finalization.
25907       procedure finalize;
25908       pragma Import (C, finalize, "__gnat_finalize");
25910       --  The following is to initialize the SEH exceptions
25912       SEH : aliased array (1 .. 2) of Integer;
25914       Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
25915       pragma Volatile (Ensure_Reference);
25917    --  Start of processing for main
25919    begin
25920       --  Save global variables
25922       gnat_argc := argc;
25923       gnat_argv := argv;
25924       gnat_envp := envp;
25926       --  Call low level system initialization
25928       Initialize (SEH'Address);
25930       --  Call our generated Ada initialization routine
25932       adainit;
25934       --  Now we call the main program of the partition
25936       Ada_Main_Program;
25938       --  Perform Ada finalization
25940       adafinal;
25942       --  Perform low level system finalization
25944       Finalize;
25946       --  Return the proper exit status
25947       return (gnat_exit_status);
25948    end;
25950 --  This section is entirely comments, so it has no effect on the
25951 --  compilation of the Ada_Main package. It provides the list of
25952 --  object files and linker options, as well as some standard
25953 --  libraries needed for the link. The gnatlink utility parses
25954 --  this b~hello.adb file to read these comment lines to generate
25955 --  the appropriate command line arguments for the call to the
25956 --  system linker. The BEGIN/END lines are used for sentinels for
25957 --  this parsing operation.
25959 --  The exact file names will of course depend on the environment,
25960 --  host/target and location of files on the host system.
25962 -- BEGIN Object file/option list
25963    --   ./hello.o
25964    --   -L./
25965    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
25966    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
25967 -- END Object file/option list
25969 end ada_main;
25970 @end example
25972 The Ada code in the above example is exactly what is generated by the
25973 binder. We have added comments to more clearly indicate the function
25974 of each part of the generated @code{Ada_Main} package.
25976 The code is standard Ada in all respects, and can be processed by any
25977 tools that handle Ada. In particular, it is possible to use the debugger
25978 in Ada mode to debug the generated @code{Ada_Main} package. For example,
25979 suppose that for reasons that you do not understand, your program is crashing
25980 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
25981 you can place a breakpoint on the call:
25983 @quotation
25985 @example
25986 Ada.Text_Io'Elab_Body;
25987 @end example
25988 @end quotation
25990 and trace the elaboration routine for this package to find out where
25991 the problem might be (more usually of course you would be debugging
25992 elaboration code in your own application).
25994 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
25996 @node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
25997 @anchor{gnat_ugn/elaboration_order_handling_in_gnat doc}@anchor{216}@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order-handling-in-gnat}@anchor{f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id1}@anchor{217}
25998 @chapter Elaboration Order Handling in GNAT
26001 @geindex Order of elaboration
26003 @geindex Elaboration control
26005 This appendix describes the handling of elaboration code in Ada and GNAT, and
26006 discusses how the order of elaboration of program units can be controlled in
26007 GNAT, either automatically or with explicit programming features.
26009 @menu
26010 * Elaboration Code:: 
26011 * Elaboration Order:: 
26012 * Checking the Elaboration Order:: 
26013 * Controlling the Elaboration Order in Ada:: 
26014 * Controlling the Elaboration Order in GNAT:: 
26015 * Mixing Elaboration Models:: 
26016 * ABE Diagnostics:: 
26017 * SPARK Diagnostics:: 
26018 * Elaboration Circularities:: 
26019 * Resolving Elaboration Circularities:: 
26020 * Elaboration-related Compiler Switches:: 
26021 * Summary of Procedures for Elaboration Control:: 
26022 * Inspecting the Chosen Elaboration Order:: 
26024 @end menu
26026 @node Elaboration Code,Elaboration Order,,Elaboration Order Handling in GNAT
26027 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{218}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{219}
26028 @section Elaboration Code
26031 Ada defines the term @emph{execution} as the process by which a construct achieves
26032 its run-time effect. This process is also referred to as @strong{elaboration} for
26033 declarations and @emph{evaluation} for expressions.
26035 The execution model in Ada allows for certain sections of an Ada program to be
26036 executed prior to execution of the program itself, primarily with the intent of
26037 initializing data. These sections are referred to as @strong{elaboration code}.
26038 Elaboration code is executed as follows:
26041 @itemize *
26043 @item 
26044 All partitions of an Ada program are executed in parallel with one another,
26045 possibly in a separate address space, and possibly on a separate computer.
26047 @item 
26048 The execution of a partition involves running the environment task for that
26049 partition.
26051 @item 
26052 The environment task executes all elaboration code (if available) for all
26053 units within that partition. This code is said to be executed at
26054 @strong{elaboration time}.
26056 @item 
26057 The environment task executes the Ada program (if available) for that
26058 partition.
26059 @end itemize
26061 In addition to the Ada terminology, this appendix defines the following terms:
26064 @itemize *
26066 @item 
26067 @emph{Invocation}
26069 The act of calling a subprogram, instantiating a generic, or activating a
26070 task.
26072 @item 
26073 @emph{Scenario}
26075 A construct that is elaborated or invoked by elaboration code is referred to
26076 as an @emph{elaboration scenario} or simply a @strong{scenario}. GNAT recognizes the
26077 following scenarios:
26080 @itemize -
26082 @item 
26083 @code{'Access} of entries, operators, and subprograms
26085 @item 
26086 Activation of tasks
26088 @item 
26089 Calls to entries, operators, and subprograms
26091 @item 
26092 Instantiations of generic templates
26093 @end itemize
26095 @item 
26096 @emph{Target}
26098 A construct elaborated by a scenario is referred to as @emph{elaboration target}
26099 or simply @strong{target}. GNAT recognizes the following targets:
26102 @itemize -
26104 @item 
26105 For @code{'Access} of entries, operators, and subprograms, the target is the
26106 entry, operator, or subprogram being aliased.
26108 @item 
26109 For activation of tasks, the target is the task body
26111 @item 
26112 For calls to entries, operators, and subprograms, the target is the entry,
26113 operator, or subprogram being invoked.
26115 @item 
26116 For instantiations of generic templates, the target is the generic template
26117 being instantiated.
26118 @end itemize
26119 @end itemize
26121 Elaboration code may appear in two distinct contexts:
26124 @itemize *
26126 @item 
26127 @emph{Library level}
26129 A scenario appears at the library level when it is encapsulated by a package
26130 [body] compilation unit, ignoring any other package [body] declarations in
26131 between.
26133 @example
26134 with Server;
26135 package Client is
26136    procedure Proc;
26138    package Nested is
26139       Val : ... := Server.Func;
26140    end Nested;
26141 end Client;
26142 @end example
26144 In the example above, the call to @code{Server.Func} is an elaboration scenario
26145 because it appears at the library level of package @code{Client}. Note that the
26146 declaration of package @code{Nested} is ignored according to the definition
26147 given above. As a result, the call to @code{Server.Func} will be invoked when
26148 the spec of unit @code{Client} is elaborated.
26150 @item 
26151 @emph{Package body statements}
26153 A scenario appears within the statement sequence of a package body when it is
26154 bounded by the region starting from the @code{begin} keyword of the package body
26155 and ending at the @code{end} keyword of the package body.
26157 @example
26158 package body Client is
26159    procedure Proc is
26160    begin
26161       ...
26162    end Proc;
26163 begin
26164    Proc;
26165 end Client;
26166 @end example
26168 In the example above, the call to @code{Proc} is an elaboration scenario because
26169 it appears within the statement sequence of package body @code{Client}. As a
26170 result, the call to @code{Proc} will be invoked when the body of @code{Client} is
26171 elaborated.
26172 @end itemize
26174 @node Elaboration Order,Checking the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
26175 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order}@anchor{21a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{21b}
26176 @section Elaboration Order
26179 The sequence by which the elaboration code of all units within a partition is
26180 executed is referred to as @strong{elaboration order}.
26182 Within a single unit, elaboration code is executed in sequential order.
26184 @quotation
26186 @example
26187 package body Client is
26188    Result : ... := Server.Func;
26190    procedure Proc is
26191       package Inst is new Server.Gen;
26192    begin
26193       Inst.Eval (Result);
26194    end Proc;
26195 begin
26196    Proc;
26197 end Client;
26198 @end example
26199 @end quotation
26201 In the example above, the elaboration order within package body @code{Client} is
26202 as follows:
26205 @enumerate 
26207 @item 
26208 The object declaration of @code{Result} is elaborated.
26211 @itemize *
26213 @item 
26214 Function @code{Server.Func} is invoked.
26215 @end itemize
26217 @item 
26218 The subprogram body of @code{Proc} is elaborated.
26220 @item 
26221 Procedure @code{Proc} is invoked.
26224 @itemize *
26226 @item 
26227 Generic unit @code{Server.Gen} is instantiated as @code{Inst}.
26229 @item 
26230 Instance @code{Inst} is elaborated.
26232 @item 
26233 Procedure @code{Inst.Eval} is invoked.
26234 @end itemize
26235 @end enumerate
26237 The elaboration order of all units within a partition depends on the following
26238 factors:
26241 @itemize *
26243 @item 
26244 @emph{with}ed units
26246 @item 
26247 parent units
26249 @item 
26250 purity of units
26252 @item 
26253 preelaborability of units
26255 @item 
26256 presence of elaboration-control pragmas
26258 @item 
26259 invocations performed in elaboration code
26260 @end itemize
26262 A program may have several elaboration orders depending on its structure.
26264 @quotation
26266 @example
26267 package Server is
26268    function Func (Index : Integer) return Integer;
26269 end Server;
26270 @end example
26272 @example
26273 package body Server is
26274    Results : array (1 .. 5) of Integer := (1, 2, 3, 4, 5);
26276    function Func (Index : Integer) return Integer is
26277    begin
26278       return Results (Index);
26279    end Func;
26280 end Server;
26281 @end example
26283 @example
26284 with Server;
26285 package Client is
26286    Val : constant Integer := Server.Func (3);
26287 end Client;
26288 @end example
26290 @example
26291 with Client;
26292 procedure Main is begin null; end Main;
26293 @end example
26294 @end quotation
26296 The following elaboration order exhibits a fundamental problem referred to as
26297 @emph{access-before-elaboration} or simply @strong{ABE}.
26299 @quotation
26301 @example
26302 spec of Server
26303 spec of Client
26304 body of Server
26305 body of Main
26306 @end example
26307 @end quotation
26309 The elaboration of @code{Server}’s spec materializes function @code{Func}, making it
26310 callable. The elaboration of @code{Client}’s spec elaborates the declaration of
26311 @code{Val}. This invokes function @code{Server.Func}, however the body of
26312 @code{Server.Func} has not been elaborated yet because @code{Server}’s body comes
26313 after @code{Client}’s spec in the elaboration order. As a result, the value of
26314 constant @code{Val} is now undefined.
26316 Without any guarantees from the language, an undetected ABE problem may hinder
26317 proper initialization of data, which in turn may lead to undefined behavior at
26318 run time. To prevent such ABE problems, Ada employs dynamic checks in the same
26319 vein as index or null exclusion checks. A failed ABE check raises exception
26320 @code{Program_Error}.
26322 The following elaboration order avoids the ABE problem and the program can be
26323 successfully elaborated.
26325 @quotation
26327 @example
26328 spec of Server
26329 body of Server
26330 spec of Client
26331 body of Main
26332 @end example
26333 @end quotation
26335 Ada states that a total elaboration order must exist, but it does not define
26336 what this order is. A compiler is thus tasked with choosing a suitable
26337 elaboration order which satisfies the dependencies imposed by @emph{with} clauses,
26338 unit categorization, elaboration-control pragmas, and invocations performed in
26339 elaboration code. Ideally an order that avoids ABE problems should be chosen,
26340 however a compiler may not always find such an order due to complications with
26341 respect to control and data flow.
26343 @node Checking the Elaboration Order,Controlling the Elaboration Order in Ada,Elaboration Order,Elaboration Order Handling in GNAT
26344 @anchor{gnat_ugn/elaboration_order_handling_in_gnat checking-the-elaboration-order}@anchor{21c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id4}@anchor{21d}
26345 @section Checking the Elaboration Order
26348 To avoid placing the entire elaboration-order burden on the programmer, Ada
26349 provides three lines of defense:
26352 @itemize *
26354 @item 
26355 @emph{Static semantics}
26357 Static semantic rules restrict the possible choice of elaboration order. For
26358 instance, if unit Client @emph{with}s unit Server, then the spec of Server is
26359 always elaborated prior to Client. The same principle applies to child units
26360 - the spec of a parent unit is always elaborated prior to the child unit.
26362 @item 
26363 @emph{Dynamic semantics}
26365 Dynamic checks are performed at run time, to ensure that a target is
26366 elaborated prior to a scenario that invokes it, thus avoiding ABE problems.
26367 A failed run-time check raises exception @code{Program_Error}. The following
26368 restrictions apply:
26371 @itemize -
26373 @item 
26374 @emph{Restrictions on calls}
26376 An entry, operator, or subprogram can be called from elaboration code only
26377 when the corresponding body has been elaborated.
26379 @item 
26380 @emph{Restrictions on instantiations}
26382 A generic unit can be instantiated by elaboration code only when the
26383 corresponding body has been elaborated.
26385 @item 
26386 @emph{Restrictions on task activation}
26388 A task can be activated by elaboration code only when the body of the
26389 associated task type has been elaborated.
26390 @end itemize
26392 The restrictions above can be summarized by the following rule:
26394 @emph{If a target has a body, then this body must be elaborated prior to the
26395 scenario that invokes the target.}
26397 @item 
26398 @emph{Elaboration control}
26400 Pragmas are provided for the programmer to specify the desired elaboration
26401 order.
26402 @end itemize
26404 @node Controlling the Elaboration Order in Ada,Controlling the Elaboration Order in GNAT,Checking the Elaboration Order,Elaboration Order Handling in GNAT
26405 @anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order-in-ada}@anchor{21e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id5}@anchor{21f}
26406 @section Controlling the Elaboration Order in Ada
26409 Ada provides several idioms and pragmas to aid the programmer with specifying
26410 the desired elaboration order and avoiding ABE problems altogether.
26413 @itemize *
26415 @item 
26416 @emph{Packages without a body}
26418 A library package which does not require a completing body does not suffer
26419 from ABE problems.
26421 @example
26422 package Pack is
26423    generic
26424       type Element is private;
26425    package Containers is
26426       type Element_Array is array (1 .. 10) of Element;
26427    end Containers;
26428 end Pack;
26429 @end example
26431 In the example above, package @code{Pack} does not require a body because it
26432 does not contain any constructs which require completion in a body. As a
26433 result, generic @code{Pack.Containers} can be instantiated without encountering
26434 any ABE problems.
26435 @end itemize
26437 @geindex pragma Pure
26440 @itemize *
26442 @item 
26443 @emph{pragma Pure}
26445 Pragma @code{Pure} places sufficient restrictions on a unit to guarantee that no
26446 scenario within the unit can result in an ABE problem.
26447 @end itemize
26449 @geindex pragma Preelaborate
26452 @itemize *
26454 @item 
26455 @emph{pragma Preelaborate}
26457 Pragma @code{Preelaborate} is slightly less restrictive than pragma @code{Pure},
26458 but still strong enough to prevent ABE problems within a unit.
26459 @end itemize
26461 @geindex pragma Elaborate_Body
26464 @itemize *
26466 @item 
26467 @emph{pragma Elaborate_Body}
26469 Pragma @code{Elaborate_Body} requires that the body of a unit is elaborated
26470 immediately after its spec. This restriction guarantees that no client
26471 scenario can invoke a server target before the target body has been
26472 elaborated because the spec and body are effectively “glued” together.
26474 @example
26475 package Server is
26476    pragma Elaborate_Body;
26478    function Func return Integer;
26479 end Server;
26480 @end example
26482 @example
26483 package body Server is
26484    function Func return Integer is
26485    begin
26486       ...
26487    end Func;
26488 end Server;
26489 @end example
26491 @example
26492 with Server;
26493 package Client is
26494    Val : constant Integer := Server.Func;
26495 end Client;
26496 @end example
26498 In the example above, pragma @code{Elaborate_Body} guarantees the following
26499 elaboration order:
26501 @example
26502 spec of Server
26503 body of Server
26504 spec of Client
26505 @end example
26507 because the spec of @code{Server} must be elaborated prior to @code{Client} by
26508 virtue of the @emph{with} clause, and in addition the body of @code{Server} must be
26509 elaborated immediately after the spec of @code{Server}.
26511 Removing pragma @code{Elaborate_Body} could result in the following incorrect
26512 elaboration order:
26514 @example
26515 spec of Server
26516 spec of Client
26517 body of Server
26518 @end example
26520 where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func} has
26521 not been elaborated yet.
26522 @end itemize
26524 The pragmas outlined above allow a server unit to guarantee safe elaboration
26525 use by client units. Thus it is a good rule to mark units as @code{Pure} or
26526 @code{Preelaborate}, and if this is not possible, mark them as @code{Elaborate_Body}.
26528 There are however situations where @code{Pure}, @code{Preelaborate}, and
26529 @code{Elaborate_Body} are not applicable. Ada provides another set of pragmas for
26530 use by client units to help ensure the elaboration safety of server units they
26531 depend on.
26533 @geindex pragma Elaborate (Unit)
26536 @itemize *
26538 @item 
26539 @emph{pragma Elaborate (Unit)}
26541 Pragma @code{Elaborate} can be placed in the context clauses of a unit, after a
26542 @emph{with} clause. It guarantees that both the spec and body of its argument will
26543 be elaborated prior to the unit with the pragma. Note that other unrelated
26544 units may be elaborated in between the spec and the body.
26546 @example
26547 package Server is
26548    function Func return Integer;
26549 end Server;
26550 @end example
26552 @example
26553 package body Server is
26554    function Func return Integer is
26555    begin
26556       ...
26557    end Func;
26558 end Server;
26559 @end example
26561 @example
26562 with Server;
26563 pragma Elaborate (Server);
26564 package Client is
26565    Val : constant Integer := Server.Func;
26566 end Client;
26567 @end example
26569 In the example above, pragma @code{Elaborate} guarantees the following
26570 elaboration order:
26572 @example
26573 spec of Server
26574 body of Server
26575 spec of Client
26576 @end example
26578 Removing pragma @code{Elaborate} could result in the following incorrect
26579 elaboration order:
26581 @example
26582 spec of Server
26583 spec of Client
26584 body of Server
26585 @end example
26587 where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func}
26588 has not been elaborated yet.
26589 @end itemize
26591 @geindex pragma Elaborate_All (Unit)
26594 @itemize *
26596 @item 
26597 @emph{pragma Elaborate_All (Unit)}
26599 Pragma @code{Elaborate_All} is placed in the context clauses of a unit, after
26600 a @emph{with} clause. It guarantees that both the spec and body of its argument
26601 will be elaborated prior to the unit with the pragma, as well as all units
26602 @emph{with}ed by the spec and body of the argument, recursively. Note that other
26603 unrelated units may be elaborated in between the spec and the body.
26605 @example
26606 package Math is
26607    function Factorial (Val : Natural) return Natural;
26608 end Math;
26609 @end example
26611 @example
26612 package body Math is
26613    function Factorial (Val : Natural) return Natural is
26614    begin
26615       ...;
26616    end Factorial;
26617 end Math;
26618 @end example
26620 @example
26621 package Computer is
26622    type Operation_Kind is (None, Op_Factorial);
26624    function Compute
26625      (Val : Natural;
26626       Op  : Operation_Kind) return Natural;
26627 end Computer;
26628 @end example
26630 @example
26631 with Math;
26632 package body Computer is
26633    function Compute
26634      (Val : Natural;
26635       Op  : Operation_Kind) return Natural
26636    is
26637       if Op = Op_Factorial then
26638          return Math.Factorial (Val);
26639       end if;
26641       return 0;
26642    end Compute;
26643 end Computer;
26644 @end example
26646 @example
26647 with Computer;
26648 pragma Elaborate_All (Computer);
26649 package Client is
26650    Val : constant Natural :=
26651            Computer.Compute (123, Computer.Op_Factorial);
26652 end Client;
26653 @end example
26655 In the example above, pragma @code{Elaborate_All} can result in the following
26656 elaboration order:
26658 @example
26659 spec of Math
26660 body of Math
26661 spec of Computer
26662 body of Computer
26663 spec of Client
26664 @end example
26666 Note that there are several allowable suborders for the specs and bodies of
26667 @code{Math} and @code{Computer}, but the point is that these specs and bodies will
26668 be elaborated prior to @code{Client}.
26670 Removing pragma @code{Elaborate_All} could result in the following incorrect
26671 elaboration order:
26673 @example
26674 spec of Math
26675 spec of Computer
26676 body of Computer
26677 spec of Client
26678 body of Math
26679 @end example
26681 where @code{Client} invokes @code{Computer.Compute}, which in turn invokes
26682 @code{Math.Factorial}, but the body of @code{Math.Factorial} has not been
26683 elaborated yet.
26684 @end itemize
26686 All pragmas shown above can be summarized by the following rule:
26688 @emph{If a client unit elaborates a server target directly or indirectly, then if
26689 the server unit requires a body and does not have pragma Pure, Preelaborate,
26690 or Elaborate_Body, then the client unit should have pragma Elaborate or
26691 Elaborate_All for the server unit.}
26693 If the rule outlined above is not followed, then a program may fall in one of
26694 the following states:
26697 @itemize *
26699 @item 
26700 @emph{No elaboration order exists}
26702 In this case a compiler must diagnose the situation, and refuse to build an
26703 executable program.
26705 @item 
26706 @emph{One or more incorrect elaboration orders exist}
26708 In this case a compiler can build an executable program, but
26709 @code{Program_Error} will be raised when the program is run.
26711 @item 
26712 @emph{Several elaboration orders exist, some correct, some incorrect}
26714 In this case the programmer has not controlled the elaboration order. As a
26715 result, a compiler may or may not pick one of the correct orders, and the
26716 program may or may not raise @code{Program_Error} when it is run. This is the
26717 worst possible state because the program may fail on another compiler, or
26718 even another version of the same compiler.
26720 @item 
26721 @emph{One or more correct orders exist}
26723 In this case a compiler can build an executable program, and the program is
26724 run successfully. This state may be guaranteed by following the outlined
26725 rules, or may be the result of good program architecture.
26726 @end itemize
26728 Note that one additional advantage of using @code{Elaborate} and @code{Elaborate_All}
26729 is that the program continues to stay in the last state (one or more correct
26730 orders exist) even if maintenance changes the bodies of targets.
26732 @node Controlling the Elaboration Order in GNAT,Mixing Elaboration Models,Controlling the Elaboration Order in Ada,Elaboration Order Handling in GNAT
26733 @anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order-in-gnat}@anchor{220}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id6}@anchor{221}
26734 @section Controlling the Elaboration Order in GNAT
26737 In addition to Ada semantics and rules synthesized from them, GNAT offers
26738 three elaboration models to aid the programmer with specifying the correct
26739 elaboration order and to diagnose elaboration problems.
26741 @geindex Dynamic elaboration model
26744 @itemize *
26746 @item 
26747 @emph{Dynamic elaboration model}
26749 This is the most permissive of the three elaboration models and emulates the
26750 behavior specified by the Ada Reference Manual. When the dynamic model is in
26751 effect, GNAT makes the following assumptions:
26754 @itemize -
26756 @item 
26757 All code within all units in a partition is considered to be elaboration
26758 code.
26760 @item 
26761 Some of the invocations in elaboration code may not take place at run time
26762 due to conditional execution.
26763 @end itemize
26765 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
26766 that invoke internal targets. In addition, GNAT generates run-time checks for
26767 all external targets and for all scenarios that may exhibit ABE problems.
26769 The elaboration order is obtained by honoring all @emph{with} clauses, purity and
26770 preelaborability of units, and elaboration-control pragmas. The dynamic model
26771 attempts to take all invocations in elaboration code into account. If an
26772 invocation leads to a circularity, GNAT ignores the invocation based on the
26773 assumptions stated above. An order obtained using the dynamic model may fail
26774 an ABE check at run time when GNAT ignored an invocation.
26776 The dynamic model is enabled with compiler switch @code{-gnatE}.
26777 @end itemize
26779 @geindex Static elaboration model
26782 @itemize *
26784 @item 
26785 @emph{Static elaboration model}
26787 This is the middle ground of the three models. When the static model is in
26788 effect, GNAT makes the following assumptions:
26791 @itemize -
26793 @item 
26794 Only code at the library level and in package body statements within all
26795 units in a partition is considered to be elaboration code.
26797 @item 
26798 All invocations in elaboration will take place at run time, regardless of
26799 conditional execution.
26800 @end itemize
26802 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
26803 that invoke internal targets. In addition, GNAT generates run-time checks for
26804 all external targets and for all scenarios that may exhibit ABE problems.
26806 The elaboration order is obtained by honoring all @emph{with} clauses, purity and
26807 preelaborability of units, presence of elaboration-control pragmas, and all
26808 invocations in elaboration code. An order obtained using the static model is
26809 guaranteed to be ABE problem-free, excluding dispatching calls and
26810 access-to-subprogram types.
26812 The static model is the default model in GNAT.
26813 @end itemize
26815 @geindex SPARK elaboration model
26818 @itemize *
26820 @item 
26821 @emph{SPARK elaboration model}
26823 This is the most conservative of the three models and enforces the SPARK
26824 rules of elaboration as defined in the SPARK Reference Manual, section 7.7.
26825 The SPARK model is in effect only when a scenario and a target reside in a
26826 region subject to @code{SPARK_Mode On}, otherwise the dynamic or static model
26827 is in effect.
26829 The SPARK model is enabled with compiler switch @code{-gnatd.v}.
26830 @end itemize
26832 @geindex Legacy elaboration models
26835 @itemize *
26837 @item 
26838 @emph{Legacy elaboration models}
26840 In addition to the three elaboration models outlined above, GNAT provides the
26841 following legacy models:
26844 @itemize -
26846 @item 
26847 @cite{Legacy elaboration-checking model} available in pre-18.x versions of GNAT.
26848 This model is enabled with compiler switch @code{-gnatH}.
26850 @item 
26851 @cite{Legacy elaboration-order model} available in pre-20.x versions of GNAT.
26852 This model is enabled with binder switch @code{-H}.
26853 @end itemize
26854 @end itemize
26856 @geindex Relaxed elaboration mode
26858 The dynamic, legacy, and static models can be relaxed using compiler switch
26859 @code{-gnatJ}, making them more permissive. Note that in this mode, GNAT
26860 may not diagnose certain elaboration issues or install run-time checks.
26862 @node Mixing Elaboration Models,ABE Diagnostics,Controlling the Elaboration Order in GNAT,Elaboration Order Handling in GNAT
26863 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{222}@anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{223}
26864 @section Mixing Elaboration Models
26867 It is possible to mix units compiled with a different elaboration model,
26868 however the following rules must be observed:
26871 @itemize *
26873 @item 
26874 A client unit compiled with the dynamic model can only @emph{with} a server unit
26875 that meets at least one of the following criteria:
26878 @itemize -
26880 @item 
26881 The server unit is compiled with the dynamic model.
26883 @item 
26884 The server unit is a GNAT implementation unit from the @code{Ada}, @code{GNAT},
26885 @code{Interfaces}, or @code{System} hierarchies.
26887 @item 
26888 The server unit has pragma @code{Pure} or @code{Preelaborate}.
26890 @item 
26891 The client unit has an explicit @code{Elaborate_All} pragma for the server
26892 unit.
26893 @end itemize
26894 @end itemize
26896 These rules ensure that elaboration checks are not omitted. If the rules are
26897 violated, the binder emits a warning:
26899 @quotation
26901 @example
26902 warning: "x.ads" has dynamic elaboration checks and with's
26903 warning:   "y.ads" which has static elaboration checks
26904 @end example
26905 @end quotation
26907 The warnings can be suppressed by binder switch @code{-ws}.
26909 @node ABE Diagnostics,SPARK Diagnostics,Mixing Elaboration Models,Elaboration Order Handling in GNAT
26910 @anchor{gnat_ugn/elaboration_order_handling_in_gnat abe-diagnostics}@anchor{224}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{225}
26911 @section ABE Diagnostics
26914 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
26915 that invoke internal targets, regardless of whether the dynamic, SPARK, or
26916 static model is in effect.
26918 Note that GNAT emits warnings rather than hard errors whenever it encounters an
26919 elaboration problem. This is because the elaboration model in effect may be too
26920 conservative, or a particular scenario may not be invoked due conditional
26921 execution. The warnings can be suppressed selectively with @code{pragma Warnings
26922 (Off)} or globally with compiler switch @code{-gnatwL}.
26924 A @emph{guaranteed ABE} arises when the body of a target is not elaborated early
26925 enough, and causes @emph{all} scenarios that directly invoke the target to fail.
26927 @quotation
26929 @example
26930 package body Guaranteed_ABE is
26931    function ABE return Integer;
26933    Val : constant Integer := ABE;
26935    function ABE return Integer is
26936    begin
26937      ...
26938    end ABE;
26939 end Guaranteed_ABE;
26940 @end example
26941 @end quotation
26943 In the example above, the elaboration of @code{Guaranteed_ABE}’s body elaborates
26944 the declaration of @code{Val}. This invokes function @code{ABE}, however the body of
26945 @code{ABE} has not been elaborated yet. GNAT emits the following diagnostic:
26947 @quotation
26949 @example
26950 4.    Val : constant Integer := ABE;
26951                                 |
26952    >>> warning: cannot call "ABE" before body seen
26953    >>> warning: Program_Error will be raised at run time
26954 @end example
26955 @end quotation
26957 A @emph{conditional ABE} arises when the body of a target is not elaborated early
26958 enough, and causes @emph{some} scenarios that directly invoke the target to fail.
26960 @quotation
26962 @example
26963  1. package body Conditional_ABE is
26964  2.    procedure Force_Body is null;
26965  3.
26966  4.    generic
26967  5.       with function Func return Integer;
26968  6.    package Gen is
26969  7.       Val : constant Integer := Func;
26970  8.    end Gen;
26971  9.
26972 10.    function ABE return Integer;
26974 12.    function Cause_ABE return Boolean is
26975 13.       package Inst is new Gen (ABE);
26976 14.    begin
26977 15.       ...
26978 16.    end Cause_ABE;
26980 18.    Val : constant Boolean := Cause_ABE;
26982 20.    function ABE return Integer is
26983 21.    begin
26984 22.       ...
26985 23.    end ABE;
26987 25.    Safe : constant Boolean := Cause_ABE;
26988 26. end Conditional_ABE;
26989 @end example
26990 @end quotation
26992 In the example above, the elaboration of package body @code{Conditional_ABE}
26993 elaborates the declaration of @code{Val}. This invokes function @code{Cause_ABE},
26994 which instantiates generic unit @code{Gen} as @code{Inst}. The elaboration of
26995 @code{Inst} invokes function @code{ABE}, however the body of @code{ABE} has not been
26996 elaborated yet. GNAT emits the following diagnostic:
26998 @quotation
27000 @example
27001 13.       package Inst is new Gen (ABE);
27002           |
27003     >>> warning: in instantiation at line 7
27004     >>> warning: cannot call "ABE" before body seen
27005     >>> warning: Program_Error may be raised at run time
27006     >>> warning:   body of unit "Conditional_ABE" elaborated
27007     >>> warning:   function "Cause_ABE" called at line 18
27008     >>> warning:   function "ABE" called at line 7, instance at line 13
27009 @end example
27010 @end quotation
27012 Note that the same ABE problem does not occur with the elaboration of
27013 declaration @code{Safe} because the body of function @code{ABE} has already been
27014 elaborated at that point.
27016 @node SPARK Diagnostics,Elaboration Circularities,ABE Diagnostics,Elaboration Order Handling in GNAT
27017 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{226}@anchor{gnat_ugn/elaboration_order_handling_in_gnat spark-diagnostics}@anchor{227}
27018 @section SPARK Diagnostics
27021 GNAT enforces the SPARK rules of elaboration as defined in the SPARK Reference
27022 Manual section 7.7 when compiler switch @code{-gnatd.v} is in effect. Note
27023 that GNAT emits hard errors whenever it encounters a violation of the SPARK
27024 rules.
27026 @quotation
27028 @example
27029 1. with Server;
27030 2. package body SPARK_Diagnostics with SPARK_Mode is
27031 3.    Val : constant Integer := Server.Func;
27032                                       |
27033    >>> call to "Func" during elaboration in SPARK
27034    >>> unit "SPARK_Diagnostics" requires pragma "Elaborate_All" for "Server"
27035    >>>   body of unit "SPARK_Model" elaborated
27036    >>>   function "Func" called at line 3
27038 4. end SPARK_Diagnostics;
27039 @end example
27040 @end quotation
27042 @node Elaboration Circularities,Resolving Elaboration Circularities,SPARK Diagnostics,Elaboration Order Handling in GNAT
27043 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-circularities}@anchor{228}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{229}
27044 @section Elaboration Circularities
27047 An @strong{elaboration circularity} occurs whenever the elaboration of a set of
27048 units enters a deadlocked state, where each unit is waiting for another unit
27049 to be elaborated. This situation may be the result of improper use of @emph{with}
27050 clauses, elaboration-control pragmas, or invocations in elaboration code.
27052 The following example exhibits an elaboration circularity.
27054 @quotation
27056 @example
27057 with B; pragma Elaborate (B);
27058 package A is
27059 end A;
27060 @end example
27062 @example
27063 package B is
27064    procedure Force_Body;
27065 end B;
27066 @end example
27068 @example
27069 with C;
27070 package body B is
27071    procedure Force_Body is null;
27073    Elab : constant Integer := C.Func;
27074 end B;
27075 @end example
27077 @example
27078 package C is
27079    function Func return Integer;
27080 end C;
27081 @end example
27083 @example
27084 with A;
27085 package body C is
27086    function Func return Integer is
27087    begin
27088       ...
27089    end Func;
27090 end C;
27091 @end example
27092 @end quotation
27094 The binder emits the following diagnostic:
27096 @quotation
27098 @example
27099 error: Elaboration circularity detected
27100 info:
27101 info:    Reason:
27102 info:
27103 info:      unit "a (spec)" depends on its own elaboration
27104 info:
27105 info:    Circularity:
27106 info:
27107 info:      unit "a (spec)" has with clause and pragma Elaborate for unit "b (spec)"
27108 info:      unit "b (body)" is in the closure of pragma Elaborate
27109 info:      unit "b (body)" invokes a construct of unit "c (body)" at elaboration time
27110 info:      unit "c (body)" has with clause for unit "a (spec)"
27111 info:
27112 info:    Suggestions:
27113 info:
27114 info:      remove pragma Elaborate for unit "b (body)" in unit "a (spec)"
27115 info:      use the dynamic elaboration model (compiler switch -gnatE)
27116 @end example
27117 @end quotation
27119 The diagnostic consist of the following sections:
27122 @itemize *
27124 @item 
27125 Reason
27127 This section provides a short explanation describing why the set of units
27128 could not be ordered.
27130 @item 
27131 Circularity
27133 This section enumerates the units comprising the deadlocked set, along with
27134 their interdependencies.
27136 @item 
27137 Suggestions
27139 This section enumerates various tactics for eliminating the circularity.
27140 @end itemize
27142 @node Resolving Elaboration Circularities,Elaboration-related Compiler Switches,Elaboration Circularities,Elaboration Order Handling in GNAT
27143 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{22a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat resolving-elaboration-circularities}@anchor{22b}
27144 @section Resolving Elaboration Circularities
27147 The most desirable option from the point of view of long-term maintenance is to
27148 rearrange the program so that the elaboration problems are avoided. One useful
27149 technique is to place the elaboration code into separate child packages.
27150 Another is to move some of the initialization code to explicitly invoked
27151 subprograms, where the program controls the order of initialization explicitly.
27152 Although this is the most desirable option, it may be impractical and involve
27153 too much modification, especially in the case of complex legacy code.
27155 When faced with an elaboration circularity, the programmer should also consider
27156 the tactics given in the suggestions section of the circularity diagnostic.
27157 Depending on the units involved in the circularity, their @emph{with} clauses,
27158 purity, preelaborability, presence of elaboration-control pragmas and
27159 invocations at elaboration time, the binder may suggest one or more of the
27160 following tactics to eliminate the circularity:
27163 @itemize *
27165 @item 
27166 Pragma Elaborate elimination
27168 @example
27169 remove pragma Elaborate for unit "..." in unit "..."
27170 @end example
27172 This tactic is suggested when the binder has determined that pragma
27173 @code{Elaborate}:
27176 @itemize -
27178 @item 
27179 Prevents a set of units from being elaborated.
27181 @item 
27182 The removal of the pragma will not eliminate the semantic effects of the
27183 pragma. In other words, the argument of the pragma will still be elaborated
27184 prior to the unit containing the pragma.
27186 @item 
27187 The removal of the pragma will enable the successful ordering of the units.
27188 @end itemize
27190 The programmer should remove the pragma as advised, and rebuild the program.
27192 @item 
27193 Pragma Elaborate_All elimination
27195 @example
27196 remove pragma Elaborate_All for unit "..." in unit "..."
27197 @end example
27199 This tactic is suggested when the binder has determined that pragma
27200 @code{Elaborate_All}:
27203 @itemize -
27205 @item 
27206 Prevents a set of units from being elaborated.
27208 @item 
27209 The removal of the pragma will not eliminate the semantic effects of the
27210 pragma. In other words, the argument of the pragma along with its @emph{with}
27211 closure will still be elaborated prior to the unit containing the pragma.
27213 @item 
27214 The removal of the pragma will enable the successful ordering of the units.
27215 @end itemize
27217 The programmer should remove the pragma as advised, and rebuild the program.
27219 @item 
27220 Pragma Elaborate_All downgrade
27222 @example
27223 change pragma Elaborate_All for unit "..." to Elaborate in unit "..."
27224 @end example
27226 This tactic is always suggested with the pragma @code{Elaborate_All} elimination
27227 tactic. It offers a different alernative of guaranteeing that the argument of
27228 the pragma will still be elaborated prior to the unit containing the pragma.
27230 The programmer should update the pragma as advised, and rebuild the program.
27232 @item 
27233 Pragma Elaborate_Body elimination
27235 @example
27236 remove pragma Elaborate_Body in unit "..."
27237 @end example
27239 This tactic is suggested when the binder has determined that pragma
27240 @code{Elaborate_Body}:
27243 @itemize -
27245 @item 
27246 Prevents a set of units from being elaborated.
27248 @item 
27249 The removal of the pragma will enable the successful ordering of the units.
27250 @end itemize
27252 Note that the binder cannot determine whether the pragma is required for
27253 other purposes, such as guaranteeing the initialization of a variable
27254 declared in the spec by elaboration code in the body.
27256 The programmer should remove the pragma as advised, and rebuild the program.
27258 @item 
27259 Use of pragma Restrictions
27261 @example
27262 use pragma Restrictions (No_Entry_Calls_In_Elaboration_Code)
27263 @end example
27265 This tactic is suggested when the binder has determined that a task
27266 activation at elaboration time:
27269 @itemize -
27271 @item 
27272 Prevents a set of units from being elaborated.
27273 @end itemize
27275 Note that the binder cannot determine with certainty whether the task will
27276 block at elaboration time.
27278 The programmer should create a configuration file, place the pragma within,
27279 update the general compilation arguments, and rebuild the program.
27281 @item 
27282 Use of dynamic elaboration model
27284 @example
27285 use the dynamic elaboration model (compiler switch -gnatE)
27286 @end example
27288 This tactic is suggested when the binder has determined that an invocation at
27289 elaboration time:
27292 @itemize -
27294 @item 
27295 Prevents a set of units from being elaborated.
27297 @item 
27298 The use of the dynamic model will enable the successful ordering of the
27299 units.
27300 @end itemize
27302 The programmer has two options:
27305 @itemize -
27307 @item 
27308 Determine the units involved in the invocation using the detailed
27309 invocation information, and add compiler switch @code{-gnatE} to the
27310 compilation arguments of selected files only. This approach will yield
27311 safer elaboration orders compared to the other option because it will
27312 minimize the opportunities presented to the dynamic model for ignoring
27313 invocations.
27315 @item 
27316 Add compiler switch @code{-gnatE} to the general compilation arguments.
27317 @end itemize
27319 @item 
27320 Use of detailed invocation information
27322 @example
27323 use detailed invocation information (compiler switch -gnatd_F)
27324 @end example
27326 This tactic is always suggested with the use of the dynamic model tactic. It
27327 causes the circularity section of the circularity diagnostic to describe the
27328 flow of elaboration code from a unit to a unit, enumerating all such paths in
27329 the process.
27331 The programmer should analyze this information to determine which units
27332 should be compiled with the dynamic model.
27334 @item 
27335 Forced-dependency elimination
27337 @example
27338 remove the dependency of unit "..." on unit "..." from the argument of switch -f
27339 @end example
27341 This tactic is suggested when the binder has determined that a dependency
27342 present in the forced-elaboration-order file indicated by binder switch
27343 @code{-f}:
27346 @itemize -
27348 @item 
27349 Prevents a set of units from being elaborated.
27351 @item 
27352 The removal of the dependency will enable the successful ordering of the
27353 units.
27354 @end itemize
27356 The programmer should edit the forced-elaboration-order file, remove the
27357 dependency, and rebind the program.
27359 @item 
27360 All forced-dependency elimination
27362 @example
27363 remove switch -f
27364 @end example
27366 This tactic is suggested in case editing the forced-elaboration-order file is
27367 not an option.
27369 The programmer should remove binder switch @code{-f} from the binder
27370 arguments, and rebind.
27372 @item 
27373 Multiple-circularities diagnostic
27375 @example
27376 diagnose all circularities (binder switch -d_C)
27377 @end example
27379 By default, the binder will diagnose only the highest-precedence circularity.
27380 If the program contains multiple circularities, the binder will suggest the
27381 use of binder switch @code{-d_C} in order to obtain the diagnostics of all
27382 circularities.
27384 The programmer should add binder switch @code{-d_C} to the binder
27385 arguments, and rebind.
27386 @end itemize
27388 If none of the tactics suggested by the binder eliminate the elaboration
27389 circularity, the programmer should consider using one of the legacy elaboration
27390 models, in the following order:
27393 @itemize *
27395 @item 
27396 Use the pre-20.x legacy elaboration-order model, with binder switch
27397 @code{-H}.
27399 @item 
27400 Use both pre-18.x and pre-20.x legacy elaboration models, with compiler
27401 switch @code{-gnatH} and binder switch @code{-H}.
27403 @item 
27404 Use the relaxed static-elaboration model, with compiler switches
27405 @code{-gnatH} @code{-gnatJ} and binder switch @code{-H}.
27407 @item 
27408 Use the relaxed dynamic-elaboration model, with compiler switches
27409 @code{-gnatH} @code{-gnatJ} @code{-gnatE} and binder switch
27410 @code{-H}.
27411 @end itemize
27413 @node Elaboration-related Compiler Switches,Summary of Procedures for Elaboration Control,Resolving Elaboration Circularities,Elaboration Order Handling in GNAT
27414 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-related-compiler-switches}@anchor{22c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id12}@anchor{22d}
27415 @section Elaboration-related Compiler Switches
27418 GNAT has several switches that affect the elaboration model and consequently
27419 the elaboration order chosen by the binder.
27421 @geindex -gnatE (gnat)
27424 @table @asis
27426 @item @code{-gnatE}
27428 Dynamic elaboration checking mode enabled
27430 When this switch is in effect, GNAT activates the dynamic model.
27431 @end table
27433 @geindex -gnatel (gnat)
27436 @table @asis
27438 @item @code{-gnatel}
27440 Turn on info messages on generated Elaborate[_All] pragmas
27442 This switch is only applicable to the pre-20.x legacy elaboration models.
27443 The post-20.x elaboration model no longer relies on implicitly generated
27444 @code{Elaborate} and @code{Elaborate_All} pragmas to order units.
27446 When this switch is in effect, GNAT will emit the following supplementary
27447 information depending on the elaboration model in effect.
27450 @itemize -
27452 @item 
27453 @emph{Dynamic model}
27455 GNAT will indicate missing @code{Elaborate} and @code{Elaborate_All} pragmas for
27456 all library-level scenarios within the partition.
27458 @item 
27459 @emph{Static model}
27461 GNAT will indicate all scenarios invoked during elaboration. In addition,
27462 it will provide detailed traceback when an implicit @code{Elaborate} or
27463 @code{Elaborate_All} pragma is generated.
27465 @item 
27466 @emph{SPARK model}
27468 GNAT will indicate how an elaboration requirement is met by the context of
27469 a unit. This diagnostic requires compiler switch @code{-gnatd.v}.
27471 @example
27472 1. with Server; pragma Elaborate_All (Server);
27473 2. package Client with SPARK_Mode is
27474 3.    Val : constant Integer := Server.Func;
27475                                       |
27476    >>> info: call to "Func" during elaboration in SPARK
27477    >>> info: "Elaborate_All" requirement for unit "Server" met by pragma at line 1
27479 4. end Client;
27480 @end example
27481 @end itemize
27482 @end table
27484 @geindex -gnatH (gnat)
27487 @table @asis
27489 @item @code{-gnatH}
27491 Legacy elaboration checking mode enabled
27493 When this switch is in effect, GNAT will utilize the pre-18.x elaboration
27494 model.
27495 @end table
27497 @geindex -gnatJ (gnat)
27500 @table @asis
27502 @item @code{-gnatJ}
27504 Relaxed elaboration checking mode enabled
27506 When this switch is in effect, GNAT will not process certain scenarios,
27507 resulting in a more permissive elaboration model. Note that this may
27508 eliminate some diagnostics and run-time checks.
27509 @end table
27511 @geindex -gnatw.f (gnat)
27514 @table @asis
27516 @item @code{-gnatw.f}
27518 Turn on warnings for suspicious Subp’Access
27520 When this switch is in effect, GNAT will treat @code{'Access} of an entry,
27521 operator, or subprogram as a potential call to the target and issue warnings:
27523 @example
27524  1. package body Attribute_Call is
27525  2.    function Func return Integer;
27526  3.    type Func_Ptr is access function return Integer;
27527  4.
27528  5.    Ptr : constant Func_Ptr := Func'Access;
27529                                       |
27530     >>> warning: "Access" attribute of "Func" before body seen
27531     >>> warning: possible Program_Error on later references
27532     >>> warning:   body of unit "Attribute_Call" elaborated
27533     >>> warning:   "Access" of "Func" taken at line 5
27535  6.
27536  7.    function Func return Integer is
27537  8.    begin
27538  9.       ...
27539 10.    end Func;
27540 11. end Attribute_Call;
27541 @end example
27543 In the example above, the elaboration of declaration @code{Ptr} is assigned
27544 @code{Func'Access} before the body of @code{Func} has been elaborated.
27545 @end table
27547 @geindex -gnatwl (gnat)
27550 @table @asis
27552 @item @code{-gnatwl}
27554 Turn on warnings for elaboration problems
27556 When this switch is in effect, GNAT emits diagnostics in the form of warnings
27557 concerning various elaboration problems. The warnings are enabled by default.
27558 The switch is provided in case all warnings are suppressed, but elaboration
27559 warnings are still desired.
27561 @item @code{-gnatwL}
27563 Turn off warnings for elaboration problems
27565 When this switch is in effect, GNAT no longer emits any diagnostics in the
27566 form of warnings. Selective suppression of elaboration problems is possible
27567 using @code{pragma Warnings (Off)}.
27569 @example
27570  1. package body Selective_Suppression is
27571  2.    function ABE return Integer;
27572  3.
27573  4.    Val_1 : constant Integer := ABE;
27574                                    |
27575     >>> warning: cannot call "ABE" before body seen
27576     >>> warning: Program_Error will be raised at run time
27578  5.
27579  6.    pragma Warnings (Off);
27580  7.    Val_2 : constant Integer := ABE;
27581  8.    pragma Warnings (On);
27582  9.
27583 10.    function ABE return Integer is
27584 11.    begin
27585 12.       ...
27586 13.    end ABE;
27587 14. end Selective_Suppression;
27588 @end example
27590 Note that suppressing elaboration warnings does not eliminate run-time
27591 checks. The example above will still fail at run time with an ABE.
27592 @end table
27594 @node Summary of Procedures for Elaboration Control,Inspecting the Chosen Elaboration Order,Elaboration-related Compiler Switches,Elaboration Order Handling in GNAT
27595 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id13}@anchor{22e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat summary-of-procedures-for-elaboration-control}@anchor{22f}
27596 @section Summary of Procedures for Elaboration Control
27599 A programmer should first compile the program with the default options, using
27600 none of the binder or compiler switches. If the binder succeeds in finding an
27601 elaboration order, then apart from possible cases involing dispatching calls
27602 and access-to-subprogram types, the program is free of elaboration errors.
27604 If it is important for the program to be portable to compilers other than GNAT,
27605 then the programmer should use compiler switch @code{-gnatel} and consider
27606 the messages about missing or implicitly created @code{Elaborate} and
27607 @code{Elaborate_All} pragmas.
27609 If the binder reports an elaboration circularity, the programmer has several
27610 options:
27613 @itemize *
27615 @item 
27616 Ensure that elaboration warnings are enabled. This will allow the static
27617 model to output trace information of elaboration issues. The trace
27618 information could shed light on previously unforeseen dependencies, as well
27619 as their origins. Elaboration warnings are enabled with compiler switch
27620 @code{-gnatwl}.
27622 @item 
27623 Cosider the tactics given in the suggestions section of the circularity
27624 diagnostic.
27626 @item 
27627 If none of the steps outlined above resolve the circularity, use a more
27628 permissive elaboration model, in the following order:
27631 @itemize -
27633 @item 
27634 Use the pre-20.x legacy elaboration-order model, with binder switch
27635 @code{-H}.
27637 @item 
27638 Use both pre-18.x and pre-20.x legacy elaboration models, with compiler
27639 switch @code{-gnatH} and binder switch @code{-H}.
27641 @item 
27642 Use the relaxed static elaboration model, with compiler switches
27643 @code{-gnatH} @code{-gnatJ} and binder switch @code{-H}.
27645 @item 
27646 Use the relaxed dynamic elaboration model, with compiler switches
27647 @code{-gnatH} @code{-gnatJ} @code{-gnatE} and binder switch
27648 @code{-H}.
27649 @end itemize
27650 @end itemize
27652 @node Inspecting the Chosen Elaboration Order,,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
27653 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id14}@anchor{230}@anchor{gnat_ugn/elaboration_order_handling_in_gnat inspecting-the-chosen-elaboration-order}@anchor{231}
27654 @section Inspecting the Chosen Elaboration Order
27657 To see the elaboration order chosen by the binder, inspect the contents of file
27658 @cite{b~xxx.adb}. On certain targets, this file appears as @cite{b_xxx.adb}. The
27659 elaboration order appears as a sequence of calls to @code{Elab_Body} and
27660 @code{Elab_Spec}, interspersed with assignments to @cite{Exxx} which indicates that a
27661 particular unit is elaborated. For example:
27663 @quotation
27665 @example
27666 System.Soft_Links'Elab_Body;
27667 E14 := True;
27668 System.Secondary_Stack'Elab_Body;
27669 E18 := True;
27670 System.Exception_Table'Elab_Body;
27671 E24 := True;
27672 Ada.Io_Exceptions'Elab_Spec;
27673 E67 := True;
27674 Ada.Tags'Elab_Spec;
27675 Ada.Streams'Elab_Spec;
27676 E43 := True;
27677 Interfaces.C'Elab_Spec;
27678 E69 := True;
27679 System.Finalization_Root'Elab_Spec;
27680 E60 := True;
27681 System.Os_Lib'Elab_Body;
27682 E71 := True;
27683 System.Finalization_Implementation'Elab_Spec;
27684 System.Finalization_Implementation'Elab_Body;
27685 E62 := True;
27686 Ada.Finalization'Elab_Spec;
27687 E58 := True;
27688 Ada.Finalization.List_Controller'Elab_Spec;
27689 E76 := True;
27690 System.File_Control_Block'Elab_Spec;
27691 E74 := True;
27692 System.File_Io'Elab_Body;
27693 E56 := True;
27694 Ada.Tags'Elab_Body;
27695 E45 := True;
27696 Ada.Text_Io'Elab_Spec;
27697 Ada.Text_Io'Elab_Body;
27698 E07 := True;
27699 @end example
27700 @end quotation
27702 Note also binder switch @code{-l}, which outputs the chosen elaboration
27703 order and provides a more readable form of the above:
27705 @quotation
27707 @example
27708 ada (spec)
27709 interfaces (spec)
27710 system (spec)
27711 system.case_util (spec)
27712 system.case_util (body)
27713 system.concat_2 (spec)
27714 system.concat_2 (body)
27715 system.concat_3 (spec)
27716 system.concat_3 (body)
27717 system.htable (spec)
27718 system.parameters (spec)
27719 system.parameters (body)
27720 system.crtl (spec)
27721 interfaces.c_streams (spec)
27722 interfaces.c_streams (body)
27723 system.restrictions (spec)
27724 system.restrictions (body)
27725 system.standard_library (spec)
27726 system.exceptions (spec)
27727 system.exceptions (body)
27728 system.storage_elements (spec)
27729 system.storage_elements (body)
27730 system.secondary_stack (spec)
27731 system.stack_checking (spec)
27732 system.stack_checking (body)
27733 system.string_hash (spec)
27734 system.string_hash (body)
27735 system.htable (body)
27736 system.strings (spec)
27737 system.strings (body)
27738 system.traceback (spec)
27739 system.traceback (body)
27740 system.traceback_entries (spec)
27741 system.traceback_entries (body)
27742 ada.exceptions (spec)
27743 ada.exceptions.last_chance_handler (spec)
27744 system.soft_links (spec)
27745 system.soft_links (body)
27746 ada.exceptions.last_chance_handler (body)
27747 system.secondary_stack (body)
27748 system.exception_table (spec)
27749 system.exception_table (body)
27750 ada.io_exceptions (spec)
27751 ada.tags (spec)
27752 ada.streams (spec)
27753 interfaces.c (spec)
27754 interfaces.c (body)
27755 system.finalization_root (spec)
27756 system.finalization_root (body)
27757 system.memory (spec)
27758 system.memory (body)
27759 system.standard_library (body)
27760 system.os_lib (spec)
27761 system.os_lib (body)
27762 system.unsigned_types (spec)
27763 system.stream_attributes (spec)
27764 system.stream_attributes (body)
27765 system.finalization_implementation (spec)
27766 system.finalization_implementation (body)
27767 ada.finalization (spec)
27768 ada.finalization (body)
27769 ada.finalization.list_controller (spec)
27770 ada.finalization.list_controller (body)
27771 system.file_control_block (spec)
27772 system.file_io (spec)
27773 system.file_io (body)
27774 system.val_uns (spec)
27775 system.val_util (spec)
27776 system.val_util (body)
27777 system.val_uns (body)
27778 system.wch_con (spec)
27779 system.wch_con (body)
27780 system.wch_cnv (spec)
27781 system.wch_jis (spec)
27782 system.wch_jis (body)
27783 system.wch_cnv (body)
27784 system.wch_stw (spec)
27785 system.wch_stw (body)
27786 ada.tags (body)
27787 ada.exceptions (body)
27788 ada.text_io (spec)
27789 ada.text_io (body)
27790 text_io (spec)
27791 gdbstr (body)
27792 @end example
27793 @end quotation
27795 @node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
27796 @anchor{gnat_ugn/inline_assembler doc}@anchor{232}@anchor{gnat_ugn/inline_assembler id1}@anchor{233}@anchor{gnat_ugn/inline_assembler inline-assembler}@anchor{10}
27797 @chapter Inline Assembler
27800 @geindex Inline Assembler
27802 If you need to write low-level software that interacts directly
27803 with the hardware, Ada provides two ways to incorporate assembly
27804 language code into your program.  First, you can import and invoke
27805 external routines written in assembly language, an Ada feature fully
27806 supported by GNAT.  However, for small sections of code it may be simpler
27807 or more efficient to include assembly language statements directly
27808 in your Ada source program, using the facilities of the implementation-defined
27809 package @code{System.Machine_Code}, which incorporates the gcc
27810 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
27811 including the following:
27814 @itemize *
27816 @item 
27817 No need to use non-Ada tools
27819 @item 
27820 Consistent interface over different targets
27822 @item 
27823 Automatic usage of the proper calling conventions
27825 @item 
27826 Access to Ada constants and variables
27828 @item 
27829 Definition of intrinsic routines
27831 @item 
27832 Possibility of inlining a subprogram comprising assembler code
27834 @item 
27835 Code optimizer can take Inline Assembler code into account
27836 @end itemize
27838 This appendix presents a series of examples to show you how to use
27839 the Inline Assembler.  Although it focuses on the Intel x86,
27840 the general approach applies also to other processors.
27841 It is assumed that you are familiar with Ada
27842 and with assembly language programming.
27844 @menu
27845 * Basic Assembler Syntax:: 
27846 * A Simple Example of Inline Assembler:: 
27847 * Output Variables in Inline Assembler:: 
27848 * Input Variables in Inline Assembler:: 
27849 * Inlining Inline Assembler Code:: 
27850 * Other Asm Functionality:: 
27852 @end menu
27854 @node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
27855 @anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{234}@anchor{gnat_ugn/inline_assembler id2}@anchor{235}
27856 @section Basic Assembler Syntax
27859 The assembler used by GNAT and gcc is based not on the Intel assembly
27860 language, but rather on a language that descends from the AT&T Unix
27861 assembler @code{as} (and which is often referred to as ‘AT&T syntax’).
27862 The following table summarizes the main features of @code{as} syntax
27863 and points out the differences from the Intel conventions.
27864 See the gcc @code{as} and @code{gas} (an @code{as} macro
27865 pre-processor) documentation for further information.
27868 @display
27869 @emph{Register names}@w{ }
27870 @display
27871 gcc / @code{as}: Prefix with ‘%’; for example @code{%eax}@w{ }
27872 Intel: No extra punctuation; for example @code{eax}@w{ }
27873 @end display
27874 @end display
27879 @display
27880 @emph{Immediate operand}@w{ }
27881 @display
27882 gcc / @code{as}: Prefix with ‘$’; for example @code{$4}@w{ }
27883 Intel: No extra punctuation; for example @code{4}@w{ }
27884 @end display
27885 @end display
27890 @display
27891 @emph{Address}@w{ }
27892 @display
27893 gcc / @code{as}: Prefix with ‘$’; for example @code{$loc}@w{ }
27894 Intel: No extra punctuation; for example @code{loc}@w{ }
27895 @end display
27896 @end display
27901 @display
27902 @emph{Memory contents}@w{ }
27903 @display
27904 gcc / @code{as}: No extra punctuation; for example @code{loc}@w{ }
27905 Intel: Square brackets; for example @code{[loc]}@w{ }
27906 @end display
27907 @end display
27912 @display
27913 @emph{Register contents}@w{ }
27914 @display
27915 gcc / @code{as}: Parentheses; for example @code{(%eax)}@w{ }
27916 Intel: Square brackets; for example @code{[eax]}@w{ }
27917 @end display
27918 @end display
27923 @display
27924 @emph{Hexadecimal numbers}@w{ }
27925 @display
27926 gcc / @code{as}: Leading ‘0x’ (C language syntax); for example @code{0xA0}@w{ }
27927 Intel: Trailing ‘h’; for example @code{A0h}@w{ }
27928 @end display
27929 @end display
27934 @display
27935 @emph{Operand size}@w{ }
27936 @display
27937 gcc / @code{as}: Explicit in op code; for example @code{movw} to move a 16-bit word@w{ }
27938 Intel: Implicit, deduced by assembler; for example @code{mov}@w{ }
27939 @end display
27940 @end display
27945 @display
27946 @emph{Instruction repetition}@w{ }
27947 @display
27948 gcc / @code{as}: Split into two lines; for example@w{ }
27949 @display
27950 @code{rep}@w{ }
27951 @code{stosl}@w{ }
27952 @end display
27953 Intel: Keep on one line; for example @code{rep stosl}@w{ }
27954 @end display
27955 @end display
27960 @display
27961 @emph{Order of operands}@w{ }
27962 @display
27963 gcc / @code{as}: Source first; for example @code{movw $4, %eax}@w{ }
27964 Intel: Destination first; for example @code{mov eax, 4}@w{ }
27965 @end display
27966 @end display
27970 @node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
27971 @anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{236}@anchor{gnat_ugn/inline_assembler id3}@anchor{237}
27972 @section A Simple Example of Inline Assembler
27975 The following example will generate a single assembly language statement,
27976 @code{nop}, which does nothing.  Despite its lack of run-time effect,
27977 the example will be useful in illustrating the basics of
27978 the Inline Assembler facility.
27980 @quotation
27982 @example
27983 with System.Machine_Code; use System.Machine_Code;
27984 procedure Nothing is
27985 begin
27986    Asm ("nop");
27987 end Nothing;
27988 @end example
27989 @end quotation
27991 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
27992 here it takes one parameter, a @emph{template string} that must be a static
27993 expression and that will form the generated instruction.
27994 @code{Asm} may be regarded as a compile-time procedure that parses
27995 the template string and additional parameters (none here),
27996 from which it generates a sequence of assembly language instructions.
27998 The examples in this chapter will illustrate several of the forms
27999 for invoking @code{Asm}; a complete specification of the syntax
28000 is found in the @code{Machine_Code_Insertions} section of the
28001 @cite{GNAT Reference Manual}.
28003 Under the standard GNAT conventions, the @code{Nothing} procedure
28004 should be in a file named @code{nothing.adb}.
28005 You can build the executable in the usual way:
28007 @quotation
28009 @example
28010 $ gnatmake nothing
28011 @end example
28012 @end quotation
28014 However, the interesting aspect of this example is not its run-time behavior
28015 but rather the generated assembly code.
28016 To see this output, invoke the compiler as follows:
28018 @quotation
28020 @example
28021 $ gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
28022 @end example
28023 @end quotation
28025 where the options are:
28028 @itemize *
28030 @item 
28032 @table @asis
28034 @item @code{-c}
28036 compile only (no bind or link)
28037 @end table
28039 @item 
28041 @table @asis
28043 @item @code{-S}
28045 generate assembler listing
28046 @end table
28048 @item 
28050 @table @asis
28052 @item @code{-fomit-frame-pointer}
28054 do not set up separate stack frames
28055 @end table
28057 @item 
28059 @table @asis
28061 @item @code{-gnatp}
28063 do not add runtime checks
28064 @end table
28065 @end itemize
28067 This gives a human-readable assembler version of the code. The resulting
28068 file will have the same name as the Ada source file, but with a @code{.s}
28069 extension. In our example, the file @code{nothing.s} has the following
28070 contents:
28072 @quotation
28074 @example
28075 .file "nothing.adb"
28076 gcc2_compiled.:
28077 ___gnu_compiled_ada:
28078 .text
28079    .align 4
28080 .globl __ada_nothing
28081 __ada_nothing:
28082 #APP
28083    nop
28084 #NO_APP
28085    jmp L1
28086    .align 2,0x90
28088    ret
28089 @end example
28090 @end quotation
28092 The assembly code you included is clearly indicated by
28093 the compiler, between the @code{#APP} and @code{#NO_APP}
28094 delimiters. The character before the ‘APP’ and ‘NOAPP’
28095 can differ on different targets. For example, GNU/Linux uses ‘#APP’ while
28096 on NT you will see ‘/APP’.
28098 If you make a mistake in your assembler code (such as using the
28099 wrong size modifier, or using a wrong operand for the instruction) GNAT
28100 will report this error in a temporary file, which will be deleted when
28101 the compilation is finished.  Generating an assembler file will help
28102 in such cases, since you can assemble this file separately using the
28103 @code{as} assembler that comes with gcc.
28105 Assembling the file using the command
28107 @quotation
28109 @example
28110 $ as nothing.s
28111 @end example
28112 @end quotation
28114 will give you error messages whose lines correspond to the assembler
28115 input file, so you can easily find and correct any mistakes you made.
28116 If there are no errors, @code{as} will generate an object file
28117 @code{nothing.out}.
28119 @node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
28120 @anchor{gnat_ugn/inline_assembler id4}@anchor{238}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{239}
28121 @section Output Variables in Inline Assembler
28124 The examples in this section, showing how to access the processor flags,
28125 illustrate how to specify the destination operands for assembly language
28126 statements.
28128 @quotation
28130 @example
28131 with Interfaces; use Interfaces;
28132 with Ada.Text_IO; use Ada.Text_IO;
28133 with System.Machine_Code; use System.Machine_Code;
28134 procedure Get_Flags is
28135    Flags : Unsigned_32;
28136    use ASCII;
28137 begin
28138    Asm ("pushfl"          & LF & HT & -- push flags on stack
28139         "popl %%eax"      & LF & HT & -- load eax with flags
28140         "movl %%eax, %0",             -- store flags in variable
28141         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28142    Put_Line ("Flags register:" & Flags'Img);
28143 end Get_Flags;
28144 @end example
28145 @end quotation
28147 In order to have a nicely aligned assembly listing, we have separated
28148 multiple assembler statements in the Asm template string with linefeed
28149 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
28150 The resulting section of the assembly output file is:
28152 @quotation
28154 @example
28155 #APP
28156    pushfl
28157    popl %eax
28158    movl %eax, -40(%ebp)
28159 #NO_APP
28160 @end example
28161 @end quotation
28163 It would have been legal to write the Asm invocation as:
28165 @quotation
28167 @example
28168 Asm ("pushfl popl %%eax movl %%eax, %0")
28169 @end example
28170 @end quotation
28172 but in the generated assembler file, this would come out as:
28174 @quotation
28176 @example
28177 #APP
28178    pushfl popl %eax movl %eax, -40(%ebp)
28179 #NO_APP
28180 @end example
28181 @end quotation
28183 which is not so convenient for the human reader.
28185 We use Ada comments
28186 at the end of each line to explain what the assembler instructions
28187 actually do.  This is a useful convention.
28189 When writing Inline Assembler instructions, you need to precede each register
28190 and variable name with a percent sign.  Since the assembler already requires
28191 a percent sign at the beginning of a register name, you need two consecutive
28192 percent signs for such names in the Asm template string, thus @code{%%eax}.
28193 In the generated assembly code, one of the percent signs will be stripped off.
28195 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28196 variables: operands you later define using @code{Input} or @code{Output}
28197 parameters to @code{Asm}.
28198 An output variable is illustrated in
28199 the third statement in the Asm template string:
28201 @quotation
28203 @example
28204 movl %%eax, %0
28205 @end example
28206 @end quotation
28208 The intent is to store the contents of the eax register in a variable that can
28209 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
28210 necessarily work, since the compiler might optimize by using a register
28211 to hold Flags, and the expansion of the @code{movl} instruction would not be
28212 aware of this optimization.  The solution is not to store the result directly
28213 but rather to advise the compiler to choose the correct operand form;
28214 that is the purpose of the @code{%0} output variable.
28216 Information about the output variable is supplied in the @code{Outputs}
28217 parameter to @code{Asm}:
28219 @quotation
28221 @example
28222 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28223 @end example
28224 @end quotation
28226 The output is defined by the @code{Asm_Output} attribute of the target type;
28227 the general format is
28229 @quotation
28231 @example
28232 Type'Asm_Output (constraint_string, variable_name)
28233 @end example
28234 @end quotation
28236 The constraint string directs the compiler how
28237 to store/access the associated variable.  In the example
28239 @quotation
28241 @example
28242 Unsigned_32'Asm_Output ("=m", Flags);
28243 @end example
28244 @end quotation
28246 the @code{"m"} (memory) constraint tells the compiler that the variable
28247 @code{Flags} should be stored in a memory variable, thus preventing
28248 the optimizer from keeping it in a register.  In contrast,
28250 @quotation
28252 @example
28253 Unsigned_32'Asm_Output ("=r", Flags);
28254 @end example
28255 @end quotation
28257 uses the @code{"r"} (register) constraint, telling the compiler to
28258 store the variable in a register.
28260 If the constraint is preceded by the equal character ‘=’, it tells
28261 the compiler that the variable will be used to store data into it.
28263 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28264 allowing the optimizer to choose whatever it deems best.
28266 There are a fairly large number of constraints, but the ones that are
28267 most useful (for the Intel x86 processor) are the following:
28269 @quotation
28272 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
28273 @item
28275 @emph{=}
28277 @tab
28279 output constraint
28281 @item
28283 @emph{g}
28285 @tab
28287 global (i.e., can be stored anywhere)
28289 @item
28291 @emph{m}
28293 @tab
28295 in memory
28297 @item
28299 @emph{I}
28301 @tab
28303 a constant
28305 @item
28307 @emph{a}
28309 @tab
28311 use eax
28313 @item
28315 @emph{b}
28317 @tab
28319 use ebx
28321 @item
28323 @emph{c}
28325 @tab
28327 use ecx
28329 @item
28331 @emph{d}
28333 @tab
28335 use edx
28337 @item
28339 @emph{S}
28341 @tab
28343 use esi
28345 @item
28347 @emph{D}
28349 @tab
28351 use edi
28353 @item
28355 @emph{r}
28357 @tab
28359 use one of eax, ebx, ecx or edx
28361 @item
28363 @emph{q}
28365 @tab
28367 use one of eax, ebx, ecx, edx, esi or edi
28369 @end multitable
28371 @end quotation
28373 The full set of constraints is described in the gcc and @code{as}
28374 documentation; note that it is possible to combine certain constraints
28375 in one constraint string.
28377 You specify the association of an output variable with an assembler operand
28378 through the @code{%@emph{n}} notation, where @emph{n} is a non-negative
28379 integer.  Thus in
28381 @quotation
28383 @example
28384 Asm ("pushfl"          & LF & HT & -- push flags on stack
28385      "popl %%eax"      & LF & HT & -- load eax with flags
28386      "movl %%eax, %0",             -- store flags in variable
28387      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28388 @end example
28389 @end quotation
28391 @code{%0} will be replaced in the expanded code by the appropriate operand,
28392 whatever
28393 the compiler decided for the @code{Flags} variable.
28395 In general, you may have any number of output variables:
28398 @itemize *
28400 @item 
28401 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28403 @item 
28404 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28405 of @code{Asm_Output} attributes
28406 @end itemize
28408 For example:
28410 @quotation
28412 @example
28413 Asm ("movl %%eax, %0" & LF & HT &
28414      "movl %%ebx, %1" & LF & HT &
28415      "movl %%ecx, %2",
28416      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
28417                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
28418                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
28419 @end example
28420 @end quotation
28422 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28423 in the Ada program.
28425 As a variation on the @code{Get_Flags} example, we can use the constraints
28426 string to direct the compiler to store the eax register into the @code{Flags}
28427 variable, instead of including the store instruction explicitly in the
28428 @code{Asm} template string:
28430 @quotation
28432 @example
28433 with Interfaces; use Interfaces;
28434 with Ada.Text_IO; use Ada.Text_IO;
28435 with System.Machine_Code; use System.Machine_Code;
28436 procedure Get_Flags_2 is
28437    Flags : Unsigned_32;
28438    use ASCII;
28439 begin
28440    Asm ("pushfl"      & LF & HT & -- push flags on stack
28441         "popl %%eax",             -- save flags in eax
28442         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28443    Put_Line ("Flags register:" & Flags'Img);
28444 end Get_Flags_2;
28445 @end example
28446 @end quotation
28448 The @code{"a"} constraint tells the compiler that the @code{Flags}
28449 variable will come from the eax register. Here is the resulting code:
28451 @quotation
28453 @example
28454 #APP
28455    pushfl
28456    popl %eax
28457 #NO_APP
28458    movl %eax,-40(%ebp)
28459 @end example
28460 @end quotation
28462 The compiler generated the store of eax into Flags after
28463 expanding the assembler code.
28465 Actually, there was no need to pop the flags into the eax register;
28466 more simply, we could just pop the flags directly into the program variable:
28468 @quotation
28470 @example
28471 with Interfaces; use Interfaces;
28472 with Ada.Text_IO; use Ada.Text_IO;
28473 with System.Machine_Code; use System.Machine_Code;
28474 procedure Get_Flags_3 is
28475    Flags : Unsigned_32;
28476    use ASCII;
28477 begin
28478    Asm ("pushfl"  & LF & HT & -- push flags on stack
28479         "pop %0",             -- save flags in Flags
28480         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28481    Put_Line ("Flags register:" & Flags'Img);
28482 end Get_Flags_3;
28483 @end example
28484 @end quotation
28486 @node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
28487 @anchor{gnat_ugn/inline_assembler id5}@anchor{23a}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{23b}
28488 @section Input Variables in Inline Assembler
28491 The example in this section illustrates how to specify the source operands
28492 for assembly language statements.
28493 The program simply increments its input value by 1:
28495 @quotation
28497 @example
28498 with Interfaces; use Interfaces;
28499 with Ada.Text_IO; use Ada.Text_IO;
28500 with System.Machine_Code; use System.Machine_Code;
28501 procedure Increment is
28503    function Incr (Value : Unsigned_32) return Unsigned_32 is
28504       Result : Unsigned_32;
28505    begin
28506       Asm ("incl %0",
28507            Outputs => Unsigned_32'Asm_Output ("=a", Result),
28508            Inputs  => Unsigned_32'Asm_Input ("a", Value));
28509       return Result;
28510    end Incr;
28512    Value : Unsigned_32;
28514 begin
28515    Value := 5;
28516    Put_Line ("Value before is" & Value'Img);
28517    Value := Incr (Value);
28518   Put_Line ("Value after is" & Value'Img);
28519 end Increment;
28520 @end example
28521 @end quotation
28523 The @code{Outputs} parameter to @code{Asm} specifies
28524 that the result will be in the eax register and that it is to be stored
28525 in the @code{Result} variable.
28527 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28528 but with an @code{Asm_Input} attribute.
28529 The @code{"="} constraint, indicating an output value, is not present.
28531 You can have multiple input variables, in the same way that you can have more
28532 than one output variable.
28534 The parameter count (%0, %1) etc, still starts at the first output statement,
28535 and continues with the input statements.
28537 Just as the @code{Outputs} parameter causes the register to be stored into the
28538 target variable after execution of the assembler statements, so does the
28539 @code{Inputs} parameter cause its variable to be loaded into the register
28540 before execution of the assembler statements.
28542 Thus the effect of the @code{Asm} invocation is:
28545 @itemize *
28547 @item 
28548 load the 32-bit value of @code{Value} into eax
28550 @item 
28551 execute the @code{incl %eax} instruction
28553 @item 
28554 store the contents of eax into the @code{Result} variable
28555 @end itemize
28557 The resulting assembler file (with @code{-O2} optimization) contains:
28559 @quotation
28561 @example
28562 _increment__incr.1:
28563    subl $4,%esp
28564    movl 8(%esp),%eax
28565 #APP
28566    incl %eax
28567 #NO_APP
28568    movl %eax,%edx
28569    movl %ecx,(%esp)
28570    addl $4,%esp
28571    ret
28572 @end example
28573 @end quotation
28575 @node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
28576 @anchor{gnat_ugn/inline_assembler id6}@anchor{23c}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{23d}
28577 @section Inlining Inline Assembler Code
28580 For a short subprogram such as the @code{Incr} function in the previous
28581 section, the overhead of the call and return (creating / deleting the stack
28582 frame) can be significant, compared to the amount of code in the subprogram
28583 body.  A solution is to apply Ada’s @code{Inline} pragma to the subprogram,
28584 which directs the compiler to expand invocations of the subprogram at the
28585 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28586 Here is the resulting program:
28588 @quotation
28590 @example
28591 with Interfaces; use Interfaces;
28592 with Ada.Text_IO; use Ada.Text_IO;
28593 with System.Machine_Code; use System.Machine_Code;
28594 procedure Increment_2 is
28596    function Incr (Value : Unsigned_32) return Unsigned_32 is
28597       Result : Unsigned_32;
28598    begin
28599       Asm ("incl %0",
28600            Outputs => Unsigned_32'Asm_Output ("=a", Result),
28601            Inputs  => Unsigned_32'Asm_Input ("a", Value));
28602       return Result;
28603    end Incr;
28604    pragma Inline (Increment);
28606    Value : Unsigned_32;
28608 begin
28609    Value := 5;
28610    Put_Line ("Value before is" & Value'Img);
28611    Value := Increment (Value);
28612    Put_Line ("Value after is" & Value'Img);
28613 end Increment_2;
28614 @end example
28615 @end quotation
28617 Compile the program with both optimization (@code{-O2}) and inlining
28618 (@code{-gnatn}) enabled.
28620 The @code{Incr} function is still compiled as usual, but at the
28621 point in @code{Increment} where our function used to be called:
28623 @quotation
28625 @example
28626 pushl %edi
28627 call _increment__incr.1
28628 @end example
28629 @end quotation
28631 the code for the function body directly appears:
28633 @quotation
28635 @example
28636 movl %esi,%eax
28637 #APP
28638    incl %eax
28639 #NO_APP
28640    movl %eax,%edx
28641 @end example
28642 @end quotation
28644 thus saving the overhead of stack frame setup and an out-of-line call.
28646 @node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
28647 @anchor{gnat_ugn/inline_assembler id7}@anchor{23e}@anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{23f}
28648 @section Other @code{Asm} Functionality
28651 This section describes two important parameters to the @code{Asm}
28652 procedure: @code{Clobber}, which identifies register usage;
28653 and @code{Volatile}, which inhibits unwanted optimizations.
28655 @menu
28656 * The Clobber Parameter:: 
28657 * The Volatile Parameter:: 
28659 @end menu
28661 @node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
28662 @anchor{gnat_ugn/inline_assembler id8}@anchor{240}@anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{241}
28663 @subsection The @code{Clobber} Parameter
28666 One of the dangers of intermixing assembly language and a compiled language
28667 such as Ada is that the compiler needs to be aware of which registers are
28668 being used by the assembly code.  In some cases, such as the earlier examples,
28669 the constraint string is sufficient to indicate register usage (e.g.,
28670 @code{"a"} for
28671 the eax register).  But more generally, the compiler needs an explicit
28672 identification of the registers that are used by the Inline Assembly
28673 statements.
28675 Using a register that the compiler doesn’t know about
28676 could be a side effect of an instruction (like @code{mull}
28677 storing its result in both eax and edx).
28678 It can also arise from explicit register usage in your
28679 assembly code; for example:
28681 @quotation
28683 @example
28684 Asm ("movl %0, %%ebx" & LF & HT &
28685      "movl %%ebx, %1",
28686      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28687      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
28688 @end example
28689 @end quotation
28691 where the compiler (since it does not analyze the @code{Asm} template string)
28692 does not know you are using the ebx register.
28694 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28695 to identify the registers that will be used by your assembly code:
28697 @quotation
28699 @example
28700 Asm ("movl %0, %%ebx" & LF & HT &
28701      "movl %%ebx, %1",
28702      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28703      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
28704      Clobber => "ebx");
28705 @end example
28706 @end quotation
28708 The Clobber parameter is a static string expression specifying the
28709 register(s) you are using.  Note that register names are @emph{not} prefixed
28710 by a percent sign. Also, if more than one register is used then their names
28711 are separated by commas; e.g., @code{"eax, ebx"}
28713 The @code{Clobber} parameter has several additional uses:
28716 @itemize *
28718 @item 
28719 Use ‘register’ name @code{cc} to indicate that flags might have changed
28721 @item 
28722 Use ‘register’ name @code{memory} if you changed a memory location
28723 @end itemize
28725 @node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
28726 @anchor{gnat_ugn/inline_assembler id9}@anchor{242}@anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{243}
28727 @subsection The @code{Volatile} Parameter
28730 @geindex Volatile parameter
28732 Compiler optimizations in the presence of Inline Assembler may sometimes have
28733 unwanted effects.  For example, when an @code{Asm} invocation with an input
28734 variable is inside a loop, the compiler might move the loading of the input
28735 variable outside the loop, regarding it as a one-time initialization.
28737 If this effect is not desired, you can disable such optimizations by setting
28738 the @code{Volatile} parameter to @code{True}; for example:
28740 @quotation
28742 @example
28743 Asm ("movl %0, %%ebx" & LF & HT &
28744      "movl %%ebx, %1",
28745      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
28746      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
28747      Clobber  => "ebx",
28748      Volatile => True);
28749 @end example
28750 @end quotation
28752 By default, @code{Volatile} is set to @code{False} unless there is no
28753 @code{Outputs} parameter.
28755 Although setting @code{Volatile} to @code{True} prevents unwanted
28756 optimizations, it will also disable other optimizations that might be
28757 important for efficiency. In general, you should set @code{Volatile}
28758 to @code{True} only if the compiler’s optimizations have created
28759 problems.
28761 @node GNU Free Documentation License,Index,Inline Assembler,Top
28762 @anchor{share/gnu_free_documentation_license doc}@anchor{244}@anchor{share/gnu_free_documentation_license gnu-fdl}@anchor{1}@anchor{share/gnu_free_documentation_license gnu-free-documentation-license}@anchor{245}
28763 @chapter GNU Free Documentation License
28766 Version 1.3, 3 November 2008
28768 Copyright  2000, 2001, 2002, 2007, 2008  Free Software Foundation, Inc
28769 @indicateurl{https://fsf.org/}
28771 Everyone is permitted to copy and distribute verbatim copies of this
28772 license document, but changing it is not allowed.
28774 @strong{Preamble}
28776 The purpose of this License is to make a manual, textbook, or other
28777 functional and useful document “free” in the sense of freedom: to
28778 assure everyone the effective freedom to copy and redistribute it,
28779 with or without modifying it, either commercially or noncommercially.
28780 Secondarily, this License preserves for the author and publisher a way
28781 to get credit for their work, while not being considered responsible
28782 for modifications made by others.
28784 This License is a kind of “copyleft”, which means that derivative
28785 works of the document must themselves be free in the same sense.  It
28786 complements the GNU General Public License, which is a copyleft
28787 license designed for free software.
28789 We have designed this License in order to use it for manuals for free
28790 software, because free software needs free documentation: a free
28791 program should come with manuals providing the same freedoms that the
28792 software does.  But this License is not limited to software manuals;
28793 it can be used for any textual work, regardless of subject matter or
28794 whether it is published as a printed book.  We recommend this License
28795 principally for works whose purpose is instruction or reference.
28797 @strong{1. APPLICABILITY AND DEFINITIONS}
28799 This License applies to any manual or other work, in any medium, that
28800 contains a notice placed by the copyright holder saying it can be
28801 distributed under the terms of this License.  Such a notice grants a
28802 world-wide, royalty-free license, unlimited in duration, to use that
28803 work under the conditions stated herein.  The @strong{Document}, below,
28804 refers to any such manual or work.  Any member of the public is a
28805 licensee, and is addressed as “@strong{you}”.  You accept the license if you
28806 copy, modify or distribute the work in a way requiring permission
28807 under copyright law.
28809 A “@strong{Modified Version}” of the Document means any work containing the
28810 Document or a portion of it, either copied verbatim, or with
28811 modifications and/or translated into another language.
28813 A “@strong{Secondary Section}” is a named appendix or a front-matter section of
28814 the Document that deals exclusively with the relationship of the
28815 publishers or authors of the Document to the Document’s overall subject
28816 (or to related matters) and contains nothing that could fall directly
28817 within that overall subject.  (Thus, if the Document is in part a
28818 textbook of mathematics, a Secondary Section may not explain any
28819 mathematics.)  The relationship could be a matter of historical
28820 connection with the subject or with related matters, or of legal,
28821 commercial, philosophical, ethical or political position regarding
28822 them.
28824 The “@strong{Invariant Sections}” are certain Secondary Sections whose titles
28825 are designated, as being those of Invariant Sections, in the notice
28826 that says that the Document is released under this License.  If a
28827 section does not fit the above definition of Secondary then it is not
28828 allowed to be designated as Invariant.  The Document may contain zero
28829 Invariant Sections.  If the Document does not identify any Invariant
28830 Sections then there are none.
28832 The “@strong{Cover Texts}” are certain short passages of text that are listed,
28833 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
28834 the Document is released under this License.  A Front-Cover Text may
28835 be at most 5 words, and a Back-Cover Text may be at most 25 words.
28837 A “@strong{Transparent}” copy of the Document means a machine-readable copy,
28838 represented in a format whose specification is available to the
28839 general public, that is suitable for revising the document
28840 straightforwardly with generic text editors or (for images composed of
28841 pixels) generic paint programs or (for drawings) some widely available
28842 drawing editor, and that is suitable for input to text formatters or
28843 for automatic translation to a variety of formats suitable for input
28844 to text formatters.  A copy made in an otherwise Transparent file
28845 format whose markup, or absence of markup, has been arranged to thwart
28846 or discourage subsequent modification by readers is not Transparent.
28847 An image format is not Transparent if used for any substantial amount
28848 of text.  A copy that is not “Transparent” is called @strong{Opaque}.
28850 Examples of suitable formats for Transparent copies include plain
28851 ASCII without markup, Texinfo input format, LaTeX input format, SGML
28852 or XML using a publicly available DTD, and standard-conforming simple
28853 HTML, PostScript or PDF designed for human modification.  Examples of
28854 transparent image formats include PNG, XCF and JPG.  Opaque formats
28855 include proprietary formats that can be read and edited only by
28856 proprietary word processors, SGML or XML for which the DTD and/or
28857 processing tools are not generally available, and the
28858 machine-generated HTML, PostScript or PDF produced by some word
28859 processors for output purposes only.
28861 The “@strong{Title Page}” means, for a printed book, the title page itself,
28862 plus such following pages as are needed to hold, legibly, the material
28863 this License requires to appear in the title page.  For works in
28864 formats which do not have any title page as such, “Title Page” means
28865 the text near the most prominent appearance of the work’s title,
28866 preceding the beginning of the body of the text.
28868 The “@strong{publisher}” means any person or entity that distributes
28869 copies of the Document to the public.
28871 A section “@strong{Entitled XYZ}” means a named subunit of the Document whose
28872 title either is precisely XYZ or contains XYZ in parentheses following
28873 text that translates XYZ in another language.  (Here XYZ stands for a
28874 specific section name mentioned below, such as “@strong{Acknowledgements}”,
28875 “@strong{Dedications}”, “@strong{Endorsements}”, or “@strong{History}”.)
28876 To “@strong{Preserve the Title}”
28877 of such a section when you modify the Document means that it remains a
28878 section “Entitled XYZ” according to this definition.
28880 The Document may include Warranty Disclaimers next to the notice which
28881 states that this License applies to the Document.  These Warranty
28882 Disclaimers are considered to be included by reference in this
28883 License, but only as regards disclaiming warranties: any other
28884 implication that these Warranty Disclaimers may have is void and has
28885 no effect on the meaning of this License.
28887 @strong{2. VERBATIM COPYING}
28889 You may copy and distribute the Document in any medium, either
28890 commercially or noncommercially, provided that this License, the
28891 copyright notices, and the license notice saying this License applies
28892 to the Document are reproduced in all copies, and that you add no other
28893 conditions whatsoever to those of this License.  You may not use
28894 technical measures to obstruct or control the reading or further
28895 copying of the copies you make or distribute.  However, you may accept
28896 compensation in exchange for copies.  If you distribute a large enough
28897 number of copies you must also follow the conditions in section 3.
28899 You may also lend copies, under the same conditions stated above, and
28900 you may publicly display copies.
28902 @strong{3. COPYING IN QUANTITY}
28904 If you publish printed copies (or copies in media that commonly have
28905 printed covers) of the Document, numbering more than 100, and the
28906 Document’s license notice requires Cover Texts, you must enclose the
28907 copies in covers that carry, clearly and legibly, all these Cover
28908 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
28909 the back cover.  Both covers must also clearly and legibly identify
28910 you as the publisher of these copies.  The front cover must present
28911 the full title with all words of the title equally prominent and
28912 visible.  You may add other material on the covers in addition.
28913 Copying with changes limited to the covers, as long as they preserve
28914 the title of the Document and satisfy these conditions, can be treated
28915 as verbatim copying in other respects.
28917 If the required texts for either cover are too voluminous to fit
28918 legibly, you should put the first ones listed (as many as fit
28919 reasonably) on the actual cover, and continue the rest onto adjacent
28920 pages.
28922 If you publish or distribute Opaque copies of the Document numbering
28923 more than 100, you must either include a machine-readable Transparent
28924 copy along with each Opaque copy, or state in or with each Opaque copy
28925 a computer-network location from which the general network-using
28926 public has access to download using public-standard network protocols
28927 a complete Transparent copy of the Document, free of added material.
28928 If you use the latter option, you must take reasonably prudent steps,
28929 when you begin distribution of Opaque copies in quantity, to ensure
28930 that this Transparent copy will remain thus accessible at the stated
28931 location until at least one year after the last time you distribute an
28932 Opaque copy (directly or through your agents or retailers) of that
28933 edition to the public.
28935 It is requested, but not required, that you contact the authors of the
28936 Document well before redistributing any large number of copies, to give
28937 them a chance to provide you with an updated version of the Document.
28939 @strong{4. MODIFICATIONS}
28941 You may copy and distribute a Modified Version of the Document under
28942 the conditions of sections 2 and 3 above, provided that you release
28943 the Modified Version under precisely this License, with the Modified
28944 Version filling the role of the Document, thus licensing distribution
28945 and modification of the Modified Version to whoever possesses a copy
28946 of it.  In addition, you must do these things in the Modified Version:
28949 @enumerate A
28951 @item 
28952 Use in the Title Page (and on the covers, if any) a title distinct
28953 from that of the Document, and from those of previous versions
28954 (which should, if there were any, be listed in the History section
28955 of the Document).  You may use the same title as a previous version
28956 if the original publisher of that version gives permission.
28958 @item 
28959 List on the Title Page, as authors, one or more persons or entities
28960 responsible for authorship of the modifications in the Modified
28961 Version, together with at least five of the principal authors of the
28962 Document (all of its principal authors, if it has fewer than five),
28963 unless they release you from this requirement.
28965 @item 
28966 State on the Title page the name of the publisher of the
28967 Modified Version, as the publisher.
28969 @item 
28970 Preserve all the copyright notices of the Document.
28972 @item 
28973 Add an appropriate copyright notice for your modifications
28974 adjacent to the other copyright notices.
28976 @item 
28977 Include, immediately after the copyright notices, a license notice
28978 giving the public permission to use the Modified Version under the
28979 terms of this License, in the form shown in the Addendum below.
28981 @item 
28982 Preserve in that license notice the full lists of Invariant Sections
28983 and required Cover Texts given in the Document’s license notice.
28985 @item 
28986 Include an unaltered copy of this License.
28988 @item 
28989 Preserve the section Entitled “History”, Preserve its Title, and add
28990 to it an item stating at least the title, year, new authors, and
28991 publisher of the Modified Version as given on the Title Page.  If
28992 there is no section Entitled “History” in the Document, create one
28993 stating the title, year, authors, and publisher of the Document as
28994 given on its Title Page, then add an item describing the Modified
28995 Version as stated in the previous sentence.
28997 @item 
28998 Preserve the network location, if any, given in the Document for
28999 public access to a Transparent copy of the Document, and likewise
29000 the network locations given in the Document for previous versions
29001 it was based on.  These may be placed in the “History” section.
29002 You may omit a network location for a work that was published at
29003 least four years before the Document itself, or if the original
29004 publisher of the version it refers to gives permission.
29006 @item 
29007 For any section Entitled “Acknowledgements” or “Dedications”,
29008 Preserve the Title of the section, and preserve in the section all
29009 the substance and tone of each of the contributor acknowledgements
29010 and/or dedications given therein.
29012 @item 
29013 Preserve all the Invariant Sections of the Document,
29014 unaltered in their text and in their titles.  Section numbers
29015 or the equivalent are not considered part of the section titles.
29017 @item 
29018 Delete any section Entitled “Endorsements”.  Such a section
29019 may not be included in the Modified Version.
29021 @item 
29022 Do not retitle any existing section to be Entitled “Endorsements”
29023 or to conflict in title with any Invariant Section.
29025 @item 
29026 Preserve any Warranty Disclaimers.
29027 @end enumerate
29029 If the Modified Version includes new front-matter sections or
29030 appendices that qualify as Secondary Sections and contain no material
29031 copied from the Document, you may at your option designate some or all
29032 of these sections as invariant.  To do this, add their titles to the
29033 list of Invariant Sections in the Modified Version’s license notice.
29034 These titles must be distinct from any other section titles.
29036 You may add a section Entitled “Endorsements”, provided it contains
29037 nothing but endorsements of your Modified Version by various
29038 parties—for example, statements of peer review or that the text has
29039 been approved by an organization as the authoritative definition of a
29040 standard.
29042 You may add a passage of up to five words as a Front-Cover Text, and a
29043 passage of up to 25 words as a Back-Cover Text, to the end of the list
29044 of Cover Texts in the Modified Version.  Only one passage of
29045 Front-Cover Text and one of Back-Cover Text may be added by (or
29046 through arrangements made by) any one entity.  If the Document already
29047 includes a cover text for the same cover, previously added by you or
29048 by arrangement made by the same entity you are acting on behalf of,
29049 you may not add another; but you may replace the old one, on explicit
29050 permission from the previous publisher that added the old one.
29052 The author(s) and publisher(s) of the Document do not by this License
29053 give permission to use their names for publicity for or to assert or
29054 imply endorsement of any Modified Version.
29056 @strong{5. COMBINING DOCUMENTS}
29058 You may combine the Document with other documents released under this
29059 License, under the terms defined in section 4 above for modified
29060 versions, provided that you include in the combination all of the
29061 Invariant Sections of all of the original documents, unmodified, and
29062 list them all as Invariant Sections of your combined work in its
29063 license notice, and that you preserve all their Warranty Disclaimers.
29065 The combined work need only contain one copy of this License, and
29066 multiple identical Invariant Sections may be replaced with a single
29067 copy.  If there are multiple Invariant Sections with the same name but
29068 different contents, make the title of each such section unique by
29069 adding at the end of it, in parentheses, the name of the original
29070 author or publisher of that section if known, or else a unique number.
29071 Make the same adjustment to the section titles in the list of
29072 Invariant Sections in the license notice of the combined work.
29074 In the combination, you must combine any sections Entitled “History”
29075 in the various original documents, forming one section Entitled
29076 “History”; likewise combine any sections Entitled “Acknowledgements”,
29077 and any sections Entitled “Dedications”.  You must delete all sections
29078 Entitled “Endorsements”.
29080 @strong{6. COLLECTIONS OF DOCUMENTS}
29082 You may make a collection consisting of the Document and other documents
29083 released under this License, and replace the individual copies of this
29084 License in the various documents with a single copy that is included in
29085 the collection, provided that you follow the rules of this License for
29086 verbatim copying of each of the documents in all other respects.
29088 You may extract a single document from such a collection, and distribute
29089 it individually under this License, provided you insert a copy of this
29090 License into the extracted document, and follow this License in all
29091 other respects regarding verbatim copying of that document.
29093 @strong{7. AGGREGATION WITH INDEPENDENT WORKS}
29095 A compilation of the Document or its derivatives with other separate
29096 and independent documents or works, in or on a volume of a storage or
29097 distribution medium, is called an “aggregate” if the copyright
29098 resulting from the compilation is not used to limit the legal rights
29099 of the compilation’s users beyond what the individual works permit.
29100 When the Document is included in an aggregate, this License does not
29101 apply to the other works in the aggregate which are not themselves
29102 derivative works of the Document.
29104 If the Cover Text requirement of section 3 is applicable to these
29105 copies of the Document, then if the Document is less than one half of
29106 the entire aggregate, the Document’s Cover Texts may be placed on
29107 covers that bracket the Document within the aggregate, or the
29108 electronic equivalent of covers if the Document is in electronic form.
29109 Otherwise they must appear on printed covers that bracket the whole
29110 aggregate.
29112 @strong{8. TRANSLATION}
29114 Translation is considered a kind of modification, so you may
29115 distribute translations of the Document under the terms of section 4.
29116 Replacing Invariant Sections with translations requires special
29117 permission from their copyright holders, but you may include
29118 translations of some or all Invariant Sections in addition to the
29119 original versions of these Invariant Sections.  You may include a
29120 translation of this License, and all the license notices in the
29121 Document, and any Warranty Disclaimers, provided that you also include
29122 the original English version of this License and the original versions
29123 of those notices and disclaimers.  In case of a disagreement between
29124 the translation and the original version of this License or a notice
29125 or disclaimer, the original version will prevail.
29127 If a section in the Document is Entitled “Acknowledgements”,
29128 “Dedications”, or “History”, the requirement (section 4) to Preserve
29129 its Title (section 1) will typically require changing the actual
29130 title.
29132 @strong{9. TERMINATION}
29134 You may not copy, modify, sublicense, or distribute the Document
29135 except as expressly provided under this License.  Any attempt
29136 otherwise to copy, modify, sublicense, or distribute it is void, and
29137 will automatically terminate your rights under this License.
29139 However, if you cease all violation of this License, then your license
29140 from a particular copyright holder is reinstated (a) provisionally,
29141 unless and until the copyright holder explicitly and finally
29142 terminates your license, and (b) permanently, if the copyright holder
29143 fails to notify you of the violation by some reasonable means prior to
29144 60 days after the cessation.
29146 Moreover, your license from a particular copyright holder is
29147 reinstated permanently if the copyright holder notifies you of the
29148 violation by some reasonable means, this is the first time you have
29149 received notice of violation of this License (for any work) from that
29150 copyright holder, and you cure the violation prior to 30 days after
29151 your receipt of the notice.
29153 Termination of your rights under this section does not terminate the
29154 licenses of parties who have received copies or rights from you under
29155 this License.  If your rights have been terminated and not permanently
29156 reinstated, receipt of a copy of some or all of the same material does
29157 not give you any rights to use it.
29159 @strong{10. FUTURE REVISIONS OF THIS LICENSE}
29161 The Free Software Foundation may publish new, revised versions
29162 of the GNU Free Documentation License from time to time.  Such new
29163 versions will be similar in spirit to the present version, but may
29164 differ in detail to address new problems or concerns.  See
29165 @indicateurl{https://www.gnu.org/copyleft/}.
29167 Each version of the License is given a distinguishing version number.
29168 If the Document specifies that a particular numbered version of this
29169 License “or any later version” applies to it, you have the option of
29170 following the terms and conditions either of that specified version or
29171 of any later version that has been published (not as a draft) by the
29172 Free Software Foundation.  If the Document does not specify a version
29173 number of this License, you may choose any version ever published (not
29174 as a draft) by the Free Software Foundation.  If the Document
29175 specifies that a proxy can decide which future versions of this
29176 License can be used, that proxy’s public statement of acceptance of a
29177 version permanently authorizes you to choose that version for the
29178 Document.
29180 @strong{11. RELICENSING}
29182 “Massive Multiauthor Collaboration Site” (or “MMC Site”) means any
29183 World Wide Web server that publishes copyrightable works and also
29184 provides prominent facilities for anybody to edit those works.  A
29185 public wiki that anybody can edit is an example of such a server.  A
29186 “Massive Multiauthor Collaboration” (or “MMC”) contained in the
29187 site means any set of copyrightable works thus published on the MMC
29188 site.
29190 “CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0
29191 license published by Creative Commons Corporation, a not-for-profit
29192 corporation with a principal place of business in San Francisco,
29193 California, as well as future copyleft versions of that license
29194 published by that same organization.
29196 “Incorporate” means to publish or republish a Document, in whole or
29197 in part, as part of another Document.
29199 An MMC is “eligible for relicensing” if it is licensed under this
29200 License, and if all works that were first published under this License
29201 somewhere other than this MMC, and subsequently incorporated in whole
29202 or in part into the MMC, (1) had no cover texts or invariant sections,
29203 and (2) were thus incorporated prior to November 1, 2008.
29205 The operator of an MMC Site may republish an MMC contained in the site
29206 under CC-BY-SA on the same site at any time before August 1, 2009,
29207 provided the MMC is eligible for relicensing.
29209 @strong{ADDENDUM: How to use this License for your documents}
29211 To use this License in a document you have written, include a copy of
29212 the License in the document and put the following copyright and
29213 license notices just after the title page:
29215 @quotation
29217 Copyright © YEAR  YOUR NAME.
29218 Permission is granted to copy, distribute and/or modify this document
29219 under the terms of the GNU Free Documentation License, Version 1.3
29220 or any later version published by the Free Software Foundation;
29221 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
29222 A copy of the license is included in the section entitled “GNU
29223 Free Documentation License”.
29224 @end quotation
29226 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
29227 replace the “with … Texts.” line with this:
29229 @quotation
29231 with the Invariant Sections being LIST THEIR TITLES, with the
29232 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
29233 @end quotation
29235 If you have Invariant Sections without Cover Texts, or some other
29236 combination of the three, merge those two alternatives to suit the
29237 situation.
29239 If your document contains nontrivial examples of program code, we
29240 recommend releasing these examples in parallel under your choice of
29241 free software license, such as the GNU General Public License,
29242 to permit their use in free software.
29244 @node Index,,GNU Free Documentation License,Top
29245 @unnumbered Index
29248 @printindex ge
29250 @anchor{gnat_ugn/gnat_utility_programs switches-related-to-project-files}@w{                              }
29251 @anchor{cf}@w{                              }
29253 @c %**end of body
29254 @bye