hppa: Fix LO_SUM DLTIND14R address support in PRINT_OPERAND_ADDRESS
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blobf64c091f849fb1b6ea588fc39dd0b39a21bfd842
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 5.3.0.@*
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 @c %**end of header
20 @copying
21 @quotation
22 GNAT User's Guide for Native Platforms , Dec 21, 2023
24 AdaCore
26 Copyright @copyright{} 2008-2024, Free Software Foundation
27 @end quotation
29 @end copying
31 @titlepage
32 @title GNAT User's Guide for Native Platforms
33 @insertcopying
34 @end titlepage
35 @contents
37 @c %** start of user preamble
39 @c %** end of user preamble
41 @ifnottex
42 @node Top
43 @top GNAT User's Guide for Native Platforms
44 @insertcopying
45 @end ifnottex
47 @c %**start of body
48 @anchor{gnat_ugn doc}@anchor{0}
49 `GNAT, The GNU Ada Development Environment'
52 @include gcc-common.texi
53 GCC version @value{version-GCC}@*
54 AdaCore
56 Permission is granted to copy, distribute and/or modify this document
57 under the terms of the GNU Free Documentation License, Version 1.3 or
58 any later version published by the Free Software Foundation; with no
59 Invariant Sections, with the Front-Cover Texts being
60 “GNAT User’s Guide for Native Platforms”,
61 and with no Back-Cover Texts.  A copy of the license is
62 included in the section entitled @ref{1,,GNU Free Documentation License}.
64 @menu
65 * About This Guide:: 
66 * Getting Started with GNAT:: 
67 * The GNAT Compilation Model:: 
68 * Building Executable Programs with GNAT:: 
69 * GNAT Utility Programs:: 
70 * GNAT and Program Execution:: 
71 * Platform-Specific Information:: 
72 * Example of Binder Output File:: 
73 * Elaboration Order Handling in GNAT:: 
74 * Inline Assembler:: 
75 * GNU Free Documentation License:: 
76 * Index:: 
78 @detailmenu
79  --- The Detailed Node Listing ---
81 About This Guide
83 * What This Guide Contains:: 
84 * What You Should Know before Reading This Guide:: 
85 * Related Information:: 
86 * Conventions:: 
88 Getting Started with GNAT
90 * System Requirements:: 
91 * Running GNAT:: 
92 * Running a Simple Ada Program:: 
93 * Running a Program with Multiple Units:: 
95 The GNAT Compilation Model
97 * Source Representation:: 
98 * Foreign Language Representation:: 
99 * File Naming Topics and Utilities:: 
100 * Configuration Pragmas:: 
101 * Generating Object Files:: 
102 * Source Dependencies:: 
103 * The Ada Library Information Files:: 
104 * Binding an Ada Program:: 
105 * GNAT and Libraries:: 
106 * Conditional Compilation:: 
107 * Mixed Language Programming:: 
108 * GNAT and Other Compilation Models:: 
109 * Using GNAT Files with External Tools:: 
111 Foreign Language Representation
113 * Latin-1:: 
114 * Other 8-Bit Codes:: 
115 * Wide_Character Encodings:: 
116 * Wide_Wide_Character Encodings:: 
118 File Naming Topics and Utilities
120 * File Naming Rules:: 
121 * Using Other File Names:: 
122 * Alternative File Naming Schemes:: 
123 * Handling Arbitrary File Naming Conventions with gnatname:: 
124 * File Name Krunching with gnatkr:: 
125 * Renaming Files with gnatchop:: 
127 Handling Arbitrary File Naming Conventions with gnatname
129 * Arbitrary File Naming Conventions:: 
130 * Running gnatname:: 
131 * Switches for gnatname:: 
132 * Examples of gnatname Usage:: 
134 File Name Krunching with gnatkr
136 * About gnatkr:: 
137 * Using gnatkr:: 
138 * Krunching Method:: 
139 * Examples of gnatkr Usage:: 
141 Renaming Files with gnatchop
143 * Handling Files with Multiple Units:: 
144 * Operating gnatchop in Compilation Mode:: 
145 * Command Line for gnatchop:: 
146 * Switches for gnatchop:: 
147 * Examples of gnatchop Usage:: 
149 Configuration Pragmas
151 * Handling of Configuration Pragmas:: 
152 * The Configuration Pragmas Files:: 
154 GNAT and Libraries
156 * Introduction to Libraries in GNAT:: 
157 * General Ada Libraries:: 
158 * Stand-alone Ada Libraries:: 
159 * Rebuilding the GNAT Run-Time Library:: 
161 General Ada Libraries
163 * Building a library:: 
164 * Installing a library:: 
165 * Using a library:: 
167 Stand-alone Ada Libraries
169 * Introduction to Stand-alone Libraries:: 
170 * Building a Stand-alone Library:: 
171 * Creating a Stand-alone Library to be used in a non-Ada context:: 
172 * Restrictions in Stand-alone Libraries:: 
174 Conditional Compilation
176 * Modeling Conditional Compilation in Ada:: 
177 * Preprocessing with gnatprep:: 
178 * Integrated Preprocessing:: 
180 Modeling Conditional Compilation in Ada
182 * Use of Boolean Constants:: 
183 * Debugging - A Special Case:: 
184 * Conditionalizing Declarations:: 
185 * Use of Alternative Implementations:: 
186 * Preprocessing:: 
188 Preprocessing with gnatprep
190 * Preprocessing Symbols:: 
191 * Using gnatprep:: 
192 * Switches for gnatprep:: 
193 * Form of Definitions File:: 
194 * Form of Input Text for gnatprep:: 
196 Mixed Language Programming
198 * Interfacing to C:: 
199 * Calling Conventions:: 
200 * Building Mixed Ada and C++ Programs:: 
201 * Partition-Wide Settings:: 
202 * Generating Ada Bindings for C and C++ headers:: 
203 * Generating C Headers for Ada Specifications:: 
205 Building Mixed Ada and C++ Programs
207 * Interfacing to C++:: 
208 * Linking a Mixed C++ & Ada Program:: 
209 * A Simple Example:: 
210 * Interfacing with C++ constructors:: 
211 * Interfacing with C++ at the Class Level:: 
213 Generating Ada Bindings for C and C++ headers
215 * Running the Binding Generator:: 
216 * Generating Bindings for C++ Headers:: 
217 * Switches:: 
219 Generating C Headers for Ada Specifications
221 * Running the C Header Generator:: 
223 GNAT and Other Compilation Models
225 * Comparison between GNAT and C/C++ Compilation Models:: 
226 * Comparison between GNAT and Conventional Ada Library Models:: 
228 Using GNAT Files with External Tools
230 * Using Other Utility Programs with GNAT:: 
231 * The External Symbol Naming Scheme of GNAT:: 
233 Building Executable Programs with GNAT
235 * Building with gnatmake:: 
236 * Compiling with gcc:: 
237 * Compiler Switches:: 
238 * Linker Switches:: 
239 * Binding with gnatbind:: 
240 * Linking with gnatlink:: 
241 * Using the GNU make Utility:: 
243 Building with gnatmake
245 * Running gnatmake:: 
246 * Switches for gnatmake:: 
247 * Mode Switches for gnatmake:: 
248 * Notes on the Command Line:: 
249 * How gnatmake Works:: 
250 * Examples of gnatmake Usage:: 
252 Compiling with gcc
254 * Compiling Programs:: 
255 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
256 * Order of Compilation Issues:: 
257 * Examples:: 
259 Compiler Switches
261 * Alphabetical List of All Switches:: 
262 * Output and Error Message Control:: 
263 * Warning Message Control:: 
264 * Debugging and Assertion Control:: 
265 * Validity Checking:: 
266 * Style Checking:: 
267 * Run-Time Checks:: 
268 * Using gcc for Syntax Checking:: 
269 * Using gcc for Semantic Checking:: 
270 * Compiling Different Versions of Ada:: 
271 * Character Set Control:: 
272 * File Naming Control:: 
273 * Subprogram Inlining Control:: 
274 * Auxiliary Output Control:: 
275 * Debugging Control:: 
276 * Exception Handling Control:: 
277 * Units to Sources Mapping Files:: 
278 * Code Generation Control:: 
280 Binding with gnatbind
282 * Running gnatbind:: 
283 * Switches for gnatbind:: 
284 * Command-Line Access:: 
285 * Search Paths for gnatbind:: 
286 * Examples of gnatbind Usage:: 
288 Switches for gnatbind
290 * Consistency-Checking Modes:: 
291 * Binder Error Message Control:: 
292 * Elaboration Control:: 
293 * Output Control:: 
294 * Dynamic Allocation Control:: 
295 * Binding with Non-Ada Main Programs:: 
296 * Binding Programs with No Main Subprogram:: 
298 Linking with gnatlink
300 * Running gnatlink:: 
301 * Switches for gnatlink:: 
303 Using the GNU make Utility
305 * Using gnatmake in a Makefile:: 
306 * Automatically Creating a List of Directories:: 
307 * Generating the Command Line Switches:: 
308 * Overcoming Command Line Length Limits:: 
310 GNAT Utility Programs
312 * The File Cleanup Utility gnatclean:: 
313 * The GNAT Library Browser gnatls:: 
315 The File Cleanup Utility gnatclean
317 * Running gnatclean:: 
318 * Switches for gnatclean:: 
320 The GNAT Library Browser gnatls
322 * Running gnatls:: 
323 * Switches for gnatls:: 
324 * Example of gnatls Usage:: 
326 GNAT and Program Execution
328 * Running and Debugging Ada Programs:: 
329 * Profiling:: 
330 * Improving Performance:: 
331 * Overflow Check Handling in GNAT:: 
332 * Performing Dimensionality Analysis in GNAT:: 
333 * Stack Related Facilities:: 
334 * Memory Management Issues:: 
336 Running and Debugging Ada Programs
338 * The GNAT Debugger GDB:: 
339 * Running GDB:: 
340 * Introduction to GDB Commands:: 
341 * Using Ada Expressions:: 
342 * Calling User-Defined Subprograms:: 
343 * Using the next Command in a Function:: 
344 * Stopping When Ada Exceptions Are Raised:: 
345 * Ada Tasks:: 
346 * Debugging Generic Units:: 
347 * Remote Debugging with gdbserver:: 
348 * GNAT Abnormal Termination or Failure to Terminate:: 
349 * Naming Conventions for GNAT Source Files:: 
350 * Getting Internal Debugging Information:: 
351 * Stack Traceback:: 
352 * Pretty-Printers for the GNAT runtime:: 
354 Stack Traceback
356 * Non-Symbolic Traceback:: 
357 * Symbolic Traceback:: 
359 Profiling
361 * Profiling an Ada Program with gprof:: 
363 Profiling an Ada Program with gprof
365 * Compilation for profiling:: 
366 * Program execution:: 
367 * Running gprof:: 
368 * Interpretation of profiling results:: 
370 Improving Performance
372 * Performance Considerations:: 
373 * Text_IO Suggestions:: 
374 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
376 Performance Considerations
378 * Controlling Run-Time Checks:: 
379 * Use of Restrictions:: 
380 * Optimization Levels:: 
381 * Debugging Optimized Code:: 
382 * Inlining of Subprograms:: 
383 * Floating Point Operations:: 
384 * Vectorization of loops:: 
385 * Other Optimization Switches:: 
386 * Optimization and Strict Aliasing:: 
387 * Aliased Variables and Optimization:: 
388 * Atomic Variables and Optimization:: 
389 * Passive Task Optimization:: 
391 Reducing Size of Executables with Unused Subprogram/Data Elimination
393 * About unused subprogram/data elimination:: 
394 * Compilation options:: 
395 * Example of unused subprogram/data elimination:: 
397 Overflow Check Handling in GNAT
399 * Background:: 
400 * Management of Overflows in GNAT:: 
401 * Specifying the Desired Mode:: 
402 * Default Settings:: 
403 * Implementation Notes:: 
405 Stack Related Facilities
407 * Stack Overflow Checking:: 
408 * Static Stack Usage Analysis:: 
409 * Dynamic Stack Usage Analysis:: 
411 Memory Management Issues
413 * Some Useful Memory Pools:: 
414 * The GNAT Debug Pool Facility:: 
416 Platform-Specific Information
418 * Run-Time Libraries:: 
419 * Specifying a Run-Time Library:: 
420 * GNU/Linux Topics:: 
421 * Microsoft Windows Topics:: 
422 * Mac OS Topics:: 
424 Run-Time Libraries
426 * Summary of Run-Time Configurations:: 
428 Specifying a Run-Time Library
430 * Choosing the Scheduling Policy:: 
432 GNU/Linux Topics
434 * Required Packages on GNU/Linux:: 
435 * Position Independent Executable (PIE) Enabled by Default on Linux: Position Independent Executable PIE Enabled by Default on 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 performance 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 `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 `greetings.ads'
944 spec of package @code{Greetings}
946 @item `greetings.adb'
948 body of package @code{Greetings}
950 @item `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 `spec') and the corresponding body in
1179 separate files. An Ada `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 `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 `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 `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 `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 `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 `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 `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 `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 `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 `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.
1366 @end table
1368 @geindex Upper-Half Coding
1371 @table @asis
1373 @item `Upper-Half Coding'
1375 The wide character with encoding @code{16#abcd#} where the upper bit is on
1376 (in other words, ‘a’ is in the range 8-F) is represented as two bytes,
1377 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1378 character, but is not required to be in the upper half. This method can
1379 be also used for shift-JIS or EUC, where the internal coding matches the
1380 external coding.
1381 @end table
1383 @geindex Shift JIS Coding
1386 @table @asis
1388 @item `Shift JIS Coding'
1390 A wide character is represented by a two-character sequence,
1391 @code{16#ab#} and
1392 @code{16#cd#}, with the restrictions described for upper-half encoding as
1393 described above. The internal character code is the corresponding JIS
1394 character according to the standard algorithm for Shift-JIS
1395 conversion. Only characters defined in the JIS code set table can be
1396 used with this encoding method.
1397 @end table
1399 @geindex EUC Coding
1402 @table @asis
1404 @item `EUC Coding'
1406 A wide character is represented by a two-character sequence
1407 @code{16#ab#} and
1408 @code{16#cd#}, with both characters being in the upper half. The internal
1409 character code is the corresponding JIS character according to the EUC
1410 encoding algorithm. Only characters defined in the JIS code set table
1411 can be used with this encoding method.
1413 @item `UTF-8 Coding'
1415 A wide character is represented using
1416 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1417 10646-1/Am.2. Depending on the character value, the representation
1418 is a one, two, or three byte sequence:
1420 @example
1421 16#0000#-16#007f#: 2#0xxxxxxx#
1422 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1423 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1424 @end example
1426 where the @code{xxx} bits correspond to the left-padded bits of the
1427 16-bit character value. Note that all lower half ASCII characters
1428 are represented as ASCII bytes and all upper half characters and
1429 other wide characters are represented as sequences of upper-half
1430 (The full UTF-8 scheme allows for encoding 31-bit characters as
1431 6-byte sequences, and in the following section on wide wide
1432 characters, the use of these sequences is documented).
1434 @item `Brackets Coding'
1436 In this encoding, a wide character is represented by the following eight
1437 character sequence:
1439 @example
1440 [ " a b c d " ]
1441 @end example
1443 where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1444 characters (using uppercase letters) of the wide character code. For
1445 example, [‘A345’] is used to represent the wide character with code
1446 @code{16#A345#}. It is also possible (though not required) to use the
1447 Brackets coding for upper half characters. For example, the code
1448 @code{16#A3#} can be represented as @code{['A3']}.
1450 This scheme is compatible with use of the full Wide_Character set,
1451 and is also the method used for wide character encoding in some standard
1452 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1453 @end table
1455 @cartouche
1456 @quotation Note 
1457 Some of these coding schemes do not permit the full use of the
1458 Ada character set. For example, neither Shift JIS nor EUC allow the
1459 use of the upper half of the Latin-1 set.
1460 @end quotation
1461 @end cartouche
1463 @node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1464 @anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{38}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{39}
1465 @subsection Wide_Wide_Character Encodings
1468 GNAT allows wide wide character codes to appear in character and string
1469 literals, and also optionally in identifiers, by means of the following
1470 possible encoding schemes:
1473 @table @asis
1475 @item `UTF-8 Coding'
1477 A wide character is represented using
1478 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1479 10646-1/Am.2. Depending on the character value, the representation
1480 of character codes with values greater than 16#FFFF# is a
1481 is a four, five, or six byte sequence:
1483 @example
1484 16#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
1485                              10xxxxxx
1486 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1487                              10xxxxxx 10xxxxxx
1488 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1489                              10xxxxxx 10xxxxxx 10xxxxxx
1490 @end example
1492 where the @code{xxx} bits correspond to the left-padded bits of the
1493 32-bit character value.
1495 @item `Brackets Coding'
1497 In this encoding, a wide wide character is represented by the following ten or
1498 twelve byte character sequence:
1500 @example
1501 [ " a b c d e f " ]
1502 [ " a b c d e f g h " ]
1503 @end example
1505 where @code{a-h} are the six or eight hexadecimal
1506 characters (using uppercase letters) of the wide wide character code. For
1507 example, [“1F4567”] is used to represent the wide wide character with code
1508 @code{16#001F_4567#}.
1510 This scheme is compatible with use of the full Wide_Wide_Character set,
1511 and is also the method used for wide wide character encoding in some standard
1512 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1513 @end table
1515 @node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1516 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{24}@anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{3a}
1517 @section File Naming Topics and Utilities
1520 GNAT has a default file naming scheme and also provides the user with
1521 a high degree of control over how the names and extensions of the
1522 source files correspond to the Ada compilation units that they contain.
1524 @menu
1525 * File Naming Rules:: 
1526 * Using Other File Names:: 
1527 * Alternative File Naming Schemes:: 
1528 * Handling Arbitrary File Naming Conventions with gnatname:: 
1529 * File Name Krunching with gnatkr:: 
1530 * Renaming Files with gnatchop:: 
1532 @end menu
1534 @node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1535 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{3b}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{3c}
1536 @subsection File Naming Rules
1539 The default file name is determined by the name of the unit that the
1540 file contains. The name is formed by taking the full expanded name of
1541 the unit and replacing the separating dots with hyphens and using
1542 lowercase for all letters.
1544 An exception arises if the file name generated by the above rules starts
1545 with one of the characters
1546 @code{a}, @code{g}, @code{i}, or @code{s}, and the second character is a
1547 minus. In this case, the character tilde is used in place
1548 of the minus. The reason for this special rule is to avoid clashes with
1549 the standard names for child units of the packages System, Ada,
1550 Interfaces, and GNAT, which use the prefixes
1551 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
1552 respectively.
1554 The file extension is @code{.ads} for a spec and
1555 @code{.adb} for a body. The following table shows some
1556 examples of these rules.
1558 @quotation
1561 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
1562 @item
1564 Source File
1566 @tab
1568 Ada Compilation Unit
1570 @item
1572 @code{main.ads}
1574 @tab
1576 Main (spec)
1578 @item
1580 @code{main.adb}
1582 @tab
1584 Main (body)
1586 @item
1588 @code{arith_functions.ads}
1590 @tab
1592 Arith_Functions (package spec)
1594 @item
1596 @code{arith_functions.adb}
1598 @tab
1600 Arith_Functions (package body)
1602 @item
1604 @code{func-spec.ads}
1606 @tab
1608 Func.Spec (child package spec)
1610 @item
1612 @code{func-spec.adb}
1614 @tab
1616 Func.Spec (child package body)
1618 @item
1620 @code{main-sub.adb}
1622 @tab
1624 Sub (subunit of Main)
1626 @item
1628 @code{a~bad.adb}
1630 @tab
1632 A.Bad (child package body)
1634 @end multitable
1636 @end quotation
1638 Following these rules can result in excessively long
1639 file names if corresponding
1640 unit names are long (for example, if child units or subunits are
1641 heavily nested). An option is available to shorten such long file names
1642 (called file name ‘krunching’). This may be particularly useful when
1643 programs being developed with GNAT are to be used on operating systems
1644 with limited file name lengths. @ref{3d,,Using gnatkr}.
1646 Of course, no file shortening algorithm can guarantee uniqueness over
1647 all possible unit names; if file name krunching is used, it is your
1648 responsibility to ensure no name clashes occur. Alternatively you
1649 can specify the exact file names that you want used, as described
1650 in the next section. Finally, if your Ada programs are migrating from a
1651 compiler with a different naming convention, you can use the gnatchop
1652 utility to produce source files that follow the GNAT naming conventions.
1653 (For details see @ref{1d,,Renaming Files with gnatchop}.)
1655 Note: in the case of Windows or Mac OS operating systems, case is not
1656 significant. So for example on Windows if the canonical name is
1657 @code{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1658 However, case is significant for other operating systems, so for example,
1659 if you want to use other than canonically cased file names on a Unix system,
1660 you need to follow the procedures described in the next section.
1662 @node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1663 @anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{3e}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{1c}
1664 @subsection Using Other File Names
1667 @geindex File names
1669 In the previous section, we have described the default rules used by
1670 GNAT to determine the file name in which a given unit resides. It is
1671 often convenient to follow these default rules, and if you follow them,
1672 the compiler knows without being explicitly told where to find all
1673 the files it needs.
1675 @geindex Source_File_Name pragma
1677 However, in some cases, particularly when a program is imported from
1678 another Ada compiler environment, it may be more convenient for the
1679 programmer to specify which file names contain which units. GNAT allows
1680 arbitrary file names to be used by means of the Source_File_Name pragma.
1681 The form of this pragma is as shown in the following examples:
1683 @example
1684 pragma Source_File_Name (My_Utilities.Stacks,
1685   Spec_File_Name => "myutilst_a.ada");
1686 pragma Source_File_name (My_Utilities.Stacks,
1687   Body_File_Name => "myutilst.ada");
1688 @end example
1690 As shown in this example, the first argument for the pragma is the unit
1691 name (in this example a child unit). The second argument has the form
1692 of a named association. The identifier
1693 indicates whether the file name is for a spec or a body;
1694 the file name itself is given by a string literal.
1696 The source file name pragma is a configuration pragma, which means that
1697 normally it will be placed in the @code{gnat.adc}
1698 file used to hold configuration
1699 pragmas that apply to a complete compilation environment.
1700 For more details on how the @code{gnat.adc} file is created and used
1701 see @ref{3f,,Handling of Configuration Pragmas}.
1703 @geindex gnat.adc
1705 GNAT allows completely arbitrary file names to be specified using the
1706 source file name pragma. However, if the file name specified has an
1707 extension other than @code{.ads} or @code{.adb} it is necessary to use
1708 a special syntax when compiling the file. The name in this case must be
1709 preceded by the special sequence @code{-x} followed by a space and the name
1710 of the language, here @code{ada}, as in:
1712 @example
1713 $ gcc -c -x ada peculiar_file_name.sim
1714 @end example
1716 @code{gnatmake} handles non-standard file names in the usual manner (the
1717 non-standard file name for the main program is simply used as the
1718 argument to gnatmake). Note that if the extension is also non-standard,
1719 then it must be included in the @code{gnatmake} command, it may not
1720 be omitted.
1722 @node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
1723 @anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{41}
1724 @subsection Alternative File Naming Schemes
1727 @geindex File naming schemes
1728 @geindex alternative
1730 @geindex File names
1732 The previous section described the use of the @code{Source_File_Name}
1733 pragma to allow arbitrary names to be assigned to individual source files.
1734 However, this approach requires one pragma for each file, and especially in
1735 large systems can result in very long @code{gnat.adc} files, and also create
1736 a maintenance problem.
1738 @geindex Source_File_Name pragma
1740 GNAT also provides a facility for specifying systematic file naming schemes
1741 other than the standard default naming scheme previously described. An
1742 alternative scheme for naming is specified by the use of
1743 @code{Source_File_Name} pragmas having the following format:
1745 @example
1746 pragma Source_File_Name (
1747    Spec_File_Name  => FILE_NAME_PATTERN
1748  [ , Casing          => CASING_SPEC]
1749  [ , Dot_Replacement => STRING_LITERAL ] );
1751 pragma Source_File_Name (
1752    Body_File_Name  => FILE_NAME_PATTERN
1753  [ , Casing          => CASING_SPEC ]
1754  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1756 pragma Source_File_Name (
1757    Subunit_File_Name  => FILE_NAME_PATTERN
1758  [ , Casing          => CASING_SPEC ]
1759  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1761 FILE_NAME_PATTERN ::= STRING_LITERAL
1762 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1763 @end example
1765 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1766 It contains a single asterisk character, and the unit name is substituted
1767 systematically for this asterisk. The optional parameter
1768 @code{Casing} indicates
1769 whether the unit name is to be all upper-case letters, all lower-case letters,
1770 or mixed-case. If no
1771 @code{Casing} parameter is used, then the default is all
1772 lower-case.
1774 The optional @code{Dot_Replacement} string is used to replace any periods
1775 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1776 argument is used then separating dots appear unchanged in the resulting
1777 file name.
1778 Although the above syntax indicates that the
1779 @code{Casing} argument must appear
1780 before the @code{Dot_Replacement} argument, but it
1781 is also permissible to write these arguments in the opposite order.
1783 As indicated, it is possible to specify different naming schemes for
1784 bodies, specs, and subunits. Quite often the rule for subunits is the
1785 same as the rule for bodies, in which case, there is no need to give
1786 a separate @code{Subunit_File_Name} rule, and in this case the
1787 @code{Body_File_name} rule is used for subunits as well.
1789 The separate rule for subunits can also be used to implement the rather
1790 unusual case of a compilation environment (e.g., a single directory) which
1791 contains a subunit and a child unit with the same unit name. Although
1792 both units cannot appear in the same partition, the Ada Reference Manual
1793 allows (but does not require) the possibility of the two units coexisting
1794 in the same environment.
1796 The file name translation works in the following steps:
1799 @itemize *
1801 @item 
1802 If there is a specific @code{Source_File_Name} pragma for the given unit,
1803 then this is always used, and any general pattern rules are ignored.
1805 @item 
1806 If there is a pattern type @code{Source_File_Name} pragma that applies to
1807 the unit, then the resulting file name will be used if the file exists. If
1808 more than one pattern matches, the latest one will be tried first, and the
1809 first attempt resulting in a reference to a file that exists will be used.
1811 @item 
1812 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1813 for which the corresponding file exists, then the standard GNAT default
1814 naming rules are used.
1815 @end itemize
1817 As an example of the use of this mechanism, consider a commonly used scheme
1818 in which file names are all lower case, with separating periods copied
1819 unchanged to the resulting file name, and specs end with @code{.1.ada}, and
1820 bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
1821 two pragmas appear:
1823 @example
1824 pragma Source_File_Name
1825   (Spec_File_Name => ".1.ada");
1826 pragma Source_File_Name
1827   (Body_File_Name => ".2.ada");
1828 @end example
1830 The default GNAT scheme is actually implemented by providing the following
1831 default pragmas internally:
1833 @example
1834 pragma Source_File_Name
1835   (Spec_File_Name => ".ads", Dot_Replacement => "-");
1836 pragma Source_File_Name
1837   (Body_File_Name => ".adb", Dot_Replacement => "-");
1838 @end example
1840 Our final example implements a scheme typically used with one of the
1841 Ada 83 compilers, where the separator character for subunits was ‘__’
1842 (two underscores), specs were identified by adding @code{_.ADA}, bodies
1843 by adding @code{.ADA}, and subunits by
1844 adding @code{.SEP}. All file names were
1845 upper case. Child units were not present of course since this was an
1846 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1847 the same double underscore separator for child units.
1849 @example
1850 pragma Source_File_Name
1851   (Spec_File_Name => "_.ADA",
1852    Dot_Replacement => "__",
1853    Casing = Uppercase);
1854 pragma Source_File_Name
1855   (Body_File_Name => ".ADA",
1856    Dot_Replacement => "__",
1857    Casing = Uppercase);
1858 pragma Source_File_Name
1859   (Subunit_File_Name => ".SEP",
1860    Dot_Replacement => "__",
1861    Casing = Uppercase);
1862 @end example
1864 @geindex gnatname
1866 @node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
1867 @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}
1868 @subsection Handling Arbitrary File Naming Conventions with @code{gnatname}
1871 @geindex File Naming Conventions
1873 @menu
1874 * Arbitrary File Naming Conventions:: 
1875 * Running gnatname:: 
1876 * Switches for gnatname:: 
1877 * Examples of gnatname Usage:: 
1879 @end menu
1881 @node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
1882 @anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{44}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{45}
1883 @subsubsection Arbitrary File Naming Conventions
1886 The GNAT compiler must be able to know the source file name of a compilation
1887 unit.  When using the standard GNAT default file naming conventions
1888 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
1889 does not need additional information.
1891 When the source file names do not follow the standard GNAT default file naming
1892 conventions, the GNAT compiler must be given additional information through
1893 a configuration pragmas file (@ref{25,,Configuration Pragmas})
1894 or a project file.
1895 When the non-standard file naming conventions are well-defined,
1896 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
1897 (@ref{40,,Alternative File Naming Schemes}) may be sufficient. However,
1898 if the file naming conventions are irregular or arbitrary, a number
1899 of pragma @code{Source_File_Name} for individual compilation units
1900 must be defined.
1901 To help maintain the correspondence between compilation unit names and
1902 source file names within the compiler,
1903 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
1904 set of files.
1906 @node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
1907 @anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{46}@anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{47}
1908 @subsubsection Running @code{gnatname}
1911 The usual form of the @code{gnatname} command is:
1913 @example
1914 $ gnatname [ switches ]  naming_pattern  [ naming_patterns ]
1915     [--and [ switches ]  naming_pattern  [ naming_patterns ]]
1916 @end example
1918 All of the arguments are optional. If invoked without any argument,
1919 @code{gnatname} will display its usage.
1921 When used with at least one naming pattern, @code{gnatname} will attempt to
1922 find all the compilation units in files that follow at least one of the
1923 naming patterns. To find these compilation units,
1924 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
1925 regular files.
1927 One or several Naming Patterns may be given as arguments to @code{gnatname}.
1928 Each Naming Pattern is enclosed between double quotes (or single
1929 quotes on Windows).
1930 A Naming Pattern is a regular expression similar to the wildcard patterns
1931 used in file names by the Unix shells or the DOS prompt.
1933 @code{gnatname} may be called with several sections of directories/patterns.
1934 Sections are separated by the switch @code{--and}. In each section, there must be
1935 at least one pattern. If no directory is specified in a section, the current
1936 directory (or the project directory if @code{-P} is used) is implied.
1937 The options other that the directory switches and the patterns apply globally
1938 even if they are in different sections.
1940 Examples of Naming Patterns are:
1942 @example
1943 "*.[12].ada"
1944 "*.ad[sb]*"
1945 "body_*"    "spec_*"
1946 @end example
1948 For a more complete description of the syntax of Naming Patterns,
1949 see the second kind of regular expressions described in @code{g-regexp.ads}
1950 (the ‘Glob’ regular expressions).
1952 When invoked without the switch @code{-P}, @code{gnatname} will create a
1953 configuration pragmas file @code{gnat.adc} in the current working directory,
1954 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
1955 unit.
1957 @node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
1958 @anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{48}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{49}
1959 @subsubsection Switches for @code{gnatname}
1962 Switches for @code{gnatname} must precede any specified Naming Pattern.
1964 You may specify any of the following switches to @code{gnatname}:
1966 @geindex --version (gnatname)
1969 @table @asis
1971 @item @code{--version}
1973 Display Copyright and version, then exit disregarding all other options.
1974 @end table
1976 @geindex --help (gnatname)
1979 @table @asis
1981 @item @code{--help}
1983 If @code{--version} was not used, display usage, then exit disregarding
1984 all other options.
1986 @item @code{--subdirs=`dir'}
1988 Real object, library or exec directories are subdirectories <dir> of the
1989 specified ones.
1991 @item @code{--no-backup}
1993 Do not create a backup copy of an existing project file.
1995 @item @code{--and}
1997 Start another section of directories/patterns.
1998 @end table
2000 @geindex -c (gnatname)
2003 @table @asis
2005 @item @code{-c`filename'}
2007 Create a configuration pragmas file @code{filename} (instead of the default
2008 @code{gnat.adc}).
2009 There may be zero, one or more space between @code{-c} and
2010 @code{filename}.
2011 @code{filename} may include directory information. @code{filename} must be
2012 writable. There may be only one switch @code{-c}.
2013 When a switch @code{-c} is
2014 specified, no switch @code{-P} may be specified (see below).
2015 @end table
2017 @geindex -d (gnatname)
2020 @table @asis
2022 @item @code{-d`dir'}
2024 Look for source files in directory @code{dir}. There may be zero, one or more
2025 spaces between @code{-d} and @code{dir}.
2026 @code{dir} may end with @code{/**}, that is it may be of the form
2027 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
2028 subdirectories, recursively, have to be searched for sources.
2029 When a switch @code{-d}
2030 is specified, the current working directory will not be searched for source
2031 files, unless it is explicitly specified with a @code{-d}
2032 or @code{-D} switch.
2033 Several switches @code{-d} may be specified.
2034 If @code{dir} is a relative path, it is relative to the directory of
2035 the configuration pragmas file specified with switch
2036 @code{-c},
2037 or to the directory of the project file specified with switch
2038 @code{-P} or,
2039 if neither switch @code{-c}
2040 nor switch @code{-P} are specified, it is relative to the
2041 current working directory. The directory
2042 specified with switch @code{-d} must exist and be readable.
2043 @end table
2045 @geindex -D (gnatname)
2048 @table @asis
2050 @item @code{-D`filename'}
2052 Look for source files in all directories listed in text file @code{filename}.
2053 There may be zero, one or more spaces between @code{-D}
2054 and @code{filename}.
2055 @code{filename} must be an existing, readable text file.
2056 Each nonempty line in @code{filename} must be a directory.
2057 Specifying switch @code{-D} is equivalent to specifying as many
2058 switches @code{-d} as there are nonempty lines in
2059 @code{file}.
2061 @item @code{-eL}
2063 Follow symbolic links when processing project files.
2065 @geindex -f (gnatname)
2067 @item @code{-f`pattern'}
2069 Foreign patterns. Using this switch, it is possible to add sources of languages
2070 other than Ada to the list of sources of a project file.
2071 It is only useful if a -P switch is used.
2072 For example,
2074 @example
2075 gnatname -Pprj -f"*.c" "*.ada"
2076 @end example
2078 will look for Ada units in all files with the @code{.ada} extension,
2079 and will add to the list of file for project @code{prj.gpr} the C files
2080 with extension @code{.c}.
2082 @geindex -h (gnatname)
2084 @item @code{-h}
2086 Output usage (help) information. The output is written to @code{stdout}.
2088 @geindex -P (gnatname)
2090 @item @code{-P`proj'}
2092 Create or update project file @code{proj}. There may be zero, one or more space
2093 between @code{-P} and @code{proj}. @code{proj} may include directory
2094 information. @code{proj} must be writable.
2095 There may be only one switch @code{-P}.
2096 When a switch @code{-P} is specified,
2097 no switch @code{-c} may be specified.
2098 On all platforms, except on VMS, when @code{gnatname} is invoked for an
2099 existing project file <proj>.gpr, a backup copy of the project file is created
2100 in the project directory with file name <proj>.gpr.saved_x. ‘x’ is the first
2101 non negative number that makes this backup copy a new file.
2103 @geindex -v (gnatname)
2105 @item @code{-v}
2107 Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2108 This includes name of the file written, the name of the directories to search
2109 and, for each file in those directories whose name matches at least one of
2110 the Naming Patterns, an indication of whether the file contains a unit,
2111 and if so the name of the unit.
2112 @end table
2114 @geindex -v -v (gnatname)
2117 @table @asis
2119 @item @code{-v -v}
2121 Very Verbose mode. In addition to the output produced in verbose mode,
2122 for each file in the searched directories whose name matches none of
2123 the Naming Patterns, an indication is given that there is no match.
2125 @geindex -x (gnatname)
2127 @item @code{-x`pattern'}
2129 Excluded patterns. Using this switch, it is possible to exclude some files
2130 that would match the name patterns. For example,
2132 @example
2133 gnatname -x "*_nt.ada" "*.ada"
2134 @end example
2136 will look for Ada units in all files with the @code{.ada} extension,
2137 except those whose names end with @code{_nt.ada}.
2138 @end table
2140 @node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2141 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{4a}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{4b}
2142 @subsubsection Examples of @code{gnatname} Usage
2145 @example
2146 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2147 @end example
2149 In this example, the directory @code{/home/me} must already exist
2150 and be writable. In addition, the directory
2151 @code{/home/me/sources} (specified by
2152 @code{-d sources}) must exist and be readable.
2154 Note the optional spaces after @code{-c} and @code{-d}.
2156 @example
2157 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
2158 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2159 @end example
2161 Note that several switches @code{-d} may be used,
2162 even in conjunction with one or several switches
2163 @code{-D}. Several Naming Patterns and one excluded pattern
2164 are used in this example.
2166 @node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2167 @anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{4c}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{4d}
2168 @subsection File Name Krunching with @code{gnatkr}
2171 @geindex gnatkr
2173 This section discusses the method used by the compiler to shorten
2174 the default file names chosen for Ada units so that they do not
2175 exceed the maximum length permitted. It also describes the
2176 @code{gnatkr} utility that can be used to determine the result of
2177 applying this shortening.
2179 @menu
2180 * About gnatkr:: 
2181 * Using gnatkr:: 
2182 * Krunching Method:: 
2183 * Examples of gnatkr Usage:: 
2185 @end menu
2187 @node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2188 @anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{4e}@anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{4f}
2189 @subsubsection About @code{gnatkr}
2192 The default file naming rule in GNAT
2193 is that the file name must be derived from
2194 the unit name. The exact default rule is as follows:
2197 @itemize *
2199 @item 
2200 Take the unit name and replace all dots by hyphens.
2202 @item 
2203 If such a replacement occurs in the
2204 second character position of a name, and the first character is
2205 @code{a}, @code{g}, @code{s}, or @code{i},
2206 then replace the dot by the character
2207 @code{~} (tilde)
2208 instead of a minus.
2210 The reason for this exception is to avoid clashes
2211 with the standard names for children of System, Ada, Interfaces,
2212 and GNAT, which use the prefixes
2213 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
2214 respectively.
2215 @end itemize
2217 The @code{-gnatk`nn'}
2218 switch of the compiler activates a ‘krunching’
2219 circuit that limits file names to nn characters (where nn is a decimal
2220 integer).
2222 The @code{gnatkr} utility can be used to determine the krunched name for
2223 a given file, when krunched to a specified maximum length.
2225 @node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2226 @anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{50}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{3d}
2227 @subsubsection Using @code{gnatkr}
2230 The @code{gnatkr} command has the form:
2232 @example
2233 $ gnatkr name [ length ]
2234 @end example
2236 @code{name} is the uncrunched file name, derived from the name of the unit
2237 in the standard manner described in the previous section (i.e., in particular
2238 all dots are replaced by hyphens). The file name may or may not have an
2239 extension (defined as a suffix of the form period followed by arbitrary
2240 characters other than period). If an extension is present then it will
2241 be preserved in the output. For example, when krunching @code{hellofile.ads}
2242 to eight characters, the result will be hellofil.ads.
2244 Note: for compatibility with previous versions of @code{gnatkr} dots may
2245 appear in the name instead of hyphens, but the last dot will always be
2246 taken as the start of an extension. So if @code{gnatkr} is given an argument
2247 such as @code{Hello.World.adb} it will be treated exactly as if the first
2248 period had been a hyphen, and for example krunching to eight characters
2249 gives the result @code{hellworl.adb}.
2251 Note that the result is always all lower case.
2252 Characters of the other case are folded as required.
2254 @code{length} represents the length of the krunched name. The default
2255 when no argument is given is 8 characters. A length of zero stands for
2256 unlimited, in other words do not chop except for system files where the
2257 implied crunching length is always eight characters.
2259 The output is the krunched name. The output has an extension only if the
2260 original argument was a file name with an extension.
2262 @node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2263 @anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{52}
2264 @subsubsection Krunching Method
2267 The initial file name is determined by the name of the unit that the file
2268 contains. The name is formed by taking the full expanded name of the
2269 unit and replacing the separating dots with hyphens and
2270 using lowercase
2271 for all letters, except that a hyphen in the second character position is
2272 replaced by a tilde if the first character is
2273 @code{a}, @code{i}, @code{g}, or @code{s}.
2274 The extension is @code{.ads} for a
2275 spec and @code{.adb} for a body.
2276 Krunching does not affect the extension, but the file name is shortened to
2277 the specified length by following these rules:
2280 @itemize *
2282 @item 
2283 The name is divided into segments separated by hyphens, tildes or
2284 underscores and all hyphens, tildes, and underscores are
2285 eliminated. If this leaves the name short enough, we are done.
2287 @item 
2288 If the name is too long, the longest segment is located (left-most
2289 if there are two of equal length), and shortened by dropping
2290 its last character. This is repeated until the name is short enough.
2292 As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2293 to fit the name into 8 characters as required by some operating systems:
2295 @example
2296 our-strings-wide_fixed 22
2297 our strings wide fixed 19
2298 our string  wide fixed 18
2299 our strin   wide fixed 17
2300 our stri    wide fixed 16
2301 our stri    wide fixe  15
2302 our str     wide fixe  14
2303 our str     wid  fixe  13
2304 our str     wid  fix   12
2305 ou  str     wid  fix   11
2306 ou  st      wid  fix   10
2307 ou  st      wi   fix   9
2308 ou  st      wi   fi    8
2309 Final file name: oustwifi.adb
2310 @end example
2312 @item 
2313 The file names for all predefined units are always krunched to eight
2314 characters. The krunching of these predefined units uses the following
2315 special prefix replacements:
2318 @multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
2319 @item
2321 Prefix
2323 @tab
2325 Replacement
2327 @item
2329 @code{ada-}
2331 @tab
2333 @code{a-}
2335 @item
2337 @code{gnat-}
2339 @tab
2341 @code{g-}
2343 @item
2345 @code{interfac es-}
2347 @tab
2349 @code{i-}
2351 @item
2353 @code{system-}
2355 @tab
2357 @code{s-}
2359 @end multitable
2362 These system files have a hyphen in the second character position. That
2363 is why normal user files replace such a character with a
2364 tilde, to avoid confusion with system file names.
2366 As an example of this special rule, consider
2367 @code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2369 @example
2370 ada-strings-wide_fixed 22
2371 a-  strings wide fixed 18
2372 a-  string  wide fixed 17
2373 a-  strin   wide fixed 16
2374 a-  stri    wide fixed 15
2375 a-  stri    wide fixe  14
2376 a-  str     wide fixe  13
2377 a-  str     wid  fixe  12
2378 a-  str     wid  fix   11
2379 a-  st      wid  fix   10
2380 a-  st      wi   fix   9
2381 a-  st      wi   fi    8
2382 Final file name: a-stwifi.adb
2383 @end example
2384 @end itemize
2386 Of course no file shortening algorithm can guarantee uniqueness over all
2387 possible unit names, and if file name krunching is used then it is your
2388 responsibility to ensure that no name clashes occur. The utility
2389 program @code{gnatkr} is supplied for conveniently determining the
2390 krunched name of a file.
2392 @node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2393 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{53}@anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{54}
2394 @subsubsection Examples of @code{gnatkr} Usage
2397 @example
2398 $ gnatkr very_long_unit_name.ads      --> velounna.ads
2399 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
2400 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2401 $ gnatkr grandparent-parent-child     --> grparchi
2402 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2403 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2404 @end example
2406 @node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2407 @anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{55}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{1d}
2408 @subsection Renaming Files with @code{gnatchop}
2411 @geindex gnatchop
2413 This section discusses how to handle files with multiple units by using
2414 the @code{gnatchop} utility. This utility is also useful in renaming
2415 files to meet the standard GNAT default file naming conventions.
2417 @menu
2418 * Handling Files with Multiple Units:: 
2419 * Operating gnatchop in Compilation Mode:: 
2420 * Command Line for gnatchop:: 
2421 * Switches for gnatchop:: 
2422 * Examples of gnatchop Usage:: 
2424 @end menu
2426 @node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2427 @anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{56}@anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{57}
2428 @subsubsection Handling Files with Multiple Units
2431 The basic compilation model of GNAT requires that a file submitted to the
2432 compiler have only one unit and there be a strict correspondence
2433 between the file name and the unit name.
2435 If you want to keep your files with multiple units,
2436 perhaps to maintain compatibility with some other Ada compilation system,
2437 you can use @code{gnatname} to generate or update your project files.
2438 Generated or modified project files can be processed by GNAT.
2440 See @ref{42,,Handling Arbitrary File Naming Conventions with gnatname}
2441 for more details on how to use @cite{gnatname}.
2443 Alternatively, if you want to permanently restructure a set of ‘foreign’
2444 files so that they match the GNAT rules, and do the remaining development
2445 using the GNAT structure, you can simply use @code{gnatchop} once, generate the
2446 new set of files and work with them from that point on.
2448 Note that if your file containing multiple units starts with a byte order
2449 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2450 will each start with a copy of this BOM, meaning that they can be compiled
2451 automatically in UTF-8 mode without needing to specify an explicit encoding.
2453 @node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2454 @anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{58}@anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{59}
2455 @subsubsection Operating gnatchop in Compilation Mode
2458 The basic function of @code{gnatchop} is to take a file with multiple units
2459 and split it into separate files. The boundary between files is reasonably
2460 clear, except for the issue of comments and pragmas. In default mode, the
2461 rule is that any pragmas between units belong to the previous unit, except
2462 that configuration pragmas always belong to the following unit. Any comments
2463 belong to the following unit. These rules
2464 almost always result in the right choice of
2465 the split point without needing to mark it explicitly and most users will
2466 find this default to be what they want. In this default mode it is incorrect to
2467 submit a file containing only configuration pragmas, or one that ends in
2468 configuration pragmas, to @code{gnatchop}.
2470 However, using a special option to activate ‘compilation mode’,
2471 @code{gnatchop}
2472 can perform another function, which is to provide exactly the semantics
2473 required by the RM for handling of configuration pragmas in a compilation.
2474 In the absence of configuration pragmas (at the main file level), this
2475 option has no effect, but it causes such configuration pragmas to be handled
2476 in a quite different manner.
2478 First, in compilation mode, if @code{gnatchop} is given a file that consists of
2479 only configuration pragmas, then this file is appended to the
2480 @code{gnat.adc} file in the current directory. This behavior provides
2481 the required behavior described in the RM for the actions to be taken
2482 on submitting such a file to the compiler, namely that these pragmas
2483 should apply to all subsequent compilations in the same compilation
2484 environment. Using GNAT, the current directory, possibly containing a
2485 @code{gnat.adc} file is the representation
2486 of a compilation environment. For more information on the
2487 @code{gnat.adc} file, see @ref{3f,,Handling of Configuration Pragmas}.
2489 Second, in compilation mode, if @code{gnatchop}
2490 is given a file that starts with
2491 configuration pragmas, and contains one or more units, then these
2492 configuration pragmas are prepended to each of the chopped files. This
2493 behavior provides the required behavior described in the RM for the
2494 actions to be taken on compiling such a file, namely that the pragmas
2495 apply to all units in the compilation, but not to subsequently compiled
2496 units.
2498 Finally, if configuration pragmas appear between units, they are appended
2499 to the previous unit. This results in the previous unit being illegal,
2500 since the compiler does not accept configuration pragmas that follow
2501 a unit. This provides the required RM behavior that forbids configuration
2502 pragmas other than those preceding the first compilation unit of a
2503 compilation.
2505 For most purposes, @code{gnatchop} will be used in default mode. The
2506 compilation mode described above is used only if you need exactly
2507 accurate behavior with respect to compilations, and you have files
2508 that contain multiple units and configuration pragmas. In this
2509 circumstance the use of @code{gnatchop} with the compilation mode
2510 switch provides the required behavior, and is for example the mode
2511 in which GNAT processes the ACVC tests.
2513 @node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2514 @anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{5a}@anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{5b}
2515 @subsubsection Command Line for @code{gnatchop}
2518 The @code{gnatchop} command has the form:
2520 @example
2521 $ gnatchop switches file_name [file_name ...]
2522       [directory]
2523 @end example
2525 The only required argument is the file name of the file to be chopped.
2526 There are no restrictions on the form of this file name. The file itself
2527 contains one or more Ada units, in normal GNAT format, concatenated
2528 together. As shown, more than one file may be presented to be chopped.
2530 When run in default mode, @code{gnatchop} generates one output file in
2531 the current directory for each unit in each of the files.
2533 @code{directory}, if specified, gives the name of the directory to which
2534 the output files will be written. If it is not specified, all files are
2535 written to the current directory.
2537 For example, given a
2538 file called @code{hellofiles} containing
2540 @example
2541 procedure Hello;
2543 with Ada.Text_IO; use Ada.Text_IO;
2544 procedure Hello is
2545 begin
2546    Put_Line ("Hello");
2547 end Hello;
2548 @end example
2550 the command
2552 @example
2553 $ gnatchop hellofiles
2554 @end example
2556 generates two files in the current directory, one called
2557 @code{hello.ads} containing the single line that is the procedure spec,
2558 and the other called @code{hello.adb} containing the remaining text. The
2559 original file is not affected. The generated files can be compiled in
2560 the normal manner.
2562 When gnatchop is invoked on a file that is empty or that contains only empty
2563 lines and/or comments, gnatchop will not fail, but will not produce any
2564 new sources.
2566 For example, given a
2567 file called @code{toto.txt} containing
2569 @example
2570 --  Just a comment
2571 @end example
2573 the command
2575 @example
2576 $ gnatchop toto.txt
2577 @end example
2579 will not produce any new file and will result in the following warnings:
2581 @example
2582 toto.txt:1:01: warning: empty file, contains no compilation units
2583 no compilation units found
2584 no source files written
2585 @end example
2587 @node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2588 @anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{5c}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{5d}
2589 @subsubsection Switches for @code{gnatchop}
2592 @code{gnatchop} recognizes the following switches:
2594 @geindex --version (gnatchop)
2597 @table @asis
2599 @item @code{--version}
2601 Display Copyright and version, then exit disregarding all other options.
2602 @end table
2604 @geindex --help (gnatchop)
2607 @table @asis
2609 @item @code{--help}
2611 If @code{--version} was not used, display usage, then exit disregarding
2612 all other options.
2613 @end table
2615 @geindex -c (gnatchop)
2618 @table @asis
2620 @item @code{-c}
2622 Causes @code{gnatchop} to operate in compilation mode, in which
2623 configuration pragmas are handled according to strict RM rules. See
2624 previous section for a full description of this mode.
2626 @item @code{-gnat`xxx'}
2628 This passes the given @code{-gnat`xxx'} switch to @code{gnat} which is
2629 used to parse the given file. Not all `xxx' options make sense,
2630 but for example, the use of @code{-gnati2} allows @code{gnatchop} to
2631 process a source file that uses Latin-2 coding for identifiers.
2633 @item @code{-h}
2635 Causes @code{gnatchop} to generate a brief help summary to the standard
2636 output file showing usage information.
2637 @end table
2639 @geindex -k (gnatchop)
2642 @table @asis
2644 @item @code{-k`mm'}
2646 Limit generated file names to the specified number @code{mm}
2647 of characters.
2648 This is useful if the
2649 resulting set of files is required to be interoperable with systems
2650 which limit the length of file names.
2651 No space is allowed between the @code{-k} and the numeric value. The numeric
2652 value may be omitted in which case a default of @code{-k8},
2653 suitable for use
2654 with DOS-like file systems, is used. If no @code{-k} switch
2655 is present then
2656 there is no limit on the length of file names.
2657 @end table
2659 @geindex -p (gnatchop)
2662 @table @asis
2664 @item @code{-p}
2666 Causes the file modification time stamp of the input file to be
2667 preserved and used for the time stamp of the output file(s). This may be
2668 useful for preserving coherency of time stamps in an environment where
2669 @code{gnatchop} is used as part of a standard build process.
2670 @end table
2672 @geindex -q (gnatchop)
2675 @table @asis
2677 @item @code{-q}
2679 Causes output of informational messages indicating the set of generated
2680 files to be suppressed. Warnings and error messages are unaffected.
2681 @end table
2683 @geindex -r (gnatchop)
2685 @geindex Source_Reference pragmas
2688 @table @asis
2690 @item @code{-r}
2692 Generate @code{Source_Reference} pragmas. Use this switch if the output
2693 files are regarded as temporary and development is to be done in terms
2694 of the original unchopped file. This switch causes
2695 @code{Source_Reference} pragmas to be inserted into each of the
2696 generated files to refers back to the original file name and line number.
2697 The result is that all error messages refer back to the original
2698 unchopped file.
2699 In addition, the debugging information placed into the object file (when
2700 the @code{-g} switch of @code{gcc} or @code{gnatmake} is
2701 specified)
2702 also refers back to this original file so that tools like profilers and
2703 debuggers will give information in terms of the original unchopped file.
2705 If the original file to be chopped itself contains
2706 a @code{Source_Reference}
2707 pragma referencing a third file, then gnatchop respects
2708 this pragma, and the generated @code{Source_Reference} pragmas
2709 in the chopped file refer to the original file, with appropriate
2710 line numbers. This is particularly useful when @code{gnatchop}
2711 is used in conjunction with @code{gnatprep} to compile files that
2712 contain preprocessing statements and multiple units.
2713 @end table
2715 @geindex -v (gnatchop)
2718 @table @asis
2720 @item @code{-v}
2722 Causes @code{gnatchop} to operate in verbose mode. The version
2723 number and copyright notice are output, as well as exact copies of
2724 the gnat1 commands spawned to obtain the chop control information.
2725 @end table
2727 @geindex -w (gnatchop)
2730 @table @asis
2732 @item @code{-w}
2734 Overwrite existing file names. Normally @code{gnatchop} regards it as a
2735 fatal error if there is already a file with the same name as a
2736 file it would otherwise output, in other words if the files to be
2737 chopped contain duplicated units. This switch bypasses this
2738 check, and causes all but the last instance of such duplicated
2739 units to be skipped.
2740 @end table
2742 @geindex --GCC= (gnatchop)
2745 @table @asis
2747 @item @code{--GCC=`xxxx'}
2749 Specify the path of the GNAT parser to be used. When this switch is used,
2750 no attempt is made to add the prefix to the GNAT parser executable.
2751 @end table
2753 @node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
2754 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{5e}@anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{5f}
2755 @subsubsection Examples of @code{gnatchop} Usage
2758 @example
2759 $ gnatchop -w hello_s.ada prerelease/files
2760 @end example
2762 Chops the source file @code{hello_s.ada}. The output files will be
2763 placed in the directory @code{prerelease/files},
2764 overwriting any
2765 files with matching names in that directory (no files in the current
2766 directory are modified).
2768 @example
2769 $ gnatchop archive
2770 @end example
2772 Chops the source file @code{archive}
2773 into the current directory. One
2774 useful application of @code{gnatchop} is in sending sets of sources
2775 around, for example in email messages. The required sources are simply
2776 concatenated (for example, using a Unix @code{cat}
2777 command), and then
2778 @code{gnatchop} is used at the other end to reconstitute the original
2779 file names.
2781 @example
2782 $ gnatchop file1 file2 file3 direc
2783 @end example
2785 Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
2786 the resulting files in the directory @code{direc}. Note that if any units
2787 occur more than once anywhere within this set of files, an error message
2788 is generated, and no files are written. To override this check, use the
2789 @code{-w} switch,
2790 in which case the last occurrence in the last file will
2791 be the one that is output, and earlier duplicate occurrences for a given
2792 unit will be skipped.
2794 @node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
2795 @anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{25}@anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{60}
2796 @section Configuration Pragmas
2799 @geindex Configuration pragmas
2801 @geindex Pragmas
2802 @geindex configuration
2804 Configuration pragmas include those pragmas described as
2805 such in the Ada Reference Manual, as well as
2806 implementation-dependent pragmas that are configuration pragmas.
2807 See the @code{Implementation_Defined_Pragmas} chapter in the
2808 @cite{GNAT_Reference_Manual} for details on these
2809 additional GNAT-specific configuration pragmas.
2810 Most notably, the pragma @code{Source_File_Name}, which allows
2811 specifying non-default names for source files, is a configuration
2812 pragma. The following is a complete list of configuration pragmas
2813 recognized by GNAT:
2815 @example
2816 Ada_83
2817 Ada_95
2818 Ada_05
2819 Ada_2005
2820 Ada_12
2821 Ada_2012
2822 Ada_2022
2823 Aggregate_Individually_Assign
2824 Allow_Integer_Address
2825 Annotate
2826 Assertion_Policy
2827 Assume_No_Invalid_Values
2828 C_Pass_By_Copy
2829 Check_Float_Overflow
2830 Check_Name
2831 Check_Policy
2832 Component_Alignment
2833 Convention_Identifier
2834 Debug_Policy
2835 Default_Scalar_Storage_Order
2836 Default_Storage_Pool
2837 Detect_Blocking
2838 Disable_Atomic_Synchronization
2839 Discard_Names
2840 Elaboration_Checks
2841 Eliminate
2842 Enable_Atomic_Synchronization
2843 Extend_System
2844 Extensions_Allowed
2845 External_Name_Casing
2846 Fast_Math
2847 Favor_Top_Level
2848 Ignore_Pragma
2849 Implicit_Packing
2850 Initialize_Scalars
2851 Interrupt_State
2852 License
2853 Locking_Policy
2854 No_Component_Reordering
2855 No_Heap_Finalization
2856 No_Strict_Aliasing
2857 Normalize_Scalars
2858 Optimize_Alignment
2859 Overflow_Mode
2860 Overriding_Renamings
2861 Partition_Elaboration_Policy
2862 Persistent_BSS
2863 Prefix_Exception_Messages
2864 Priority_Specific_Dispatching
2865 Profile
2866 Profile_Warnings
2867 Queuing_Policy
2868 Rename_Pragma
2869 Restrictions
2870 Restriction_Warnings
2871 Reviewable
2872 Short_Circuit_And_Or
2873 Source_File_Name
2874 Source_File_Name_Project
2875 SPARK_Mode
2876 Style_Checks
2877 Suppress
2878 Suppress_Exception_Locations
2879 Task_Dispatching_Policy
2880 Unevaluated_Use_Of_Old
2881 Unsuppress
2882 Use_VADS_Size
2883 User_Aspect_Definition
2884 Validity_Checks
2885 Warning_As_Error
2886 Warnings
2887 Wide_Character_Encoding
2888 @end example
2890 @menu
2891 * Handling of Configuration Pragmas:: 
2892 * The Configuration Pragmas Files:: 
2894 @end menu
2896 @node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
2897 @anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{3f}@anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{61}
2898 @subsection Handling of Configuration Pragmas
2901 Configuration pragmas may either appear at the start of a compilation
2902 unit, or they can appear in a configuration pragma file to apply to
2903 all compilations performed in a given compilation environment.
2905 GNAT also provides the @code{gnatchop} utility to provide an automatic
2906 way to handle configuration pragmas following the semantics for
2907 compilations (that is, files with multiple units), described in the RM.
2908 See @ref{59,,Operating gnatchop in Compilation Mode} for details.
2909 However, for most purposes, it will be more convenient to edit the
2910 @code{gnat.adc} file that contains configuration pragmas directly,
2911 as described in the following section.
2913 In the case of @code{Restrictions} pragmas appearing as configuration
2914 pragmas in individual compilation units, the exact handling depends on
2915 the type of restriction.
2917 Restrictions that require partition-wide consistency (like
2918 @code{No_Tasking}) are
2919 recognized wherever they appear
2920 and can be freely inherited, e.g. from a `with'ed unit to the `with'ing
2921 unit. This makes sense since the binder will in any case insist on seeing
2922 consistent use, so any unit not conforming to any restrictions that are
2923 anywhere in the partition will be rejected, and you might as well find
2924 that out at compile time rather than at bind time.
2926 For restrictions that do not require partition-wide consistency, e.g.
2927 SPARK or No_Implementation_Attributes, in general the restriction applies
2928 only to the unit in which the pragma appears, and not to any other units.
2930 The exception is No_Elaboration_Code which always applies to the entire
2931 object file from a compilation, i.e. to the body, spec, and all subunits.
2932 This restriction can be specified in a configuration pragma file, or it
2933 can be on the body and/or the spec (in either case it applies to all the
2934 relevant units). It can appear on a subunit only if it has previously
2935 appeared in the body of spec.
2937 @node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
2938 @anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{62}@anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{63}
2939 @subsection The Configuration Pragmas Files
2942 @geindex gnat.adc
2944 In GNAT a compilation environment is defined by the current
2945 directory at the time that a compile command is given. This current
2946 directory is searched for a file whose name is @code{gnat.adc}. If
2947 this file is present, it is expected to contain one or more
2948 configuration pragmas that will be applied to the current compilation.
2949 However, if the switch @code{-gnatA} is used, @code{gnat.adc} is not
2950 considered. When taken into account, @code{gnat.adc} is added to the
2951 dependencies, so that if @code{gnat.adc} is modified later, an invocation of
2952 @code{gnatmake} will recompile the source.
2954 Configuration pragmas may be entered into the @code{gnat.adc} file
2955 either by running @code{gnatchop} on a source file that consists only of
2956 configuration pragmas, or more conveniently by direct editing of the
2957 @code{gnat.adc} file, which is a standard format source file.
2959 Besides @code{gnat.adc}, additional files containing configuration
2960 pragmas may be applied to the current compilation using the switch
2961 @code{-gnatec=`path'} where @code{path} must designate an existing file that
2962 contains only configuration pragmas. These configuration pragmas are
2963 in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
2964 is present and switch @code{-gnatA} is not used).
2966 It is allowable to specify several switches @code{-gnatec=}, all of which
2967 will be taken into account.
2969 Files containing configuration pragmas specified with switches
2970 @code{-gnatec=} are added to the dependencies, unless they are
2971 temporary files. A file is considered temporary if its name ends in
2972 @code{.tmp} or @code{.TMP}. Certain tools follow this naming
2973 convention because they pass information to @code{gcc} via
2974 temporary files that are immediately deleted; it doesn’t make sense to
2975 depend on a file that no longer exists. Such tools include
2976 @code{gprbuild}, @code{gnatmake}, and @code{gnatcheck}.
2978 By default, configuration pragma files are stored by their absolute paths in
2979 ALI files. You can use the @code{-gnateb} switch in order to store them by
2980 their basename instead.
2982 If you are using project file, a separate mechanism is provided using
2983 project attributes.
2985 @c --Comment
2986 @c See :ref:`Specifying_Configuration_Pragmas` for more details.
2988 @node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
2989 @anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{26}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{64}
2990 @section Generating Object Files
2993 An Ada program consists of a set of source files, and the first step in
2994 compiling the program is to generate the corresponding object files.
2995 These are generated by compiling a subset of these source files.
2996 The files you need to compile are the following:
2999 @itemize *
3001 @item 
3002 If a package spec has no body, compile the package spec to produce the
3003 object file for the package.
3005 @item 
3006 If a package has both a spec and a body, compile the body to produce the
3007 object file for the package. The source file for the package spec need
3008 not be compiled in this case because there is only one object file, which
3009 contains the code for both the spec and body of the package.
3011 @item 
3012 For a subprogram, compile the subprogram body to produce the object file
3013 for the subprogram. The spec, if one is present, is as usual in a
3014 separate file, and need not be compiled.
3015 @end itemize
3017 @geindex Subunits
3020 @itemize *
3022 @item 
3023 In the case of subunits, only compile the parent unit. A single object
3024 file is generated for the entire subunit tree, which includes all the
3025 subunits.
3027 @item 
3028 Compile child units independently of their parent units
3029 (though, of course, the spec of all the ancestor unit must be present in order
3030 to compile a child unit).
3032 @geindex Generics
3034 @item 
3035 Compile generic units in the same manner as any other units. The object
3036 files in this case are small dummy files that contain at most the
3037 flag used for elaboration checking. This is because GNAT always handles generic
3038 instantiation by means of macro expansion. However, it is still necessary to
3039 compile generic units, for dependency checking and elaboration purposes.
3040 @end itemize
3042 The preceding rules describe the set of files that must be compiled to
3043 generate the object files for a program. Each object file has the same
3044 name as the corresponding source file, except that the extension is
3045 @code{.o} as usual.
3047 You may wish to compile other files for the purpose of checking their
3048 syntactic and semantic correctness. For example, in the case where a
3049 package has a separate spec and body, you would not normally compile the
3050 spec. However, it is convenient in practice to compile the spec to make
3051 sure it is error-free before compiling clients of this spec, because such
3052 compilations will fail if there is an error in the spec.
3054 GNAT provides an option for compiling such files purely for the
3055 purposes of checking correctness; such compilations are not required as
3056 part of the process of building a program. To compile a file in this
3057 checking mode, use the @code{-gnatc} switch.
3059 @node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3060 @anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{27}
3061 @section Source Dependencies
3064 A given object file clearly depends on the source file which is compiled
3065 to produce it. Here we are using “depends” in the sense of a typical
3066 @code{make} utility; in other words, an object file depends on a source
3067 file if changes to the source file require the object file to be
3068 recompiled.
3069 In addition to this basic dependency, a given object may depend on
3070 additional source files as follows:
3073 @itemize *
3075 @item 
3076 If a file being compiled `with's a unit @code{X}, the object file
3077 depends on the file containing the spec of unit @code{X}. This includes
3078 files that are `with'ed implicitly either because they are parents
3079 of `with'ed child units or they are run-time units required by the
3080 language constructs used in a particular unit.
3082 @item 
3083 If a file being compiled instantiates a library level generic unit, the
3084 object file depends on both the spec and body files for this generic
3085 unit.
3087 @item 
3088 If a file being compiled instantiates a generic unit defined within a
3089 package, the object file depends on the body file for the package as
3090 well as the spec file.
3091 @end itemize
3093 @geindex Inline
3095 @geindex -gnatn switch
3098 @itemize *
3100 @item 
3101 If a file being compiled contains a call to a subprogram for which
3102 pragma @code{Inline} applies and inlining is activated with the
3103 @code{-gnatn} switch, the object file depends on the file containing the
3104 body of this subprogram as well as on the file containing the spec. Note
3105 that for inlining to actually occur as a result of the use of this switch,
3106 it is necessary to compile in optimizing mode.
3108 @geindex -gnatN switch
3110 The use of @code{-gnatN} activates  inlining optimization
3111 that is performed by the front end of the compiler. This inlining does
3112 not require that the code generation be optimized. Like @code{-gnatn},
3113 the use of this switch generates additional dependencies.
3115 When using a gcc-based back end, then the use of
3116 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
3117 Historically front end inlining was more extensive than the gcc back end
3118 inlining, but that is no longer the case.
3120 @item 
3121 If an object file @code{O} depends on the proper body of a subunit through
3122 inlining or instantiation, it depends on the parent unit of the subunit.
3123 This means that any modification of the parent unit or one of its subunits
3124 affects the compilation of @code{O}.
3126 @item 
3127 The object file for a parent unit depends on all its subunit body files.
3129 @item 
3130 The previous two rules meant that for purposes of computing dependencies and
3131 recompilation, a body and all its subunits are treated as an indivisible whole.
3133 These rules are applied transitively: if unit @code{A} `with's
3134 unit @code{B}, whose elaboration calls an inlined procedure in package
3135 @code{C}, the object file for unit @code{A} will depend on the body of
3136 @code{C}, in file @code{c.adb}.
3138 The set of dependent files described by these rules includes all the
3139 files on which the unit is semantically dependent, as dictated by the
3140 Ada language standard. However, it is a superset of what the
3141 standard describes, because it includes generic, inline, and subunit
3142 dependencies.
3144 An object file must be recreated by recompiling the corresponding source
3145 file if any of the source files on which it depends are modified. For
3146 example, if the @code{make} utility is used to control compilation,
3147 the rule for an Ada object file must mention all the source files on
3148 which the object file depends, according to the above definition.
3149 The determination of the necessary
3150 recompilations is done automatically when one uses @code{gnatmake}.
3151 @end itemize
3153 @node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3154 @anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{66}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{28}
3155 @section The Ada Library Information Files
3158 @geindex Ada Library Information files
3160 @geindex ALI files
3162 Each compilation actually generates two output files. The first of these
3163 is the normal object file that has a @code{.o} extension. The second is a
3164 text file containing full dependency information. It has the same
3165 name as the source file, but an @code{.ali} extension.
3166 This file is known as the Ada Library Information (@code{ALI}) file.
3167 The following information is contained in the @code{ALI} file.
3170 @itemize *
3172 @item 
3173 Version information (indicates which version of GNAT was used to compile
3174 the unit(s) in question)
3176 @item 
3177 Main program information (including priority and time slice settings,
3178 as well as the wide character encoding used during compilation).
3180 @item 
3181 List of arguments used in the @code{gcc} command for the compilation
3183 @item 
3184 Attributes of the unit, including configuration pragmas used, an indication
3185 of whether the compilation was successful, exception model used etc.
3187 @item 
3188 A list of relevant restrictions applying to the unit (used for consistency)
3189 checking.
3191 @item 
3192 Categorization information (e.g., use of pragma @code{Pure}).
3194 @item 
3195 Information on all `with'ed units, including presence of
3196 @code{Elaborate} or @code{Elaborate_All} pragmas.
3198 @item 
3199 Information from any @code{Linker_Options} pragmas used in the unit
3201 @item 
3202 Information on the use of @code{Body_Version} or @code{Version}
3203 attributes in the unit.
3205 @item 
3206 Dependency information. This is a list of files, together with
3207 time stamp and checksum information. These are files on which
3208 the unit depends in the sense that recompilation is required
3209 if any of these units are modified.
3211 @item 
3212 Cross-reference data. Contains information on all entities referenced
3213 in the unit. Used by some tools to provide cross-reference information.
3214 @end itemize
3216 For a full detailed description of the format of the @code{ALI} file,
3217 see the source of the body of unit @code{Lib.Writ}, contained in file
3218 @code{lib-writ.adb} in the GNAT compiler sources.
3220 @node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3221 @anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{29}@anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{67}
3222 @section Binding an Ada Program
3225 When using languages such as C and C++, once the source files have been
3226 compiled the only remaining step in building an executable program
3227 is linking the object modules together. This means that it is possible to
3228 link an inconsistent version of a program, in which two units have
3229 included different versions of the same header.
3231 The rules of Ada do not permit such an inconsistent program to be built.
3232 For example, if two clients have different versions of the same package,
3233 it is illegal to build a program containing these two clients.
3234 These rules are enforced by the GNAT binder, which also determines an
3235 elaboration order consistent with the Ada rules.
3237 The GNAT binder is run after all the object files for a program have
3238 been created. It is given the name of the main program unit, and from
3239 this it determines the set of units required by the program, by reading the
3240 corresponding ALI files. It generates error messages if the program is
3241 inconsistent or if no valid order of elaboration exists.
3243 If no errors are detected, the binder produces a main program, in Ada by
3244 default, that contains calls to the elaboration procedures of those
3245 compilation unit that require them, followed by
3246 a call to the main program. This Ada program is compiled to generate the
3247 object file for the main program. The name of
3248 the Ada file is @code{b~xxx.adb} (with the corresponding spec
3249 @code{b~xxx.ads}) where @code{xxx} is the name of the
3250 main program unit.
3252 Finally, the linker is used to build the resulting executable program,
3253 using the object from the main program from the bind step as well as the
3254 object files for the Ada units of the program.
3256 @node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3257 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{2a}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{68}
3258 @section GNAT and Libraries
3261 @geindex Library building and using
3263 This section describes how to build and use libraries with GNAT, and also shows
3264 how to recompile the GNAT run-time library. You should be familiar with the
3265 Project Manager facility (see the `GNAT_Project_Manager' chapter of the
3266 `GPRbuild User’s Guide') before reading this chapter.
3268 @menu
3269 * Introduction to Libraries in GNAT:: 
3270 * General Ada Libraries:: 
3271 * Stand-alone Ada Libraries:: 
3272 * Rebuilding the GNAT Run-Time Library:: 
3274 @end menu
3276 @node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3277 @anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{69}@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{6a}
3278 @subsection Introduction to Libraries in GNAT
3281 A library is, conceptually, a collection of objects which does not have its
3282 own main thread of execution, but rather provides certain services to the
3283 applications that use it. A library can be either statically linked with the
3284 application, in which case its code is directly included in the application,
3285 or, on platforms that support it, be dynamically linked, in which case
3286 its code is shared by all applications making use of this library.
3288 GNAT supports both types of libraries.
3289 In the static case, the compiled code can be provided in different ways. The
3290 simplest approach is to provide directly the set of objects resulting from
3291 compilation of the library source files. Alternatively, you can group the
3292 objects into an archive using whatever commands are provided by the operating
3293 system. For the latter case, the objects are grouped into a shared library.
3295 In the GNAT environment, a library has three types of components:
3298 @itemize *
3300 @item 
3301 Source files,
3303 @item 
3304 @code{ALI} files (see @ref{28,,The Ada Library Information Files}), and
3306 @item 
3307 Object files, an archive or a shared library.
3308 @end itemize
3310 A GNAT library may expose all its source files, which is useful for
3311 documentation purposes. Alternatively, it may expose only the units needed by
3312 an external user to make use of the library. That is to say, the specs
3313 reflecting the library services along with all the units needed to compile
3314 those specs, which can include generic bodies or any body implementing an
3315 inlined routine. In the case of `stand-alone libraries' those exposed
3316 units are called `interface units' (@ref{6b,,Stand-alone Ada Libraries}).
3318 All compilation units comprising an application, including those in a library,
3319 need to be elaborated in an order partially defined by Ada’s semantics. GNAT
3320 computes the elaboration order from the @code{ALI} files and this is why they
3321 constitute a mandatory part of GNAT libraries.
3322 `Stand-alone libraries' are the exception to this rule because a specific
3323 library elaboration routine is produced independently of the application(s)
3324 using the library.
3326 @node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3327 @anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{6d}
3328 @subsection General Ada Libraries
3331 @menu
3332 * Building a library:: 
3333 * Installing a library:: 
3334 * Using a library:: 
3336 @end menu
3338 @node Building a library,Installing a library,,General Ada Libraries
3339 @anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{6e}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{6f}
3340 @subsubsection Building a library
3343 The easiest way to build a library is to use the Project Manager,
3344 which supports a special type of project called a `Library Project'
3345 (see the `Library Projects' section in the `GNAT Project Manager'
3346 chapter of the `GPRbuild User’s Guide').
3348 A project is considered a library project, when two project-level attributes
3349 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
3350 control different aspects of library configuration, additional optional
3351 project-level attributes can be specified:
3354 @itemize *
3356 @item 
3358 @table @asis
3360 @item @code{Library_Kind}
3362 This attribute controls whether the library is to be static or dynamic
3363 @end table
3365 @item 
3367 @table @asis
3369 @item @code{Library_Version}
3371 This attribute specifies the library version; this value is used
3372 during dynamic linking of shared libraries to determine if the currently
3373 installed versions of the binaries are compatible.
3374 @end table
3376 @item 
3377 @code{Library_Options}
3379 @item 
3381 @table @asis
3383 @item @code{Library_GCC}
3385 These attributes specify additional low-level options to be used during
3386 library generation, and redefine the actual application used to generate
3387 library.
3388 @end table
3389 @end itemize
3391 The GNAT Project Manager takes full care of the library maintenance task,
3392 including recompilation of the source files for which objects do not exist
3393 or are not up to date, assembly of the library archive, and installation of
3394 the library (i.e., copying associated source, object and @code{ALI} files
3395 to the specified location).
3397 Here is a simple library project file:
3399 @example
3400 project My_Lib is
3401   for Source_Dirs use ("src1", "src2");
3402   for Object_Dir use "obj";
3403   for Library_Name use "mylib";
3404   for Library_Dir use "lib";
3405   for Library_Kind use "dynamic";
3406 end My_lib;
3407 @end example
3409 and the compilation command to build and install the library:
3411 @example
3412 $ gnatmake -Pmy_lib
3413 @end example
3415 It is not entirely trivial to perform manually all the steps required to
3416 produce a library. We recommend that you use the GNAT Project Manager
3417 for this task. In special cases where this is not desired, the necessary
3418 steps are discussed below.
3420 There are various possibilities for compiling the units that make up the
3421 library: for example with a Makefile (@ref{70,,Using the GNU make Utility}) or
3422 with a conventional script. For simple libraries, it is also possible to create
3423 a dummy main program which depends upon all the packages that comprise the
3424 interface of the library. This dummy main program can then be given to
3425 @code{gnatmake}, which will ensure that all necessary objects are built.
3427 After this task is accomplished, you should follow the standard procedure
3428 of the underlying operating system to produce the static or shared library.
3430 Here is an example of such a dummy program:
3432 @example
3433 with My_Lib.Service1;
3434 with My_Lib.Service2;
3435 with My_Lib.Service3;
3436 procedure My_Lib_Dummy is
3437 begin
3438    null;
3439 end;
3440 @end example
3442 Here are the generic commands that will build an archive or a shared library.
3444 @example
3445 # compiling the library
3446 $ gnatmake -c my_lib_dummy.adb
3448 # we don't need the dummy object itself
3449 $ rm my_lib_dummy.o my_lib_dummy.ali
3451 # create an archive with the remaining objects
3452 $ ar rc libmy_lib.a *.o
3453 # some systems may require "ranlib" to be run as well
3455 # or create a shared library
3456 $ gcc -shared -o libmy_lib.so *.o
3457 # some systems may require the code to have been compiled with -fPIC
3459 # remove the object files that are now in the library
3460 $ rm *.o
3462 # Make the ALI files read-only so that gnatmake will not try to
3463 # regenerate the objects that are in the library
3464 $ chmod -w *.ali
3465 @end example
3467 Please note that the library must have a name of the form @code{lib`xxx'.a}
3468 or @code{lib`xxx'.so} (or @code{lib`xxx'.dll} on Windows) in order to
3469 be accessed by the directive @code{-l`xxx'} at link time.
3471 @node Installing a library,Using a library,Building a library,General Ada Libraries
3472 @anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{72}
3473 @subsubsection Installing a library
3476 @geindex ADA_PROJECT_PATH
3478 @geindex GPR_PROJECT_PATH
3480 If you use project files, library installation is part of the library build
3481 process (see the `Installing a Library with Project Files' section of the
3482 `GNAT Project Manager' chapter of the `GPRbuild User’s Guide').
3484 When project files are not an option, it is also possible, but not recommended,
3485 to install the library so that the sources needed to use the library are on the
3486 Ada source path and the ALI files & libraries be on the Ada Object path (see
3487 @ref{73,,Search Paths and the Run-Time Library (RTL)}). Alternatively, the system
3488 administrator can place general-purpose libraries in the default compiler
3489 paths, by specifying the libraries’ location in the configuration files
3490 @code{ada_source_path} and @code{ada_object_path}. These configuration files
3491 must be located in the GNAT installation tree at the same place as the gcc spec
3492 file. The location of the gcc spec file can be determined as follows:
3494 @example
3495 $ gcc -v
3496 @end example
3498 The configuration files mentioned above have a simple format: each line
3499 must contain one unique directory name.
3500 Those names are added to the corresponding path
3501 in their order of appearance in the file. The names can be either absolute
3502 or relative; in the latter case, they are relative to where theses files
3503 are located.
3505 The files @code{ada_source_path} and @code{ada_object_path} might not be
3506 present in a
3507 GNAT installation, in which case, GNAT will look for its run-time library in
3508 the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3509 objects and @code{ALI} files). When the files exist, the compiler does not
3510 look in @code{adainclude} and @code{adalib}, and thus the
3511 @code{ada_source_path} file
3512 must contain the location for the GNAT run-time sources (which can simply
3513 be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3514 contain the location for the GNAT run-time objects (which can simply
3515 be @code{adalib}).
3517 You can also specify a new default path to the run-time library at compilation
3518 time with the switch @code{--RTS=rts-path}. You can thus choose / change
3519 the run-time library you want your program to be compiled with. This switch is
3520 recognized by @code{gcc}, @code{gnatmake}, @code{gnatbind}, @code{gnatls}, and all
3521 project aware tools.
3523 It is possible to install a library before or after the standard GNAT
3524 library, by reordering the lines in the configuration files. In general, a
3525 library must be installed before the GNAT library if it redefines
3526 any part of it.
3528 @node Using a library,,Installing a library,General Ada Libraries
3529 @anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{74}@anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{75}
3530 @subsubsection Using a library
3533 Once again, the project facility greatly simplifies the use of
3534 libraries. In this context, using a library is just a matter of adding a
3535 `with' clause in the user project. For instance, to make use of the
3536 library @code{My_Lib} shown in examples in earlier sections, you can
3537 write:
3539 @example
3540 with "my_lib";
3541 project My_Proj is
3542   ...
3543 end My_Proj;
3544 @end example
3546 Even if you have a third-party, non-Ada library, you can still use GNAT’s
3547 Project Manager facility to provide a wrapper for it. For example, the
3548 following project, when `with'ed by your main project, will link with the
3549 third-party library @code{liba.a}:
3551 @example
3552 project Liba is
3553    for Externally_Built use "true";
3554    for Source_Files use ();
3555    for Library_Dir use "lib";
3556    for Library_Name use "a";
3557    for Library_Kind use "static";
3558 end Liba;
3559 @end example
3561 This is an alternative to the use of @code{pragma Linker_Options}. It is
3562 especially interesting in the context of systems with several interdependent
3563 static libraries where finding a proper linker order is not easy and best be
3564 left to the tools having visibility over project dependence information.
3566 In order to use an Ada library manually, you need to make sure that this
3567 library is on both your source and object path
3568 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}
3569 and @ref{76,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3570 in an archive or a shared library, you need to specify the desired
3571 library at link time.
3573 For example, you can use the library @code{mylib} installed in
3574 @code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3576 @example
3577 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3578   -largs -lmy_lib
3579 @end example
3581 This can be expressed more simply:
3583 @example
3584 $ gnatmake my_appl
3585 @end example
3587 when the following conditions are met:
3590 @itemize *
3592 @item 
3593 @code{/dir/my_lib_src} has been added by the user to the environment
3594 variable 
3595 @geindex ADA_INCLUDE_PATH
3596 @geindex environment variable; ADA_INCLUDE_PATH
3597 @code{ADA_INCLUDE_PATH}, or by the administrator to the file
3598 @code{ada_source_path}
3600 @item 
3601 @code{/dir/my_lib_obj} has been added by the user to the environment
3602 variable 
3603 @geindex ADA_OBJECTS_PATH
3604 @geindex environment variable; ADA_OBJECTS_PATH
3605 @code{ADA_OBJECTS_PATH}, or by the administrator to the file
3606 @code{ada_object_path}
3608 @item 
3609 a pragma @code{Linker_Options} has been added to one of the sources.
3610 For example:
3612 @example
3613 pragma Linker_Options ("-lmy_lib");
3614 @end example
3615 @end itemize
3617 Note that you may also load a library dynamically at
3618 run time given its filename, as illustrated in the GNAT @code{plugins} example
3619 in the directory @code{share/examples/gnat/plugins} within the GNAT
3620 install area.
3622 @node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3623 @anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{6b}
3624 @subsection Stand-alone Ada Libraries
3627 @geindex Stand-alone libraries
3629 @menu
3630 * Introduction to Stand-alone Libraries:: 
3631 * Building a Stand-alone Library:: 
3632 * Creating a Stand-alone Library to be used in a non-Ada context:: 
3633 * Restrictions in Stand-alone Libraries:: 
3635 @end menu
3637 @node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3638 @anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{78}@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{79}
3639 @subsubsection Introduction to Stand-alone Libraries
3642 A Stand-alone Library (abbreviated ‘SAL’) is a library that contains the
3643 necessary code to
3644 elaborate the Ada units that are included in the library. In contrast with
3645 an ordinary library, which consists of all sources, objects and @code{ALI}
3646 files of the
3647 library, a SAL may specify a restricted subset of compilation units
3648 to serve as a library interface. In this case, the fully
3649 self-sufficient set of files will normally consist of an objects
3650 archive, the sources of interface units’ specs, and the @code{ALI}
3651 files of interface units.
3652 If an interface spec contains a generic unit or an inlined subprogram,
3653 the body’s
3654 source must also be provided; if the units that must be provided in the source
3655 form depend on other units, the source and @code{ALI} files of those must
3656 also be provided.
3658 The main purpose of a SAL is to minimize the recompilation overhead of client
3659 applications when a new version of the library is installed. Specifically,
3660 if the interface sources have not changed, client applications do not need to
3661 be recompiled. If, furthermore, a SAL is provided in the shared form and its
3662 version, controlled by @code{Library_Version} attribute, is not changed,
3663 then the clients do not need to be relinked.
3665 SALs also allow the library providers to minimize the amount of library source
3666 text exposed to the clients.  Such ‘information hiding’ might be useful or
3667 necessary for various reasons.
3669 Stand-alone libraries are also well suited to be used in an executable whose
3670 main routine is not written in Ada.
3672 @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
3673 @anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{7a}@anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{7b}
3674 @subsubsection Building a Stand-alone Library
3677 GNAT’s Project facility provides a simple way of building and installing
3678 stand-alone libraries; see the `Stand-alone Library Projects' section
3679 in the `GNAT Project Manager' chapter of the `GPRbuild User’s Guide'.
3680 To be a Stand-alone Library Project, in addition to the two attributes
3681 that make a project a Library Project (@code{Library_Name} and
3682 @code{Library_Dir}; see the `Library Projects' section in the
3683 `GNAT Project Manager' chapter of the `GPRbuild User’s Guide'),
3684 the attribute @code{Library_Interface} must be defined.  For example:
3686 @example
3687 for Library_Dir use "lib_dir";
3688 for Library_Name use "dummy";
3689 for Library_Interface use ("int1", "int1.child");
3690 @end example
3692 Attribute @code{Library_Interface} has a non-empty string list value,
3693 each string in the list designating a unit contained in an immediate source
3694 of the project file.
3696 When a Stand-alone Library is built, first the binder is invoked to build
3697 a package whose name depends on the library name
3698 (@code{b~dummy.ads/b} in the example above).
3699 This binder-generated package includes initialization and
3700 finalization procedures whose
3701 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
3702 in the example
3703 above). The object corresponding to this package is included in the library.
3705 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
3706 calling of these procedures if a static SAL is built, or if a shared SAL
3707 is built
3708 with the project-level attribute @code{Library_Auto_Init} set to
3709 @code{"false"}.
3711 For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
3712 (those that are listed in attribute @code{Library_Interface}) are copied to
3713 the Library Directory. As a consequence, only the Interface Units may be
3714 imported from Ada units outside of the library. If other units are imported,
3715 the binding phase will fail.
3717 It is also possible to build an encapsulated library where not only
3718 the code to elaborate and finalize the library is embedded but also
3719 ensuring that the library is linked only against static
3720 libraries. So an encapsulated library only depends on system
3721 libraries, all other code, including the GNAT runtime, is embedded. To
3722 build an encapsulated library the attribute
3723 @code{Library_Standalone} must be set to @code{encapsulated}:
3725 @example
3726 for Library_Dir use "lib_dir";
3727 for Library_Name use "dummy";
3728 for Library_Kind use "dynamic";
3729 for Library_Interface use ("int1", "int1.child");
3730 for Library_Standalone use "encapsulated";
3731 @end example
3733 The default value for this attribute is @code{standard} in which case
3734 a stand-alone library is built.
3736 The attribute @code{Library_Src_Dir} may be specified for a
3737 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
3738 single string value. Its value must be the path (absolute or relative to the
3739 project directory) of an existing directory. This directory cannot be the
3740 object directory or one of the source directories, but it can be the same as
3741 the library directory. The sources of the Interface
3742 Units of the library that are needed by an Ada client of the library will be
3743 copied to the designated directory, called the Interface Copy directory.
3744 These sources include the specs of the Interface Units, but they may also
3745 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
3746 are used, or when there is a generic unit in the spec. Before the sources
3747 are copied to the Interface Copy directory, an attempt is made to delete all
3748 files in the Interface Copy directory.
3750 Building stand-alone libraries by hand is somewhat tedious, but for those
3751 occasions when it is necessary here are the steps that you need to perform:
3754 @itemize *
3756 @item 
3757 Compile all library sources.
3759 @item 
3760 Invoke the binder with the switch @code{-n} (No Ada main program),
3761 with all the @code{ALI} files of the interfaces, and
3762 with the switch @code{-L} to give specific names to the @code{init}
3763 and @code{final} procedures.  For example:
3765 @example
3766 $ gnatbind -n int1.ali int2.ali -Lsal1
3767 @end example
3769 @item 
3770 Compile the binder generated file:
3772 @example
3773 $ gcc -c b~int2.adb
3774 @end example
3776 @item 
3777 Link the dynamic library with all the necessary object files,
3778 indicating to the linker the names of the @code{init} (and possibly
3779 @code{final}) procedures for automatic initialization (and finalization).
3780 The built library should be placed in a directory different from
3781 the object directory.
3783 @item 
3784 Copy the @code{ALI} files of the interface to the library directory,
3785 add in this copy an indication that it is an interface to a SAL
3786 (i.e., add a word @code{SL} on the line in the @code{ALI} file that starts
3787 with letter ‘P’) and make the modified copy of the @code{ALI} file
3788 read-only.
3789 @end itemize
3791 Using SALs is not different from using other libraries
3792 (see @ref{75,,Using a library}).
3794 @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
3795 @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}
3796 @subsubsection Creating a Stand-alone Library to be used in a non-Ada context
3799 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
3800 a non-Ada context.
3802 The only extra step required is to ensure that library interface subprograms
3803 are compatible with the main program, by means of @code{pragma Export}
3804 or @code{pragma Convention}.
3806 Here is an example of simple library interface for use with C main program:
3808 @example
3809 package My_Package is
3811    procedure Do_Something;
3812    pragma Export (C, Do_Something, "do_something");
3814    procedure Do_Something_Else;
3815    pragma Export (C, Do_Something_Else, "do_something_else");
3817 end My_Package;
3818 @end example
3820 On the foreign language side, you must provide a ‘foreign’ view of the
3821 library interface; remember that it should contain elaboration routines in
3822 addition to interface subprograms.
3824 The example below shows the content of @code{mylib_interface.h} (note
3825 that there is no rule for the naming of this file, any name can be used)
3827 @example
3828 /* the library elaboration procedure */
3829 extern void mylibinit (void);
3831 /* the library finalization procedure */
3832 extern void mylibfinal (void);
3834 /* the interface exported by the library */
3835 extern void do_something (void);
3836 extern void do_something_else (void);
3837 @end example
3839 Libraries built as explained above can be used from any program, provided
3840 that the elaboration procedures (named @code{mylibinit} in the previous
3841 example) are called before the library services are used. Any number of
3842 libraries can be used simultaneously, as long as the elaboration
3843 procedure of each library is called.
3845 Below is an example of a C program that uses the @code{mylib} library.
3847 @example
3848 #include "mylib_interface.h"
3851 main (void)
3853    /* First, elaborate the library before using it */
3854    mylibinit ();
3856    /* Main program, using the library exported entities */
3857    do_something ();
3858    do_something_else ();
3860    /* Library finalization at the end of the program */
3861    mylibfinal ();
3862    return 0;
3864 @end example
3866 Note that invoking any library finalization procedure generated by
3867 @code{gnatbind} shuts down the Ada run-time environment.
3868 Consequently, the
3869 finalization of all Ada libraries must be performed at the end of the program.
3870 No call to these libraries or to the Ada run-time library should be made
3871 after the finalization phase.
3873 Information on limitations of binding Ada code in non-Ada contexts can be
3874 found under @ref{7e,,Binding with Non-Ada Main Programs}.
3876 Note also that special care must be taken with multi-tasks
3877 applications. The initialization and finalization routines are not
3878 protected against concurrent access. If such requirement is needed it
3879 must be ensured at the application level using a specific operating
3880 system services like a mutex or a critical-section.
3882 @node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
3883 @anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{7f}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{80}
3884 @subsubsection Restrictions in Stand-alone Libraries
3887 The pragmas listed below should be used with caution inside libraries,
3888 as they can create incompatibilities with other Ada libraries:
3891 @itemize *
3893 @item 
3894 pragma @code{Locking_Policy}
3896 @item 
3897 pragma @code{Partition_Elaboration_Policy}
3899 @item 
3900 pragma @code{Queuing_Policy}
3902 @item 
3903 pragma @code{Task_Dispatching_Policy}
3905 @item 
3906 pragma @code{Unreserve_All_Interrupts}
3907 @end itemize
3909 When using a library that contains such pragmas, the user must make sure
3910 that all libraries use the same pragmas with the same values. Otherwise,
3911 @code{Program_Error} will
3912 be raised during the elaboration of the conflicting
3913 libraries. The usage of these pragmas and its consequences for the user
3914 should therefore be well documented.
3916 Similarly, the traceback in the exception occurrence mechanism should be
3917 enabled or disabled in a consistent manner across all libraries.
3918 Otherwise, Program_Error will be raised during the elaboration of the
3919 conflicting libraries.
3921 If the @code{Version} or @code{Body_Version}
3922 attributes are used inside a library, then you need to
3923 perform a @code{gnatbind} step that specifies all @code{ALI} files in all
3924 libraries, so that version identifiers can be properly computed.
3925 In practice these attributes are rarely used, so this is unlikely
3926 to be a consideration.
3928 @node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
3929 @anchor{gnat_ugn/the_gnat_compilation_model id46}@anchor{81}@anchor{gnat_ugn/the_gnat_compilation_model rebuilding-the-gnat-run-time-library}@anchor{82}
3930 @subsection Rebuilding the GNAT Run-Time Library
3933 @geindex GNAT Run-Time Library
3934 @geindex rebuilding
3936 @geindex Building the GNAT Run-Time Library
3938 @geindex Rebuilding the GNAT Run-Time Library
3940 @geindex Run-Time Library
3941 @geindex rebuilding
3943 It may be useful to recompile the GNAT library in various debugging or
3944 experimentation contexts. A project file called
3945 @code{libada.gpr} is provided to that effect and can be found in
3946 the directory containing the GNAT library. The location of this
3947 directory depends on the way the GNAT environment has been installed and can
3948 be determined by means of the command:
3950 @example
3951 $ gnatls -v
3952 @end example
3954 The last entry in the source search path usually contains the
3955 gnat library (the @code{adainclude} directory). This project file contains its
3956 own documentation and in particular the set of instructions needed to rebuild a
3957 new library and to use it.
3959 Note that rebuilding the GNAT Run-Time is only recommended for temporary
3960 experiments or debugging, and is not supported.
3962 @geindex Conditional compilation
3964 @node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
3965 @anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{2b}@anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{83}
3966 @section Conditional Compilation
3969 This section presents some guidelines for modeling conditional compilation in Ada and describes the
3970 gnatprep preprocessor utility.
3972 @geindex Conditional compilation
3974 @menu
3975 * Modeling Conditional Compilation in Ada:: 
3976 * Preprocessing with gnatprep:: 
3977 * Integrated Preprocessing:: 
3979 @end menu
3981 @node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
3982 @anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{84}@anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{85}
3983 @subsection Modeling Conditional Compilation in Ada
3986 It is often necessary to arrange for a single source program
3987 to serve multiple purposes, where it is compiled in different
3988 ways to achieve these different goals. Some examples of the
3989 need for this feature are
3992 @itemize *
3994 @item 
3995 Adapting a program to a different hardware environment
3997 @item 
3998 Adapting a program to a different target architecture
4000 @item 
4001 Turning debugging features on and off
4003 @item 
4004 Arranging for a program to compile with different compilers
4005 @end itemize
4007 In C, or C++, the typical approach would be to use the preprocessor
4008 that is defined as part of the language. The Ada language does not
4009 contain such a feature. This is not an oversight, but rather a very
4010 deliberate design decision, based on the experience that overuse of
4011 the preprocessing features in C and C++ can result in programs that
4012 are extremely difficult to maintain. For example, if we have ten
4013 switches that can be on or off, this means that there are a thousand
4014 separate programs, any one of which might not even be syntactically
4015 correct, and even if syntactically correct, the resulting program
4016 might not work correctly. Testing all combinations can quickly become
4017 impossible.
4019 Nevertheless, the need to tailor programs certainly exists, and in
4020 this section we will discuss how this can
4021 be achieved using Ada in general, and GNAT in particular.
4023 @menu
4024 * Use of Boolean Constants:: 
4025 * Debugging - A Special Case:: 
4026 * Conditionalizing Declarations:: 
4027 * Use of Alternative Implementations:: 
4028 * Preprocessing:: 
4030 @end menu
4032 @node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4033 @anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{86}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{87}
4034 @subsubsection Use of Boolean Constants
4037 In the case where the difference is simply which code
4038 sequence is executed, the cleanest solution is to use Boolean
4039 constants to control which code is executed.
4041 @example
4042 FP_Initialize_Required : constant Boolean := True;
4044 if FP_Initialize_Required then
4046 end if;
4047 @end example
4049 Not only will the code inside the @code{if} statement not be executed if
4050 the constant Boolean is @code{False}, but it will also be completely
4051 deleted from the program.
4052 However, the code is only deleted after the @code{if} statement
4053 has been checked for syntactic and semantic correctness.
4054 (In contrast, with preprocessors the code is deleted before the
4055 compiler ever gets to see it, so it is not checked until the switch
4056 is turned on.)
4058 @geindex Preprocessors (contrasted with conditional compilation)
4060 Typically the Boolean constants will be in a separate package,
4061 something like:
4063 @example
4064 package Config is
4065    FP_Initialize_Required : constant Boolean := True;
4066    Reset_Available        : constant Boolean := False;
4067    ...
4068 end Config;
4069 @end example
4071 The @code{Config} package exists in multiple forms for the various targets,
4072 with an appropriate script selecting the version of @code{Config} needed.
4073 Then any other unit requiring conditional compilation can do a `with'
4074 of @code{Config} to make the constants visible.
4076 @node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4077 @anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{88}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{89}
4078 @subsubsection Debugging - A Special Case
4081 A common use of conditional code is to execute statements (for example
4082 dynamic checks, or output of intermediate results) under control of a
4083 debug switch, so that the debugging behavior can be turned on and off.
4084 This can be done using a Boolean constant to control whether the code
4085 is active:
4087 @example
4088 if Debugging then
4089    Put_Line ("got to the first stage!");
4090 end if;
4091 @end example
4095 @example
4096 if Debugging and then Temperature > 999.0 then
4097    raise Temperature_Crazy;
4098 end if;
4099 @end example
4101 @geindex pragma Assert
4103 Since this is a common case, there are special features to deal with
4104 this in a convenient manner. For the case of tests, Ada 2005 has added
4105 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
4106 on the @code{Assert} pragma that has always been available in GNAT, so this
4107 feature may be used with GNAT even if you are not using Ada 2005 features.
4108 The use of pragma @code{Assert} is described in the
4109 @cite{GNAT_Reference_Manual}, but as an
4110 example, the last test could be written:
4112 @example
4113 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4114 @end example
4116 or simply
4118 @example
4119 pragma Assert (Temperature <= 999.0);
4120 @end example
4122 In both cases, if assertions are active and the temperature is excessive,
4123 the exception @code{Assert_Failure} will be raised, with the given string in
4124 the first case or a string indicating the location of the pragma in the second
4125 case used as the exception message.
4127 @geindex pragma Assertion_Policy
4129 You can turn assertions on and off by using the @code{Assertion_Policy}
4130 pragma.
4132 @geindex -gnata switch
4134 This is an Ada 2005 pragma which is implemented in all modes by
4135 GNAT. Alternatively, you can use the @code{-gnata} switch
4136 to enable assertions from the command line, which applies to
4137 all versions of Ada.
4139 @geindex pragma Debug
4141 For the example above with the @code{Put_Line}, the GNAT-specific pragma
4142 @code{Debug} can be used:
4144 @example
4145 pragma Debug (Put_Line ("got to the first stage!"));
4146 @end example
4148 If debug pragmas are enabled, the argument, which must be of the form of
4149 a procedure call, is executed (in this case, @code{Put_Line} will be called).
4150 Only one call can be present, but of course a special debugging procedure
4151 containing any code you like can be included in the program and then
4152 called in a pragma @code{Debug} argument as needed.
4154 One advantage of pragma @code{Debug} over the @code{if Debugging then}
4155 construct is that pragma @code{Debug} can appear in declarative contexts,
4156 such as at the very beginning of a procedure, before local declarations have
4157 been elaborated.
4159 @geindex pragma Debug_Policy
4161 Debug pragmas are enabled using either the @code{-gnata} switch that also
4162 controls assertions, or with a separate Debug_Policy pragma.
4164 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4165 in Ada 95 and Ada 83 programs as well), and is analogous to
4166 pragma @code{Assertion_Policy} to control assertions.
4168 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
4169 and thus they can appear in @code{gnat.adc} if you are not using a
4170 project file, or in the file designated to contain configuration pragmas
4171 in a project file.
4172 They then apply to all subsequent compilations. In practice the use of
4173 the @code{-gnata} switch is often the most convenient method of controlling
4174 the status of these pragmas.
4176 Note that a pragma is not a statement, so in contexts where a statement
4177 sequence is required, you can’t just write a pragma on its own. You have
4178 to add a @code{null} statement.
4180 @example
4181 if ... then
4182    ... -- some statements
4183 else
4184    pragma Assert (Num_Cases < 10);
4185    null;
4186 end if;
4187 @end example
4189 @node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4190 @anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{8a}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{8b}
4191 @subsubsection Conditionalizing Declarations
4194 In some cases it may be necessary to conditionalize declarations to meet
4195 different requirements. For example we might want a bit string whose length
4196 is set to meet some hardware message requirement.
4198 This may be possible using declare blocks controlled
4199 by conditional constants:
4201 @example
4202 if Small_Machine then
4203    declare
4204       X : Bit_String (1 .. 10);
4205    begin
4206       ...
4207    end;
4208 else
4209    declare
4210       X : Large_Bit_String (1 .. 1000);
4211    begin
4212       ...
4213    end;
4214 end if;
4215 @end example
4217 Note that in this approach, both declarations are analyzed by the
4218 compiler so this can only be used where both declarations are legal,
4219 even though one of them will not be used.
4221 Another approach is to define integer constants, e.g., @code{Bits_Per_Word},
4222 or Boolean constants, e.g., @code{Little_Endian}, and then write declarations
4223 that are parameterized by these constants. For example
4225 @example
4226 for Rec use
4227   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4228 end record;
4229 @end example
4231 If @code{Bits_Per_Word} is set to 32, this generates either
4233 @example
4234 for Rec use
4235   Field1 at 0 range 0 .. 32;
4236 end record;
4237 @end example
4239 for the big endian case, or
4241 @example
4242 for Rec use record
4243     Field1 at 0 range 10 .. 32;
4244 end record;
4245 @end example
4247 for the little endian case. Since a powerful subset of Ada expression
4248 notation is usable for creating static constants, clever use of this
4249 feature can often solve quite difficult problems in conditionalizing
4250 compilation (note incidentally that in Ada 95, the little endian
4251 constant was introduced as @code{System.Default_Bit_Order}, so you do not
4252 need to define this one yourself).
4254 @node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4255 @anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{8c}@anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{8d}
4256 @subsubsection Use of Alternative Implementations
4259 In some cases, none of the approaches described above are adequate. This
4260 can occur for example if the set of declarations required is radically
4261 different for two different configurations.
4263 In this situation, the official Ada way of dealing with conditionalizing
4264 such code is to write separate units for the different cases. As long as
4265 this does not result in excessive duplication of code, this can be done
4266 without creating maintenance problems. The approach is to share common
4267 code as far as possible, and then isolate the code and declarations
4268 that are different. Subunits are often a convenient method for breaking
4269 out a piece of a unit that is to be conditionalized, with separate files
4270 for different versions of the subunit for different targets, where the
4271 build script selects the right one to give to the compiler.
4273 @geindex Subunits (and conditional compilation)
4275 As an example, consider a situation where a new feature in Ada 2005
4276 allows something to be done in a really nice way. But your code must be able
4277 to compile with an Ada 95 compiler. Conceptually you want to say:
4279 @example
4280 if Ada_2005 then
4281    ... neat Ada 2005 code
4282 else
4283    ... not quite as neat Ada 95 code
4284 end if;
4285 @end example
4287 where @code{Ada_2005} is a Boolean constant.
4289 But this won’t work when @code{Ada_2005} is set to @code{False},
4290 since the @code{then} clause will be illegal for an Ada 95 compiler.
4291 (Recall that although such unreachable code would eventually be deleted
4292 by the compiler, it still needs to be legal.  If it uses features
4293 introduced in Ada 2005, it will be illegal in Ada 95.)
4295 So instead we write
4297 @example
4298 procedure Insert is separate;
4299 @end example
4301 Then we have two files for the subunit @code{Insert}, with the two sets of
4302 code.
4303 If the package containing this is called @code{File_Queries}, then we might
4304 have two files
4307 @itemize *
4309 @item 
4310 @code{file_queries-insert-2005.adb}
4312 @item 
4313 @code{file_queries-insert-95.adb}
4314 @end itemize
4316 and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4318 This can also be done with project files’ naming schemes. For example:
4320 @example
4321 for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4322 @end example
4324 Note also that with project files it is desirable to use a different extension
4325 than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4326 conflict may arise through another commonly used feature: to declare as part
4327 of the project a set of directories containing all the sources obeying the
4328 default naming scheme.
4330 The use of alternative units is certainly feasible in all situations,
4331 and for example the Ada part of the GNAT run-time is conditionalized
4332 based on the target architecture using this approach. As a specific example,
4333 consider the implementation of the AST feature in VMS. There is one
4334 spec: @code{s-asthan.ads} which is the same for all architectures, and three
4335 bodies:
4338 @itemize *
4340 @item 
4342 @table @asis
4344 @item @code{s-asthan.adb}
4346 used for all non-VMS operating systems
4347 @end table
4349 @item 
4351 @table @asis
4353 @item @code{s-asthan-vms-alpha.adb}
4355 used for VMS on the Alpha
4356 @end table
4358 @item 
4360 @table @asis
4362 @item @code{s-asthan-vms-ia64.adb}
4364 used for VMS on the ia64
4365 @end table
4366 @end itemize
4368 The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4369 this operating system feature is not available, and the two remaining
4370 versions interface with the corresponding versions of VMS to provide
4371 VMS-compatible AST handling. The GNAT build script knows the architecture
4372 and operating system, and automatically selects the right version,
4373 renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4375 Another style for arranging alternative implementations is through Ada’s
4376 access-to-subprogram facility.
4377 In case some functionality is to be conditionally included,
4378 you can declare an access-to-procedure variable @code{Ref} that is initialized
4379 to designate a ‘do nothing’ procedure, and then invoke @code{Ref.all}
4380 when appropriate.
4381 In some library package, set @code{Ref} to @code{Proc'Access} for some
4382 procedure @code{Proc} that performs the relevant processing.
4383 The initialization only occurs if the library package is included in the
4384 program.
4385 The same idea can also be implemented using tagged types and dispatching
4386 calls.
4388 @node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4389 @anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{8e}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{8f}
4390 @subsubsection Preprocessing
4393 @geindex Preprocessing
4395 Although it is quite possible to conditionalize code without the use of
4396 C-style preprocessing, as described earlier in this section, it is
4397 nevertheless convenient in some cases to use the C approach. Moreover,
4398 older Ada compilers have often provided some preprocessing capability,
4399 so legacy code may depend on this approach, even though it is not
4400 standard.
4402 To accommodate such use, GNAT provides a preprocessor (modeled to a large
4403 extent on the various preprocessors that have been used
4404 with legacy code on other compilers, to enable easier transition).
4406 @geindex gnatprep
4408 The preprocessor may be used in two separate modes. It can be used quite
4409 separately from the compiler, to generate a separate output source file
4410 that is then fed to the compiler as a separate step. This is the
4411 @code{gnatprep} utility, whose use is fully described in
4412 @ref{90,,Preprocessing with gnatprep}.
4414 The preprocessing language allows such constructs as
4416 @example
4417 #if DEBUG or else (PRIORITY > 4) then
4418    sequence of declarations
4419 #else
4420    completely different sequence of declarations
4421 #end if;
4422 @end example
4424 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
4425 defined either on the command line or in a separate file.
4427 The other way of running the preprocessor is even closer to the C style and
4428 often more convenient. In this approach the preprocessing is integrated into
4429 the compilation process. The compiler is given the preprocessor input which
4430 includes @code{#if} lines etc, and then the compiler carries out the
4431 preprocessing internally and processes the resulting output.
4432 For more details on this approach, see @ref{91,,Integrated Preprocessing}.
4434 @node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4435 @anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{92}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{90}
4436 @subsection Preprocessing with @code{gnatprep}
4439 @geindex gnatprep
4441 @geindex Preprocessing (gnatprep)
4443 This section discusses how to use GNAT’s @code{gnatprep} utility for simple
4444 preprocessing.
4445 Although designed for use with GNAT, @code{gnatprep} does not depend on any
4446 special GNAT features.
4447 For further discussion of conditional compilation in general, see
4448 @ref{2b,,Conditional Compilation}.
4450 @menu
4451 * Preprocessing Symbols:: 
4452 * Using gnatprep:: 
4453 * Switches for gnatprep:: 
4454 * Form of Definitions File:: 
4455 * Form of Input Text for gnatprep:: 
4457 @end menu
4459 @node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4460 @anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{93}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{94}
4461 @subsubsection Preprocessing Symbols
4464 Preprocessing symbols are defined in `definition files' and referenced in the
4465 sources to be preprocessed. A preprocessing symbol is an identifier, following
4466 normal Ada (case-insensitive) rules for its syntax, with the restriction that
4467 all characters need to be in the ASCII set (no accented letters).
4469 @node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4470 @anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{95}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{96}
4471 @subsubsection Using @code{gnatprep}
4474 To call @code{gnatprep} use:
4476 @example
4477 $ gnatprep [ switches ] infile outfile [ deffile ]
4478 @end example
4480 where
4483 @itemize *
4485 @item 
4487 @table @asis
4489 @item `switches'
4491 is an optional sequence of switches as described in the next section.
4492 @end table
4494 @item 
4496 @table @asis
4498 @item `infile'
4500 is the full name of the input file, which is an Ada source
4501 file containing preprocessor directives.
4502 @end table
4504 @item 
4506 @table @asis
4508 @item `outfile'
4510 is the full name of the output file, which is an Ada source
4511 in standard Ada form. When used with GNAT, this file name will
4512 normally have an @code{ads} or @code{adb} suffix.
4513 @end table
4515 @item 
4517 @table @asis
4519 @item @code{deffile}
4521 is the full name of a text file containing definitions of
4522 preprocessing symbols to be referenced by the preprocessor. This argument is
4523 optional, and can be replaced by the use of the @code{-D} switch.
4524 @end table
4525 @end itemize
4527 @node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4528 @anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{97}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{98}
4529 @subsubsection Switches for @code{gnatprep}
4532 @geindex --version (gnatprep)
4535 @table @asis
4537 @item @code{--version}
4539 Display Copyright and version, then exit disregarding all other options.
4540 @end table
4542 @geindex --help (gnatprep)
4545 @table @asis
4547 @item @code{--help}
4549 If @code{--version} was not used, display usage and then exit disregarding
4550 all other options.
4551 @end table
4553 @geindex -b (gnatprep)
4556 @table @asis
4558 @item @code{-b}
4560 Causes both preprocessor lines and the lines deleted by
4561 preprocessing to be replaced by blank lines in the output source file,
4562 preserving line numbers in the output file.
4563 @end table
4565 @geindex -c (gnatprep)
4568 @table @asis
4570 @item @code{-c}
4572 Causes both preprocessor lines and the lines deleted
4573 by preprocessing to be retained in the output source as comments marked
4574 with the special string @code{"--! "}. This option will result in line numbers
4575 being preserved in the output file.
4576 @end table
4578 @geindex -C (gnatprep)
4581 @table @asis
4583 @item @code{-C}
4585 Causes comments to be scanned. Normally comments are ignored by gnatprep.
4586 If this option is specified, then comments are scanned and any $symbol
4587 substitutions performed as in program text. This is particularly useful
4588 when structured comments are used (e.g., for programs written in a
4589 pre-2014 version of the SPARK Ada subset). Note that this switch is not
4590 available when  doing integrated preprocessing (it would be useless in
4591 this context since comments are ignored by the compiler in any case).
4592 @end table
4594 @geindex -D (gnatprep)
4597 @table @asis
4599 @item @code{-D`symbol'[=`value']}
4601 Defines a new preprocessing symbol with the specified value. If no value is given
4602 on the command line, then symbol is considered to be @code{True}. This switch
4603 can be used in place of a definition file.
4604 @end table
4606 @geindex -r (gnatprep)
4609 @table @asis
4611 @item @code{-r}
4613 Causes a @code{Source_Reference} pragma to be generated that
4614 references the original input file, so that error messages will use
4615 the file name of this original file. The use of this switch implies
4616 that preprocessor lines are not to be removed from the file, so its
4617 use will force @code{-b} mode if @code{-c}
4618 has not been specified explicitly.
4620 Note that if the file to be preprocessed contains multiple units, then
4621 it will be necessary to @code{gnatchop} the output file from
4622 @code{gnatprep}. If a @code{Source_Reference} pragma is present
4623 in the preprocessed file, it will be respected by
4624 @code{gnatchop -r}
4625 so that the final chopped files will correctly refer to the original
4626 input source file for @code{gnatprep}.
4627 @end table
4629 @geindex -s (gnatprep)
4632 @table @asis
4634 @item @code{-s}
4636 Causes a sorted list of symbol names and values to be
4637 listed on the standard output file.
4638 @end table
4640 @geindex -T (gnatprep)
4643 @table @asis
4645 @item @code{-T}
4647 Use LF as line terminators when writing files. By default the line terminator
4648 of the host (LF under unix, CR/LF under Windows) is used.
4649 @end table
4651 @geindex -u (gnatprep)
4654 @table @asis
4656 @item @code{-u}
4658 Causes undefined symbols to be treated as having the value FALSE in the context
4659 of a preprocessor test. In the absence of this option, an undefined symbol in
4660 a @code{#if} or @code{#elsif} test will be treated as an error.
4661 @end table
4663 @geindex -v (gnatprep)
4666 @table @asis
4668 @item @code{-v}
4670 Verbose mode: generates more output about work done.
4671 @end table
4673 Note: if neither @code{-b} nor @code{-c} is present,
4674 then preprocessor lines and
4675 deleted lines are completely removed from the output, unless -r is
4676 specified, in which case -b is assumed.
4678 @node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4679 @anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{99}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{9a}
4680 @subsubsection Form of Definitions File
4683 The definitions file contains lines of the form:
4685 @example
4686 symbol := value
4687 @end example
4689 where @code{symbol} is a preprocessing symbol, and @code{value} is one of the following:
4692 @itemize *
4694 @item 
4695 Empty, corresponding to a null substitution,
4697 @item 
4698 A string literal using normal Ada syntax, or
4700 @item 
4701 Any sequence of characters from the set @{letters, digits, period, underline@}.
4702 @end itemize
4704 Comment lines may also appear in the definitions file, starting with
4705 the usual @code{--},
4706 and comments may be added to the definitions lines.
4708 @node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4709 @anchor{gnat_ugn/the_gnat_compilation_model form-of-input-text-for-gnatprep}@anchor{9b}@anchor{gnat_ugn/the_gnat_compilation_model id59}@anchor{9c}
4710 @subsubsection Form of Input Text for @code{gnatprep}
4713 The input text may contain preprocessor conditional inclusion lines,
4714 as well as general symbol substitution sequences.
4716 The preprocessor conditional inclusion commands have the form:
4718 @example
4719 #if <expression> [then]
4720    lines
4721 #elsif <expression> [then]
4722    lines
4723 #elsif <expression> [then]
4724    lines
4726 #else
4727    lines
4728 #end if;
4729 @end example
4731 In this example, <expression> is defined by the following grammar:
4733 @example
4734 <expression> ::=  <symbol>
4735 <expression> ::=  <symbol> = "<value>"
4736 <expression> ::=  <symbol> = <symbol>
4737 <expression> ::=  <symbol> = <integer>
4738 <expression> ::=  <symbol> > <integer>
4739 <expression> ::=  <symbol> >= <integer>
4740 <expression> ::=  <symbol> < <integer>
4741 <expression> ::=  <symbol> <= <integer>
4742 <expression> ::=  <symbol> 'Defined
4743 <expression> ::=  not <expression>
4744 <expression> ::=  <expression> and <expression>
4745 <expression> ::=  <expression> or <expression>
4746 <expression> ::=  <expression> and then <expression>
4747 <expression> ::=  <expression> or else <expression>
4748 <expression> ::=  ( <expression> )
4749 @end example
4751 Note the following restriction: it is not allowed to have “and” or “or”
4752 following “not” in the same expression without parentheses. For example, this
4753 is not allowed:
4755 @example
4756 not X or Y
4757 @end example
4759 This can be expressed instead as one of the following forms:
4761 @example
4762 (not X) or Y
4763 not (X or Y)
4764 @end example
4766 For the first test (<expression> ::= <symbol>) the symbol must have
4767 either the value true or false, that is to say the right-hand of the
4768 symbol definition must be one of the (case-insensitive) literals
4769 @code{True} or @code{False}. If the value is true, then the
4770 corresponding lines are included, and if the value is false, they are
4771 excluded.
4773 When comparing a symbol to an integer, the integer is any non negative
4774 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
4775 2#11#. The symbol value must also be a non negative integer. Integer values
4776 in the range 0 .. 2**31-1 are supported.
4778 The test (<expression> ::= <symbol>’Defined) is true only if
4779 the symbol has been defined in the definition file or by a @code{-D}
4780 switch on the command line. Otherwise, the test is false.
4782 The equality tests are case insensitive, as are all the preprocessor lines.
4784 If the symbol referenced is not defined in the symbol definitions file,
4785 then the effect depends on whether or not switch @code{-u}
4786 is specified. If so, then the symbol is treated as if it had the value
4787 false and the test fails. If this switch is not specified, then
4788 it is an error to reference an undefined symbol. It is also an error to
4789 reference a symbol that is defined with a value other than @code{True}
4790 or @code{False}.
4792 The use of the @code{not} operator inverts the sense of this logical test.
4793 The @code{not} operator cannot be combined with the @code{or} or @code{and}
4794 operators, without parentheses. For example, “if not X or Y then” is not
4795 allowed, but “if (not X) or Y then” and “if not (X or Y) then” are.
4797 The @code{then} keyword is optional as shown
4799 The @code{#} must be the first non-blank character on a line, but
4800 otherwise the format is free form. Spaces or tabs may appear between
4801 the @code{#} and the keyword. The keywords and the symbols are case
4802 insensitive as in normal Ada code. Comments may be used on a
4803 preprocessor line, but other than that, no other tokens may appear on a
4804 preprocessor line. Any number of @code{elsif} clauses can be present,
4805 including none at all. The @code{else} is optional, as in Ada.
4807 The @code{#} marking the start of a preprocessor line must be the first
4808 non-blank character on the line, i.e., it must be preceded only by
4809 spaces or horizontal tabs.
4811 Symbol substitution outside of preprocessor lines is obtained by using
4812 the sequence:
4814 @example
4815 $symbol
4816 @end example
4818 anywhere within a source line, except in a comment or within a
4819 string literal. The identifier
4820 following the @code{$} must match one of the symbols defined in the symbol
4821 definition file, and the result is to substitute the value of the
4822 symbol in place of @code{$symbol} in the output file.
4824 Note that although the substitution of strings within a string literal
4825 is not possible, it is possible to have a symbol whose defined value is
4826 a string literal. So instead of setting XYZ to @code{hello} and writing:
4828 @example
4829 Header : String := "$XYZ";
4830 @end example
4832 you should set XYZ to @code{"hello"} and write:
4834 @example
4835 Header : String := $XYZ;
4836 @end example
4838 and then the substitution will occur as desired.
4840 @node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
4841 @anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{9d}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{91}
4842 @subsection Integrated Preprocessing
4845 As noted above, a file to be preprocessed consists of Ada source code
4846 in which preprocessing lines have been inserted. However,
4847 instead of using @code{gnatprep} to explicitly preprocess a file as a separate
4848 step before compilation, you can carry out the preprocessing implicitly
4849 as part of compilation. Such `integrated preprocessing', which is the common
4850 style with C, is performed when either or both of the following switches
4851 are passed to the compiler:
4853 @quotation
4856 @itemize *
4858 @item 
4859 @code{-gnatep}, which specifies the `preprocessor data file'.
4860 This file dictates how the source files will be preprocessed (e.g., which
4861 symbol definition files apply to which sources).
4863 @item 
4864 @code{-gnateD}, which defines values for preprocessing symbols.
4865 @end itemize
4866 @end quotation
4868 Integrated preprocessing applies only to Ada source files, it is
4869 not available for configuration pragma files.
4871 With integrated preprocessing, the output from the preprocessor is not,
4872 by default, written to any external file. Instead it is passed
4873 internally to the compiler. To preserve the result of
4874 preprocessing in a file, either run @code{gnatprep}
4875 in standalone mode or else supply the @code{-gnateG} switch
4876 (described below) to the compiler.
4878 When using project files:
4880 @quotation
4883 @itemize *
4885 @item 
4886 the builder switch @code{-x} should be used if any Ada source is
4887 compiled with @code{gnatep=}, so that the compiler finds the
4888 `preprocessor data file'.
4890 @item 
4891 the preprocessing data file and the symbol definition files should be
4892 located in the source directories of the project.
4893 @end itemize
4894 @end quotation
4896 Note that the @code{gnatmake} switch @code{-m} will almost
4897 always trigger recompilation for sources that are preprocessed,
4898 because @code{gnatmake} cannot compute the checksum of the source after
4899 preprocessing.
4901 The actual preprocessing function is described in detail in
4902 @ref{90,,Preprocessing with gnatprep}. This section explains the switches
4903 that relate to integrated preprocessing.
4905 @geindex -gnatep (gcc)
4908 @table @asis
4910 @item @code{-gnatep=`preprocessor_data_file'}
4912 This switch specifies the file name (without directory
4913 information) of the preprocessor data file. Either place this file
4914 in one of the source directories, or, when using project
4915 files, reference the project file’s directory via the
4916 @code{project_name'Project_Dir} project attribute; e.g:
4918 @quotation
4920 @example
4921 project Prj is
4922    package Compiler is
4923       for Switches ("Ada") use
4924         ("-gnatep=" & Prj'Project_Dir & "prep.def");
4925    end Compiler;
4926 end Prj;
4927 @end example
4928 @end quotation
4930 A preprocessor data file is a text file that contains `preprocessor
4931 control lines'.  A preprocessor control line directs the preprocessing of
4932 either a particular source file, or, analogous to @code{others} in Ada,
4933 all sources not specified elsewhere in  the preprocessor data file.
4934 A preprocessor control line
4935 can optionally identify a `definition file' that assigns values to
4936 preprocessor symbols, as well as a list of switches that relate to
4937 preprocessing.
4938 Empty lines and comments (using Ada syntax) are also permitted, with no
4939 semantic effect.
4941 Here’s an example of a preprocessor data file:
4943 @quotation
4945 @example
4946 "toto.adb"  "prep.def" -u
4947 --  Preprocess toto.adb, using definition file prep.def
4948 --  Undefined symbols are treated as False
4950 * -c -DVERSION=V101
4951 --  Preprocess all other sources without using a definition file
4952 --  Suppressed lined are commented
4953 --  Symbol VERSION has the value V101
4955 "tata.adb" "prep2.def" -s
4956 --  Preprocess tata.adb, using definition file prep2.def
4957 --  List all symbols with their values
4958 @end example
4959 @end quotation
4961 A preprocessor control line has the following syntax:
4963 @quotation
4965 @example
4966 <preprocessor_control_line> ::=
4967    <preprocessor_input> [ <definition_file_name> ] @{ <switch> @}
4969 <preprocessor_input> ::= <source_file_name> | '*'
4971 <definition_file_name> ::= <string_literal>
4973 <source_file_name> := <string_literal>
4975 <switch> := (See below for list)
4976 @end example
4977 @end quotation
4979 Thus  each preprocessor control line starts with either a literal string or
4980 the character ‘*’:
4983 @itemize *
4985 @item 
4986 A literal string is the file name (without directory information) of the source
4987 file that will be input to the preprocessor.
4989 @item 
4990 The character ‘*’ is a wild-card indicator; the additional parameters on the line
4991 indicate the preprocessing for all the sources
4992 that are not specified explicitly on other lines (the order of the lines is not
4993 significant).
4994 @end itemize
4996 It is an error to have two lines with the same file name or two
4997 lines starting with the character ‘*’.
4999 After the file name or ‘*’, an optional literal string specifies the name of
5000 the definition file to be used for preprocessing
5001 (@ref{99,,Form of Definitions File}). The definition files are found by the
5002 compiler in one of the source directories. In some cases, when compiling
5003 a source in a directory other than the current directory, if the definition
5004 file is in the current directory, it may be necessary to add the current
5005 directory as a source directory through the @code{-I} switch; otherwise
5006 the compiler would not find the definition file.
5008 Finally, switches similar to those of @code{gnatprep} may optionally appear:
5011 @table @asis
5013 @item @code{-b}
5015 Causes both preprocessor lines and the lines deleted by
5016 preprocessing to be replaced by blank lines, preserving the line number.
5017 This switch is always implied; however, if specified after @code{-c}
5018 it cancels the effect of @code{-c}.
5020 @item @code{-c}
5022 Causes both preprocessor lines and the lines deleted
5023 by preprocessing to be retained as comments marked
5024 with the special string ‘@cite{–!}’.
5026 @item @code{-D`symbol'=`new_value'}
5028 Define or redefine @code{symbol} to have @code{new_value} as its value.
5029 The permitted form for @code{symbol} is either an Ada identifier, or any Ada reserved word
5030 aside from @code{if},
5031 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5032 The permitted form for @code{new_value} is a literal string, an Ada identifier or any Ada reserved
5033 word. A symbol declared with this switch replaces a symbol with the
5034 same name defined in a definition file.
5036 @item @code{-s}
5038 Causes a sorted list of symbol names and values to be
5039 listed on the standard output file.
5041 @item @code{-u}
5043 Causes undefined symbols to be treated as having the value @code{FALSE}
5044 in the context
5045 of a preprocessor test. In the absence of this option, an undefined symbol in
5046 a @code{#if} or @code{#elsif} test will be treated as an error.
5047 @end table
5048 @end table
5050 @geindex -gnateD (gcc)
5053 @table @asis
5055 @item @code{-gnateD`symbol'[=`new_value']}
5057 Define or redefine @code{symbol} to have @code{new_value} as its value. If no value
5058 is supplied, then the value of @code{symbol} is @code{True}.
5059 The form of @code{symbol} is an identifier, following normal Ada (case-insensitive)
5060 rules for its syntax, and @code{new_value} is either an arbitrary string between double
5061 quotes or any sequence (including an empty sequence) of characters from the
5062 set (letters, digits, period, underline).
5063 Ada reserved words may be used as symbols, with the exceptions of @code{if},
5064 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5066 Examples:
5068 @quotation
5070 @example
5071 -gnateDToto=Tata
5072 -gnateDFoo
5073 -gnateDFoo=\"Foo-Bar\"
5074 @end example
5075 @end quotation
5077 A symbol declared with this switch on the command line replaces a
5078 symbol with the same name either in a definition file or specified with a
5079 switch @code{-D} in the preprocessor data file.
5081 This switch is similar to switch @code{-D} of @code{gnatprep}.
5083 @item @code{-gnateG}
5085 When integrated preprocessing is performed on source file @code{filename.extension},
5086 create or overwrite @code{filename.extension.prep} to contain
5087 the result of the preprocessing.
5088 For example if the source file is @code{foo.adb} then
5089 the output file will be @code{foo.adb.prep}.
5090 @end table
5092 @node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5093 @anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{9e}@anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{2c}
5094 @section Mixed Language Programming
5097 @geindex Mixed Language Programming
5099 This section describes how to develop a mixed-language program,
5100 with a focus on combining Ada with C or C++.
5102 @menu
5103 * Interfacing to C:: 
5104 * Calling Conventions:: 
5105 * Building Mixed Ada and C++ Programs:: 
5106 * Partition-Wide Settings:: 
5107 * Generating Ada Bindings for C and C++ headers:: 
5108 * Generating C Headers for Ada Specifications:: 
5110 @end menu
5112 @node Interfacing to C,Calling Conventions,,Mixed Language Programming
5113 @anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{9f}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{a0}
5114 @subsection Interfacing to C
5117 Interfacing Ada with a foreign language such as C involves using
5118 compiler directives to import and/or export entity definitions in each
5119 language – using @code{extern} statements in C, for instance, and the
5120 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
5121 A full treatment of these topics is provided in Appendix B, section 1
5122 of the Ada Reference Manual.
5124 There are two ways to build a program using GNAT that contains some Ada
5125 sources and some foreign language sources, depending on whether or not
5126 the main subprogram is written in Ada.  Here is a source example with
5127 the main subprogram in Ada:
5129 @example
5130 /* file1.c */
5131 #include <stdio.h>
5133 void print_num (int num)
5135   printf ("num is %d.\\n", num);
5136   return;
5138 @end example
5140 @example
5141 /* file2.c */
5143 /* num_from_Ada is declared in my_main.adb */
5144 extern int num_from_Ada;
5146 int get_num (void)
5148   return num_from_Ada;
5150 @end example
5152 @example
5153 --  my_main.adb
5154 procedure My_Main is
5156    --  Declare then export an Integer entity called num_from_Ada
5157    My_Num : Integer := 10;
5158    pragma Export (C, My_Num, "num_from_Ada");
5160    --  Declare an Ada function spec for Get_Num, then use
5161    --  C function get_num for the implementation.
5162    function Get_Num return Integer;
5163    pragma Import (C, Get_Num, "get_num");
5165    --  Declare an Ada procedure spec for Print_Num, then use
5166    --  C function print_num for the implementation.
5167    procedure Print_Num (Num : Integer);
5168    pragma Import (C, Print_Num, "print_num");
5170 begin
5171    Print_Num (Get_Num);
5172 end My_Main;
5173 @end example
5175 To build this example:
5178 @itemize *
5180 @item 
5181 First compile the foreign language files to
5182 generate object files:
5184 @example
5185 $ gcc -c file1.c
5186 $ gcc -c file2.c
5187 @end example
5189 @item 
5190 Then, compile the Ada units to produce a set of object files and ALI
5191 files:
5193 @example
5194 $ gnatmake -c my_main.adb
5195 @end example
5197 @item 
5198 Run the Ada binder on the Ada main program:
5200 @example
5201 $ gnatbind my_main.ali
5202 @end example
5204 @item 
5205 Link the Ada main program, the Ada objects and the other language
5206 objects:
5208 @example
5209 $ gnatlink my_main.ali file1.o file2.o
5210 @end example
5211 @end itemize
5213 The last three steps can be grouped in a single command:
5215 @example
5216 $ gnatmake my_main.adb -largs file1.o file2.o
5217 @end example
5219 @geindex Binder output file
5221 If the main program is in a language other than Ada, then you may have
5222 more than one entry point into the Ada subsystem. You must use a special
5223 binder option to generate callable routines that initialize and
5224 finalize the Ada units (@ref{7e,,Binding with Non-Ada Main Programs}).
5225 Calls to the initialization and finalization routines must be inserted
5226 in the main program, or some other appropriate point in the code. The
5227 call to initialize the Ada units must occur before the first Ada
5228 subprogram is called, and the call to finalize the Ada units must occur
5229 after the last Ada subprogram returns. The binder will place the
5230 initialization and finalization subprograms into the
5231 @code{b~xxx.adb} file where they can be accessed by your C
5232 sources.  To illustrate, we have the following example:
5234 @example
5235 /* main.c */
5236 extern void adainit (void);
5237 extern void adafinal (void);
5238 extern int add (int, int);
5239 extern int sub (int, int);
5241 int main (int argc, char *argv[])
5243    int a = 21, b = 7;
5245    adainit();
5247    /* Should print "21 + 7 = 28" */
5248    printf ("%d + %d = %d\\n", a, b, add (a, b));
5250    /* Should print "21 - 7 = 14" */
5251    printf ("%d - %d = %d\\n", a, b, sub (a, b));
5253    adafinal();
5255 @end example
5257 @example
5258 --  unit1.ads
5259 package Unit1 is
5260    function Add (A, B : Integer) return Integer;
5261    pragma Export (C, Add, "add");
5262 end Unit1;
5263 @end example
5265 @example
5266 --  unit1.adb
5267 package body Unit1 is
5268    function Add (A, B : Integer) return Integer is
5269    begin
5270       return A + B;
5271    end Add;
5272 end Unit1;
5273 @end example
5275 @example
5276 --  unit2.ads
5277 package Unit2 is
5278    function Sub (A, B : Integer) return Integer;
5279    pragma Export (C, Sub, "sub");
5280 end Unit2;
5281 @end example
5283 @example
5284 --  unit2.adb
5285 package body Unit2 is
5286    function Sub (A, B : Integer) return Integer is
5287    begin
5288       return A - B;
5289    end Sub;
5290 end Unit2;
5291 @end example
5293 The build procedure for this application is similar to the last
5294 example’s:
5297 @itemize *
5299 @item 
5300 First, compile the foreign language files to generate object files:
5302 @example
5303 $ gcc -c main.c
5304 @end example
5306 @item 
5307 Next, compile the Ada units to produce a set of object files and ALI
5308 files:
5310 @example
5311 $ gnatmake -c unit1.adb
5312 $ gnatmake -c unit2.adb
5313 @end example
5315 @item 
5316 Run the Ada binder on every generated ALI file.  Make sure to use the
5317 @code{-n} option to specify a foreign main program:
5319 @example
5320 $ gnatbind -n unit1.ali unit2.ali
5321 @end example
5323 @item 
5324 Link the Ada main program, the Ada objects and the foreign language
5325 objects. You need only list the last ALI file here:
5327 @example
5328 $ gnatlink unit2.ali main.o -o exec_file
5329 @end example
5331 This procedure yields a binary executable called @code{exec_file}.
5332 @end itemize
5334 Depending on the circumstances (for example when your non-Ada main object
5335 does not provide symbol @code{main}), you may also need to instruct the
5336 GNAT linker not to include the standard startup objects by passing the
5337 @code{-nostartfiles} switch to @code{gnatlink}.
5339 @node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5340 @anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{a2}
5341 @subsection Calling Conventions
5344 @geindex Foreign Languages
5346 @geindex Calling Conventions
5348 GNAT follows standard calling sequence conventions and will thus interface
5349 to any other language that also follows these conventions. The following
5350 Convention identifiers are recognized by GNAT:
5352 @geindex Interfacing to Ada
5354 @geindex Other Ada compilers
5356 @geindex Convention Ada
5359 @table @asis
5361 @item @code{Ada}
5363 This indicates that the standard Ada calling sequence will be
5364 used and all Ada data items may be passed without any limitations in the
5365 case where GNAT is used to generate both the caller and callee. It is also
5366 possible to mix GNAT generated code and code generated by another Ada
5367 compiler. In this case, the data types should be restricted to simple
5368 cases, including primitive types. Whether complex data types can be passed
5369 depends on the situation. Probably it is safe to pass simple arrays, such
5370 as arrays of integers or floats. Records may or may not work, depending
5371 on whether both compilers lay them out identically. Complex structures
5372 involving variant records, access parameters, tasks, or protected types,
5373 are unlikely to be able to be passed.
5375 Note that in the case of GNAT running
5376 on a platform that supports HP Ada 83, a higher degree of compatibility
5377 can be guaranteed, and in particular records are laid out in an identical
5378 manner in the two compilers. Note also that if output from two different
5379 compilers is mixed, the program is responsible for dealing with elaboration
5380 issues. Probably the safest approach is to write the main program in the
5381 version of Ada other than GNAT, so that it takes care of its own elaboration
5382 requirements, and then call the GNAT-generated adainit procedure to ensure
5383 elaboration of the GNAT components. Consult the documentation of the other
5384 Ada compiler for further details on elaboration.
5386 However, it is not possible to mix the tasking run time of GNAT and
5387 HP Ada 83, all the tasking operations must either be entirely within
5388 GNAT compiled sections of the program, or entirely within HP Ada 83
5389 compiled sections of the program.
5390 @end table
5392 @geindex Interfacing to Assembly
5394 @geindex Convention Assembler
5397 @table @asis
5399 @item @code{Assembler}
5401 Specifies assembler as the convention. In practice this has the
5402 same effect as convention Ada (but is not equivalent in the sense of being
5403 considered the same convention).
5404 @end table
5406 @geindex Convention Asm
5408 @geindex Asm
5411 @table @asis
5413 @item @code{Asm}
5415 Equivalent to Assembler.
5417 @geindex Interfacing to COBOL
5419 @geindex Convention COBOL
5420 @end table
5422 @geindex COBOL
5425 @table @asis
5427 @item @code{COBOL}
5429 Data will be passed according to the conventions described
5430 in section B.4 of the Ada Reference Manual.
5431 @end table
5433 @geindex C
5435 @geindex Interfacing to C
5437 @geindex Convention C
5440 @table @asis
5442 @item @code{C}
5444 Data will be passed according to the conventions described
5445 in section B.3 of the Ada Reference Manual.
5447 A note on interfacing to a C ‘varargs’ function:
5449 @quotation
5451 @geindex C varargs function
5453 @geindex Interfacing to C varargs function
5455 @geindex varargs function interfaces
5457 In C, @code{varargs} allows a function to take a variable number of
5458 arguments. There is no direct equivalent in this to Ada. One
5459 approach that can be used is to create a C wrapper for each
5460 different profile and then interface to this C wrapper. For
5461 example, to print an @code{int} value using @code{printf},
5462 create a C function @code{printfi} that takes two arguments, a
5463 pointer to a string and an int, and calls @code{printf}.
5464 Then in the Ada program, use pragma @code{Import} to
5465 interface to @code{printfi}.
5467 It may work on some platforms to directly interface to
5468 a @code{varargs} function by providing a specific Ada profile
5469 for a particular call. However, this does not work on
5470 all platforms, since there is no guarantee that the
5471 calling sequence for a two argument normal C function
5472 is the same as for calling a @code{varargs} C function with
5473 the same two arguments.
5474 @end quotation
5475 @end table
5477 @geindex Convention Default
5479 @geindex Default
5482 @table @asis
5484 @item @code{Default}
5486 Equivalent to C.
5487 @end table
5489 @geindex Convention External
5491 @geindex External
5494 @table @asis
5496 @item @code{External}
5498 Equivalent to C.
5499 @end table
5501 @geindex C++
5503 @geindex Interfacing to C++
5505 @geindex Convention C++
5508 @table @asis
5510 @item @code{C_Plus_Plus} (or @code{CPP})
5512 This stands for C++. For most purposes this is identical to C.
5513 See the separate description of the specialized GNAT pragmas relating to
5514 C++ interfacing for further details.
5515 @end table
5517 @geindex Fortran
5519 @geindex Interfacing to Fortran
5521 @geindex Convention Fortran
5524 @table @asis
5526 @item @code{Fortran}
5528 Data will be passed according to the conventions described
5529 in section B.5 of the Ada Reference Manual.
5531 @item @code{Intrinsic}
5533 This applies to an intrinsic operation, as defined in the Ada
5534 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5535 this means that the body of the subprogram is provided by the compiler itself,
5536 usually by means of an efficient code sequence, and that the user does not
5537 supply an explicit body for it. In an application program, the pragma may
5538 be applied to the following sets of names:
5541 @itemize *
5543 @item 
5544 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5545 The corresponding subprogram declaration must have
5546 two formal parameters. The
5547 first one must be a signed integer type or a modular type with a binary
5548 modulus, and the second parameter must be of type Natural.
5549 The return type must be the same as the type of the first argument. The size
5550 of this type can only be 8, 16, 32, or 64.
5552 @item 
5553 Binary arithmetic operators: ‘+’, ‘-’, ‘*’, ‘/’.
5554 The corresponding operator declaration must have parameters and result type
5555 that have the same root numeric type (for example, all three are long_float
5556 types). This simplifies the definition of operations that use type checking
5557 to perform dimensional checks:
5559 @example
5560 type Distance is new Long_Float;
5561 type Time     is new Long_Float;
5562 type Velocity is new Long_Float;
5563 function "/" (D : Distance; T : Time)
5564   return Velocity;
5565 pragma Import (Intrinsic, "/");
5566 @end example
5568 This common idiom is often programmed with a generic definition and an
5569 explicit body. The pragma makes it simpler to introduce such declarations.
5570 It incurs no overhead in compilation time or code size, because it is
5571 implemented as a single machine instruction.
5573 @item 
5574 General subprogram entities. This is used  to bind an Ada subprogram
5575 declaration to
5576 a compiler builtin by name with back-ends where such interfaces are
5577 available. A typical example is the set of @code{__builtin} functions
5578 exposed by the GCC back-end, as in the following example:
5580 @example
5581 function builtin_sqrt (F : Float) return Float;
5582 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5583 @end example
5585 Most of the GCC builtins are accessible this way, and as for other
5586 import conventions (e.g. C), it is the user’s responsibility to ensure
5587 that the Ada subprogram profile matches the underlying builtin
5588 expectations.
5589 @end itemize
5590 @end table
5592 @geindex Stdcall
5594 @geindex Convention Stdcall
5597 @table @asis
5599 @item @code{Stdcall}
5601 This is relevant only to Windows implementations of GNAT,
5602 and specifies that the @code{Stdcall} calling sequence will be used,
5603 as defined by the NT API. Nevertheless, to ease building
5604 cross-platform bindings this convention will be handled as a @code{C} calling
5605 convention on non-Windows platforms.
5606 @end table
5608 @geindex DLL
5610 @geindex Convention DLL
5613 @table @asis
5615 @item @code{DLL}
5617 This is equivalent to @code{Stdcall}.
5618 @end table
5620 @geindex Win32
5622 @geindex Convention Win32
5625 @table @asis
5627 @item @code{Win32}
5629 This is equivalent to @code{Stdcall}.
5630 @end table
5632 @geindex Stubbed
5634 @geindex Convention Stubbed
5637 @table @asis
5639 @item @code{Stubbed}
5641 This is a special convention that indicates that the compiler
5642 should provide a stub body that raises @code{Program_Error}.
5643 @end table
5645 GNAT additionally provides a useful pragma @code{Convention_Identifier}
5646 that can be used to parameterize conventions and allow additional synonyms
5647 to be specified. For example if you have legacy code in which the convention
5648 identifier Fortran77 was used for Fortran, you can use the configuration
5649 pragma:
5651 @example
5652 pragma Convention_Identifier (Fortran77, Fortran);
5653 @end example
5655 And from now on the identifier Fortran77 may be used as a convention
5656 identifier (for example in an @code{Import} pragma) with the same
5657 meaning as Fortran.
5659 @node Building Mixed Ada and C++ Programs,Partition-Wide Settings,Calling Conventions,Mixed Language Programming
5660 @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}
5661 @subsection Building Mixed Ada and C++ Programs
5664 A programmer inexperienced with mixed-language development may find that
5665 building an application containing both Ada and C++ code can be a
5666 challenge.  This section gives a few hints that should make this task easier.
5668 @menu
5669 * Interfacing to C++:: 
5670 * Linking a Mixed C++ & Ada Program:: 
5671 * A Simple Example:: 
5672 * Interfacing with C++ constructors:: 
5673 * Interfacing with C++ at the Class Level:: 
5675 @end menu
5677 @node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5678 @anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{a6}
5679 @subsubsection Interfacing to C++
5682 GNAT supports interfacing with the G++ compiler (or any C++ compiler
5683 generating code that is compatible with the G++ Application Binary
5684 Interface —see @indicateurl{http://itanium-cxx-abi.github.io/cxx-abi/abi.html}).
5686 Interfacing can be done at 3 levels: simple data, subprograms, and
5687 classes. In the first two cases, GNAT offers a specific @code{Convention C_Plus_Plus}
5688 (or @code{CPP}) that behaves exactly like @code{Convention C}.
5689 Usually, C++ mangles the names of subprograms. To generate proper mangled
5690 names automatically, see @ref{a7,,Generating Ada Bindings for C and C++ headers}).
5691 This problem can also be addressed manually in two ways:
5694 @itemize *
5696 @item 
5697 by modifying the C++ code in order to force a C convention using
5698 the @code{extern "C"} syntax.
5700 @item 
5701 by figuring out the mangled name (using e.g. @code{nm}) and using it as the
5702 Link_Name argument of the pragma import.
5703 @end itemize
5705 Interfacing at the class level can be achieved by using the GNAT specific
5706 pragmas such as @code{CPP_Constructor}.  See the @cite{GNAT_Reference_Manual} for additional information.
5708 @node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5709 @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}
5710 @subsubsection Linking a Mixed C++ & Ada Program
5713 Usually the linker of the C++ development system must be used to link
5714 mixed applications because most C++ systems will resolve elaboration
5715 issues (such as calling constructors on global class instances)
5716 transparently during the link phase. GNAT has been adapted to ease the
5717 use of a foreign linker for the last phase. Three cases can be
5718 considered:
5721 @itemize *
5723 @item 
5724 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5725 The C++ linker can simply be called by using the C++ specific driver
5726 called @code{g++}.
5728 Note that if the C++ code uses inline functions, you will need to
5729 compile your C++ code with the @code{-fkeep-inline-functions} switch in
5730 order to provide an existing function implementation that the Ada code can
5731 link with.
5733 @example
5734 $ g++ -c -fkeep-inline-functions file1.C
5735 $ g++ -c -fkeep-inline-functions file2.C
5736 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5737 @end example
5739 @item 
5740 Using GNAT and G++ from two different GCC installations: If both
5741 compilers are on the 
5742 @geindex PATH
5743 @geindex environment variable; PATH
5744 @code{PATH}, the previous method may be used. It is
5745 important to note that environment variables such as
5746 @geindex C_INCLUDE_PATH
5747 @geindex environment variable; C_INCLUDE_PATH
5748 @code{C_INCLUDE_PATH}, 
5749 @geindex GCC_EXEC_PREFIX
5750 @geindex environment variable; GCC_EXEC_PREFIX
5751 @code{GCC_EXEC_PREFIX},
5752 @geindex BINUTILS_ROOT
5753 @geindex environment variable; BINUTILS_ROOT
5754 @code{BINUTILS_ROOT}, and
5755 @geindex GCC_ROOT
5756 @geindex environment variable; GCC_ROOT
5757 @code{GCC_ROOT} will affect both compilers
5758 at the same time and may make one of the two compilers operate
5759 improperly if set during invocation of the wrong compiler.  It is also
5760 very important that the linker uses the proper @code{libgcc.a} GCC
5761 library – that is, the one from the C++ compiler installation. The
5762 implicit link command as suggested in the @code{gnatmake} command
5763 from the former example can be replaced by an explicit link command with
5764 the full-verbosity option in order to verify which library is used:
5766 @example
5767 $ gnatbind ada_unit
5768 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5769 @end example
5771 If there is a problem due to interfering environment variables, it can
5772 be worked around by using an intermediate script. The following example
5773 shows the proper script to use when GNAT has not been installed at its
5774 default location and g++ has been installed at its default location:
5776 @example
5777 $ cat ./my_script
5778 #!/bin/sh
5779 unset BINUTILS_ROOT
5780 unset GCC_ROOT
5781 c++ $*
5782 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5783 @end example
5785 @item 
5786 Using a non-GNU C++ compiler: The commands previously described can be
5787 used to insure that the C++ linker is used. Nonetheless, you need to add
5788 a few more parameters to the link command line, depending on the exception
5789 mechanism used.
5791 If the @code{setjmp} / @code{longjmp} exception mechanism is used, only the paths
5792 to the @code{libgcc} libraries are required:
5794 @example
5795 $ cat ./my_script
5796 #!/bin/sh
5797 CC $* gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a
5798 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5799 @end example
5801 where CC is the name of the non-GNU C++ compiler.
5803 If the “zero cost” exception mechanism is used, and the platform
5804 supports automatic registration of exception tables (e.g., Solaris),
5805 paths to more objects are required:
5807 @example
5808 $ cat ./my_script
5809 #!/bin/sh
5810 CC gcc -print-file-name=crtbegin.o $* \\
5811 gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a \\
5812 gcc -print-file-name=crtend.o
5813 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5814 @end example
5816 If the “zero cost exception” mechanism is used, and the platform
5817 doesn’t support automatic registration of exception tables (e.g., HP-UX
5818 or AIX), the simple approach described above will not work and
5819 a pre-linking phase using GNAT will be necessary.
5820 @end itemize
5822 Another alternative is to use the @code{gprbuild} multi-language builder
5823 which has a large knowledge base and knows how to link Ada and C++ code
5824 together automatically in most cases.
5826 @node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
5827 @anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{aa}@anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{ab}
5828 @subsubsection A Simple Example
5831 The following example, provided as part of the GNAT examples, shows how
5832 to achieve procedural interfacing between Ada and C++ in both
5833 directions. The C++ class A has two methods. The first method is exported
5834 to Ada by the means of an extern C wrapper function. The second method
5835 calls an Ada subprogram. On the Ada side, the C++ calls are modelled by
5836 a limited record with a layout comparable to the C++ class. The Ada
5837 subprogram, in turn, calls the C++ method. So, starting from the C++
5838 main program, the process passes back and forth between the two
5839 languages.
5841 Here are the compilation commands:
5843 @example
5844 $ gnatmake -c simple_cpp_interface
5845 $ g++ -c cpp_main.C
5846 $ g++ -c ex7.C
5847 $ gnatbind -n simple_cpp_interface
5848 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
5849 @end example
5851 Here are the corresponding sources:
5853 @example
5854 //cpp_main.C
5856 #include "ex7.h"
5858 extern "C" @{
5859   void adainit (void);
5860   void adafinal (void);
5861   void method1 (A *t);
5864 void method1 (A *t)
5866   t->method1 ();
5869 int main ()
5871   A obj;
5872   adainit ();
5873   obj.method2 (3030);
5874   adafinal ();
5876 @end example
5878 @example
5879 //ex7.h
5881 class Origin @{
5882  public:
5883   int o_value;
5885 class A : public Origin @{
5886  public:
5887   void method1 (void);
5888   void method2 (int v);
5889   A();
5890   int   a_value;
5892 @end example
5894 @example
5895 //ex7.C
5897 #include "ex7.h"
5898 #include <stdio.h>
5900 extern "C" @{ void ada_method2 (A *t, int v);@}
5902 void A::method1 (void)
5904   a_value = 2020;
5905   printf ("in A::method1, a_value = %d \\n",a_value);
5908 void A::method2 (int v)
5910    ada_method2 (this, v);
5911    printf ("in A::method2, a_value = %d \\n",a_value);
5914 A::A(void)
5916    a_value = 1010;
5917   printf ("in A::A, a_value = %d \\n",a_value);
5919 @end example
5921 @example
5922 -- simple_cpp_interface.ads
5923 with System;
5924 package Simple_Cpp_Interface is
5925    type A is limited
5926       record
5927          Vptr    : System.Address;
5928          O_Value : Integer;
5929          A_Value : Integer;
5930       end record;
5931    pragma Convention (C, A);
5933    procedure Method1 (This : in out A);
5934    pragma Import (C, Method1);
5936    procedure Ada_Method2 (This : in out A; V : Integer);
5937    pragma Export (C, Ada_Method2);
5939 end Simple_Cpp_Interface;
5940 @end example
5942 @example
5943 -- simple_cpp_interface.adb
5944 package body Simple_Cpp_Interface is
5946    procedure Ada_Method2 (This : in out A; V : Integer) is
5947    begin
5948       Method1 (This);
5949       This.A_Value := V;
5950    end Ada_Method2;
5952 end Simple_Cpp_Interface;
5953 @end example
5955 @node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
5956 @anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{ad}
5957 @subsubsection Interfacing with C++ constructors
5960 In order to interface with C++ constructors GNAT provides the
5961 @code{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
5962 for additional information).
5963 In this section we present some common uses of C++ constructors
5964 in mixed-languages programs in GNAT.
5966 Let us assume that we need to interface with the following
5967 C++ class:
5969 @example
5970 class Root @{
5971 public:
5972   int  a_value;
5973   int  b_value;
5974   virtual int Get_Value ();
5975   Root();              // Default constructor
5976   Root(int v);         // 1st non-default constructor
5977   Root(int v, int w);  // 2nd non-default constructor
5979 @end example
5981 For this purpose we can write the following package spec (further
5982 information on how to build this spec is available in
5983 @ref{ae,,Interfacing with C++ at the Class Level} and
5984 @ref{a7,,Generating Ada Bindings for C and C++ headers}).
5986 @example
5987 with Interfaces.C; use Interfaces.C;
5988 package Pkg_Root is
5989   type Root is tagged limited record
5990      A_Value : int;
5991      B_Value : int;
5992   end record;
5993   pragma Import (CPP, Root);
5995   function Get_Value (Obj : Root) return int;
5996   pragma Import (CPP, Get_Value);
5998   function Constructor return Root;
5999   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
6001   function Constructor (v : Integer) return Root;
6002   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
6004   function Constructor (v, w : Integer) return Root;
6005   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
6006 end Pkg_Root;
6007 @end example
6009 On the Ada side the constructor is represented by a function (whose
6010 name is arbitrary) that returns the classwide type corresponding to
6011 the imported C++ class. Although the constructor is described as a
6012 function, it is typically a procedure with an extra implicit argument
6013 (the object being initialized) at the implementation level. GNAT
6014 issues the appropriate call, whatever it is, to get the object
6015 properly initialized.
6017 Constructors can only appear in the following contexts:
6020 @itemize *
6022 @item 
6023 On the right side of an initialization of an object of type @code{T}.
6025 @item 
6026 On the right side of an initialization of a record component of type @code{T}.
6028 @item 
6029 In an Ada 2005 limited aggregate.
6031 @item 
6032 In an Ada 2005 nested limited aggregate.
6034 @item 
6035 In an Ada 2005 limited aggregate that initializes an object built in
6036 place by an extended return statement.
6037 @end itemize
6039 In a declaration of an object whose type is a class imported from C++,
6040 either the default C++ constructor is implicitly called by GNAT, or
6041 else the required C++ constructor must be explicitly called in the
6042 expression that initializes the object. For example:
6044 @example
6045 Obj1 : Root;
6046 Obj2 : Root := Constructor;
6047 Obj3 : Root := Constructor (v => 10);
6048 Obj4 : Root := Constructor (30, 40);
6049 @end example
6051 The first two declarations are equivalent: in both cases the default C++
6052 constructor is invoked (in the former case the call to the constructor is
6053 implicit, and in the latter case the call is explicit in the object
6054 declaration). @code{Obj3} is initialized by the C++ non-default constructor
6055 that takes an integer argument, and @code{Obj4} is initialized by the
6056 non-default C++ constructor that takes two integers.
6058 Let us derive the imported C++ class in the Ada side. For example:
6060 @example
6061 type DT is new Root with record
6062    C_Value : Natural := 2009;
6063 end record;
6064 @end example
6066 In this case the components DT inherited from the C++ side must be
6067 initialized by a C++ constructor, and the additional Ada components
6068 of type DT are initialized by GNAT. The initialization of such an
6069 object is done either by default, or by means of a function returning
6070 an aggregate of type DT, or by means of an extension aggregate.
6072 @example
6073 Obj5 : DT;
6074 Obj6 : DT := Function_Returning_DT (50);
6075 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6076 @end example
6078 The declaration of @code{Obj5} invokes the default constructors: the
6079 C++ default constructor of the parent type takes care of the initialization
6080 of the components inherited from Root, and GNAT takes care of the default
6081 initialization of the additional Ada components of type DT (that is,
6082 @code{C_Value} is initialized to value 2009). The order of invocation of
6083 the constructors is consistent with the order of elaboration required by
6084 Ada and C++. That is, the constructor of the parent type is always called
6085 before the constructor of the derived type.
6087 Let us now consider a record that has components whose type is imported
6088 from C++. For example:
6090 @example
6091 type Rec1 is limited record
6092    Data1 : Root := Constructor (10);
6093    Value : Natural := 1000;
6094 end record;
6096 type Rec2 (D : Integer := 20) is limited record
6097    Rec   : Rec1;
6098    Data2 : Root := Constructor (D, 30);
6099 end record;
6100 @end example
6102 The initialization of an object of type @code{Rec2} will call the
6103 non-default C++ constructors specified for the imported components.
6104 For example:
6106 @example
6107 Obj8 : Rec2 (40);
6108 @end example
6110 Using Ada 2005 we can use limited aggregates to initialize an object
6111 invoking C++ constructors that differ from those specified in the type
6112 declarations. For example:
6114 @example
6115 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6116                         others => <>),
6117                 others => <>);
6118 @end example
6120 The above declaration uses an Ada 2005 limited aggregate to
6121 initialize @code{Obj9}, and the C++ constructor that has two integer
6122 arguments is invoked to initialize the @code{Data1} component instead
6123 of the constructor specified in the declaration of type @code{Rec1}. In
6124 Ada 2005 the box in the aggregate indicates that unspecified components
6125 are initialized using the expression (if any) available in the component
6126 declaration. That is, in this case discriminant @code{D} is initialized
6127 to value @code{20}, @code{Value} is initialized to value 1000, and the
6128 non-default C++ constructor that handles two integers takes care of
6129 initializing component @code{Data2} with values @code{20,30}.
6131 In Ada 2005 we can use the extended return statement to build the Ada
6132 equivalent to C++ non-default constructors. For example:
6134 @example
6135 function Constructor (V : Integer) return Rec2 is
6136 begin
6137    return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
6138                                  others => <>),
6139                          others => <>) do
6140       --  Further actions required for construction of
6141       --  objects of type Rec2
6142       ...
6143    end record;
6144 end Constructor;
6145 @end example
6147 In this example the extended return statement construct is used to
6148 build in place the returned object whose components are initialized
6149 by means of a limited aggregate. Any further action associated with
6150 the constructor can be placed inside the construct.
6152 @node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6153 @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}
6154 @subsubsection Interfacing with C++ at the Class Level
6157 In this section we demonstrate the GNAT features for interfacing with
6158 C++ by means of an example making use of Ada 2005 abstract interface
6159 types. This example consists of a classification of animals; classes
6160 have been used to model our main classification of animals, and
6161 interfaces provide support for the management of secondary
6162 classifications. We first demonstrate a case in which the types and
6163 constructors are defined on the C++ side and imported from the Ada
6164 side, and latter the reverse case.
6166 The root of our derivation will be the @code{Animal} class, with a
6167 single private attribute (the @code{Age} of the animal), a constructor,
6168 and two public primitives to set and get the value of this attribute.
6170 @example
6171 class Animal @{
6172  public:
6173    virtual void Set_Age (int New_Age);
6174    virtual int Age ();
6175    Animal() @{Age_Count = 0;@};
6176  private:
6177    int Age_Count;
6179 @end example
6181 Abstract interface types are defined in C++ by means of classes with pure
6182 virtual functions and no data members. In our example we will use two
6183 interfaces that provide support for the common management of @code{Carnivore}
6184 and @code{Domestic} animals:
6186 @example
6187 class Carnivore @{
6188 public:
6189    virtual int Number_Of_Teeth () = 0;
6192 class Domestic @{
6193 public:
6194    virtual void Set_Owner (char* Name) = 0;
6196 @end example
6198 Using these declarations, we can now say that a @code{Dog} is an animal that is
6199 both Carnivore and Domestic, that is:
6201 @example
6202 class Dog : Animal, Carnivore, Domestic @{
6203  public:
6204    virtual int  Number_Of_Teeth ();
6205    virtual void Set_Owner (char* Name);
6207    Dog(); // Constructor
6208  private:
6209    int  Tooth_Count;
6210    char *Owner;
6212 @end example
6214 In the following examples we will assume that the previous declarations are
6215 located in a file named @code{animals.h}. The following package demonstrates
6216 how to import these C++ declarations from the Ada side:
6218 @example
6219 with Interfaces.C.Strings; use Interfaces.C.Strings;
6220 package Animals is
6221   type Carnivore is limited interface;
6222   pragma Convention (C_Plus_Plus, Carnivore);
6223   function Number_Of_Teeth (X : Carnivore)
6224      return Natural is abstract;
6226   type Domestic is limited interface;
6227   pragma Convention (C_Plus_Plus, Domestic);
6228   procedure Set_Owner
6229     (X    : in out Domestic;
6230      Name : Chars_Ptr) is abstract;
6232   type Animal is tagged limited record
6233     Age : Natural;
6234   end record;
6235   pragma Import (C_Plus_Plus, Animal);
6237   procedure Set_Age (X : in out Animal; Age : Integer);
6238   pragma Import (C_Plus_Plus, Set_Age);
6240   function Age (X : Animal) return Integer;
6241   pragma Import (C_Plus_Plus, Age);
6243   function New_Animal return Animal;
6244   pragma CPP_Constructor (New_Animal);
6245   pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6247   type Dog is new Animal and Carnivore and Domestic with record
6248     Tooth_Count : Natural;
6249     Owner       : Chars_Ptr;
6250   end record;
6251   pragma Import (C_Plus_Plus, Dog);
6253   function Number_Of_Teeth (A : Dog) return Natural;
6254   pragma Import (C_Plus_Plus, Number_Of_Teeth);
6256   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6257   pragma Import (C_Plus_Plus, Set_Owner);
6259   function New_Dog return Dog;
6260   pragma CPP_Constructor (New_Dog);
6261   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6262 end Animals;
6263 @end example
6265 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6266 interfacing with these C++ classes is easy. The only requirement is that all
6267 the primitives and components must be declared exactly in the same order in
6268 the two languages.
6270 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6271 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
6272 the arguments to the called primitives will be the same as for C++. For the
6273 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
6274 to indicate that they have been defined on the C++ side; this is required
6275 because the dispatch table associated with these tagged types will be built
6276 in the C++ side and therefore will not contain the predefined Ada primitives
6277 which Ada would otherwise expect.
6279 As the reader can see there is no need to indicate the C++ mangled names
6280 associated with each subprogram because it is assumed that all the calls to
6281 these primitives will be dispatching calls. The only exception is the
6282 constructor, which must be registered with the compiler by means of
6283 @code{pragma CPP_Constructor} and needs to provide its associated C++
6284 mangled name because the Ada compiler generates direct calls to it.
6286 With the above packages we can now declare objects of type Dog on the Ada side
6287 and dispatch calls to the corresponding subprograms on the C++ side. We can
6288 also extend the tagged type Dog with further fields and primitives, and
6289 override some of its C++ primitives on the Ada side. For example, here we have
6290 a type derivation defined on the Ada side that inherits all the dispatching
6291 primitives of the ancestor from the C++ side.
6293 @example
6294 with Animals; use Animals;
6295 package Vaccinated_Animals is
6296   type Vaccinated_Dog is new Dog with null record;
6297   function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6298 end Vaccinated_Animals;
6299 @end example
6301 It is important to note that, because of the ABI compatibility, the programmer
6302 does not need to add any further information to indicate either the object
6303 layout or the dispatch table entry associated with each dispatching operation.
6305 Now let us define all the types and constructors on the Ada side and export
6306 them to C++, using the same hierarchy of our previous example:
6308 @example
6309 with Interfaces.C.Strings;
6310 use Interfaces.C.Strings;
6311 package Animals is
6312   type Carnivore is limited interface;
6313   pragma Convention (C_Plus_Plus, Carnivore);
6314   function Number_Of_Teeth (X : Carnivore)
6315      return Natural is abstract;
6317   type Domestic is limited interface;
6318   pragma Convention (C_Plus_Plus, Domestic);
6319   procedure Set_Owner
6320     (X    : in out Domestic;
6321      Name : Chars_Ptr) is abstract;
6323   type Animal is tagged record
6324     Age : Natural;
6325   end record;
6326   pragma Convention (C_Plus_Plus, Animal);
6328   procedure Set_Age (X : in out Animal; Age : Integer);
6329   pragma Export (C_Plus_Plus, Set_Age);
6331   function Age (X : Animal) return Integer;
6332   pragma Export (C_Plus_Plus, Age);
6334   function New_Animal return Animal'Class;
6335   pragma Export (C_Plus_Plus, New_Animal);
6337   type Dog is new Animal and Carnivore and Domestic with record
6338     Tooth_Count : Natural;
6339     Owner       : String (1 .. 30);
6340   end record;
6341   pragma Convention (C_Plus_Plus, Dog);
6343   function Number_Of_Teeth (A : Dog) return Natural;
6344   pragma Export (C_Plus_Plus, Number_Of_Teeth);
6346   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6347   pragma Export (C_Plus_Plus, Set_Owner);
6349   function New_Dog return Dog'Class;
6350   pragma Export (C_Plus_Plus, New_Dog);
6351 end Animals;
6352 @end example
6354 Compared with our previous example the only differences are the use of
6355 @code{pragma Convention} (instead of @code{pragma Import}), and the use of
6356 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
6357 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6358 nothing else to be done; as explained above, the only requirement is that all
6359 the primitives and components are declared in exactly the same order.
6361 For completeness, let us see a brief C++ main program that uses the
6362 declarations available in @code{animals.h} (presented in our first example) to
6363 import and use the declarations from the Ada side, properly initializing and
6364 finalizing the Ada run-time system along the way:
6366 @example
6367 #include "animals.h"
6368 #include <iostream>
6369 using namespace std;
6371 void Check_Carnivore (Carnivore *obj) @{...@}
6372 void Check_Domestic (Domestic *obj)   @{...@}
6373 void Check_Animal (Animal *obj)       @{...@}
6374 void Check_Dog (Dog *obj)             @{...@}
6376 extern "C" @{
6377   void adainit (void);
6378   void adafinal (void);
6379   Dog* new_dog ();
6382 void test ()
6384   Dog *obj = new_dog();  // Ada constructor
6385   Check_Carnivore (obj); // Check secondary DT
6386   Check_Domestic (obj);  // Check secondary DT
6387   Check_Animal (obj);    // Check primary DT
6388   Check_Dog (obj);       // Check primary DT
6391 int main ()
6393   adainit ();  test();  adafinal ();
6394   return 0;
6396 @end example
6398 @node Partition-Wide Settings,Generating Ada Bindings for C and C++ headers,Building Mixed Ada and C++ Programs,Mixed Language Programming
6399 @anchor{gnat_ugn/the_gnat_compilation_model id70}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model partition-wide-settings}@anchor{b1}
6400 @subsection Partition-Wide Settings
6403 When building a mixed-language application it is important to be aware that
6404 Ada enforces some partition-wide settings that may implicitly impact the
6405 behavior of the other languages.
6407 This is the case of certain signals that are reserved to the
6408 implementation to implement proper Ada semantics (such as the behavior
6409 of @code{abort} statements).
6411 It means that the Ada part of the application may override signal handlers
6412 that were previously installed by either the system or by other user code.
6414 If your application requires that either system or user signals be preserved
6415 then you need to instruct the Ada part not to install its own signal handler.
6416 This is done using @code{pragma Interrupt_State} that provides a general
6417 mechanism for overriding such uses of interrupts.
6419 The set of interrupts for which the Ada run-time library sets a specific signal
6420 handler is the following:
6423 @itemize *
6425 @item 
6426 Ada.Interrupts.Names.SIGSEGV
6428 @item 
6429 Ada.Interrupts.Names.SIGBUS
6431 @item 
6432 Ada.Interrupts.Names.SIGFPE
6434 @item 
6435 Ada.Interrupts.Names.SIGILL
6437 @item 
6438 Ada.Interrupts.Names.SIGABRT
6439 @end itemize
6441 The run-time library can be instructed not to install its signal handler for a
6442 particular signal by using the configuration pragma @code{Interrupt_State} in the
6443 Ada code. For example:
6445 @example
6446 pragma Interrupt_State (Ada.Interrupts.Names.SIGSEGV, System);
6447 pragma Interrupt_State (Ada.Interrupts.Names.SIGBUS,  System);
6448 pragma Interrupt_State (Ada.Interrupts.Names.SIGFPE,  System);
6449 pragma Interrupt_State (Ada.Interrupts.Names.SIGILL,  System);
6450 pragma Interrupt_State (Ada.Interrupts.Names.SIGABRT, System);
6451 @end example
6453 Obviously, if the Ada run-time system cannot set these handlers it comes with the
6454 drawback of not fully preserving Ada semantics. @code{SIGSEGV}, @code{SIGBUS}, @code{SIGFPE}
6455 and @code{SIGILL} are used to raise corresponding Ada exceptions in the application,
6456 while @code{SIGABRT} is used to asynchronously abort an action or a task.
6458 @node Generating Ada Bindings for C and C++ headers,Generating C Headers for Ada Specifications,Partition-Wide Settings,Mixed Language Programming
6459 @anchor{gnat_ugn/the_gnat_compilation_model generating-ada-bindings-for-c-and-c-headers}@anchor{a7}@anchor{gnat_ugn/the_gnat_compilation_model id71}@anchor{b2}
6460 @subsection Generating Ada Bindings for C and C++ headers
6463 @geindex Binding generation (for C and C++ headers)
6465 @geindex C headers (binding generation)
6467 @geindex C++ headers (binding generation)
6469 GNAT includes a binding generator for C and C++ headers which is
6470 intended to do 95% of the tedious work of generating Ada specs from C
6471 or C++ header files.
6473 Note that this capability is not intended to generate 100% correct Ada specs,
6474 and will is some cases require manual adjustments, although it can often
6475 be used out of the box in practice.
6477 Some of the known limitations include:
6480 @itemize *
6482 @item 
6483 only very simple character constant macros are translated into Ada
6484 constants. Function macros (macros with arguments) are partially translated
6485 as comments, to be completed manually if needed.
6487 @item 
6488 some extensions (e.g. vector types) are not supported
6490 @item 
6491 pointers to pointers are mapped to System.Address
6493 @item 
6494 identifiers with identical name (except casing) may generate compilation
6495 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
6496 @end itemize
6498 The code is generated using Ada 2012 syntax, which makes it easier to interface
6499 with other languages. In most cases you can still use the generated binding
6500 even if your code is compiled using earlier versions of Ada (e.g. @code{-gnat95}).
6502 @menu
6503 * Running the Binding Generator:: 
6504 * Generating Bindings for C++ Headers:: 
6505 * Switches:: 
6507 @end menu
6509 @node Running the Binding Generator,Generating Bindings for C++ Headers,,Generating Ada Bindings for C and C++ headers
6510 @anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{b3}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{b4}
6511 @subsubsection Running the Binding Generator
6514 The binding generator is part of the @code{gcc} compiler and can be
6515 invoked via the @code{-fdump-ada-spec} switch, which will generate Ada
6516 spec files for the header files specified on the command line, and all
6517 header files needed by these files transitively. For example:
6519 @example
6520 $ gcc -c -fdump-ada-spec -C /usr/include/time.h
6521 $ gcc -c *.ads
6522 @end example
6524 will generate, under GNU/Linux, the following files: @code{time_h.ads},
6525 @code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6526 correspond to the files @code{/usr/include/time.h},
6527 @code{/usr/include/bits/time.h}, etc…, and then compile these Ada specs.
6528 That is to say, the name of the Ada specs is in keeping with the relative path
6529 under @code{/usr/include/} of the header files. This behavior is specific to
6530 paths ending with @code{/include/}; in all the other cases, the name of the
6531 Ada specs is derived from the simple name of the header files instead.
6533 The @code{-C} switch tells @code{gcc} to extract comments from headers,
6534 and will attempt to generate corresponding Ada comments.
6536 If you want to generate a single Ada file and not the transitive closure, you
6537 can use instead the @code{-fdump-ada-spec-slim} switch.
6539 You can optionally specify a parent unit, of which all generated units will
6540 be children, using @code{-fada-spec-parent=`unit'}.
6542 The simple @code{gcc}-based command works only for C headers. For C++ headers
6543 you need to use either the @code{g++} command or the combination @code{gcc -x c++}.
6545 In some cases, the generated bindings will be more complete or more meaningful
6546 when defining some macros, which you can do via the @code{-D} switch. This
6547 is for example the case with @code{Xlib.h} under GNU/Linux:
6549 @example
6550 $ gcc -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6551 @end example
6553 The above will generate more complete bindings than a straight call without
6554 the @code{-DXLIB_ILLEGAL_ACCESS} switch.
6556 In other cases, it is not possible to parse a header file in a stand-alone
6557 manner, because other include files need to be included first. In this
6558 case, the solution is to create a small header file including the needed
6559 @code{#include} and possible @code{#define} directives. For example, to
6560 generate Ada bindings for @code{readline/readline.h}, you need to first
6561 include @code{stdio.h}, so you can create a file with the following two
6562 lines in e.g. @code{readline1.h}:
6564 @example
6565 #include <stdio.h>
6566 #include <readline/readline.h>
6567 @end example
6569 and then generate Ada bindings from this file:
6571 @example
6572 $ gcc -c -fdump-ada-spec readline1.h
6573 @end example
6575 @node Generating Bindings for C++ Headers,Switches,Running the Binding Generator,Generating Ada Bindings for C and C++ headers
6576 @anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{b5}@anchor{gnat_ugn/the_gnat_compilation_model id73}@anchor{b6}
6577 @subsubsection Generating Bindings for C++ Headers
6580 Generating bindings for C++ headers is done using the same options, always
6581 with the `g++' compiler. Note that generating Ada spec from C++ headers is a
6582 much more complex job and support for C++ headers is much more limited that
6583 support for C headers. As a result, you will need to modify the resulting
6584 bindings by hand more extensively when using C++ headers.
6586 In this mode, C++ classes will be mapped to Ada tagged types, constructors
6587 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
6588 multiple inheritance of abstract classes will be mapped to Ada interfaces
6589 (see the `Interfacing to C++' section in the @cite{GNAT Reference Manual}
6590 for additional information on interfacing to C++).
6592 For example, given the following C++ header file:
6594 @example
6595 class Carnivore @{
6596 public:
6597    virtual int Number_Of_Teeth () = 0;
6600 class Domestic @{
6601 public:
6602    virtual void Set_Owner (char* Name) = 0;
6605 class Animal @{
6606 public:
6607   int Age_Count;
6608   virtual void Set_Age (int New_Age);
6611 class Dog : Animal, Carnivore, Domestic @{
6612  public:
6613   int  Tooth_Count;
6614   char *Owner;
6616   virtual int  Number_Of_Teeth ();
6617   virtual void Set_Owner (char* Name);
6619   Dog();
6621 @end example
6623 The corresponding Ada code is generated:
6625 @example
6626 package Class_Carnivore is
6627   type Carnivore is limited interface;
6628   pragma Import (CPP, Carnivore);
6630   function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6631 end;
6632 use Class_Carnivore;
6634 package Class_Domestic is
6635   type Domestic is limited interface;
6636   pragma Import (CPP, Domestic);
6638   procedure Set_Owner
6639     (this : access Domestic;
6640      Name : Interfaces.C.Strings.chars_ptr) is abstract;
6641 end;
6642 use Class_Domestic;
6644 package Class_Animal is
6645   type Animal is tagged limited record
6646     Age_Count : aliased int;
6647   end record;
6648   pragma Import (CPP, Animal);
6650   procedure Set_Age (this : access Animal; New_Age : int);
6651   pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6652 end;
6653 use Class_Animal;
6655 package Class_Dog is
6656   type Dog is new Animal and Carnivore and Domestic with record
6657     Tooth_Count : aliased int;
6658     Owner : Interfaces.C.Strings.chars_ptr;
6659   end record;
6660   pragma Import (CPP, Dog);
6662   function Number_Of_Teeth (this : access Dog) return int;
6663   pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6665   procedure Set_Owner
6666     (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6667   pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6669   function New_Dog return Dog;
6670   pragma CPP_Constructor (New_Dog);
6671   pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6672 end;
6673 use Class_Dog;
6674 @end example
6676 @node Switches,,Generating Bindings for C++ Headers,Generating Ada Bindings for C and C++ headers
6677 @anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{b7}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{b8}
6678 @subsubsection Switches
6681 @geindex -fdump-ada-spec (gcc)
6684 @table @asis
6686 @item @code{-fdump-ada-spec}
6688 Generate Ada spec files for the given header files transitively (including
6689 all header files that these headers depend upon).
6690 @end table
6692 @geindex -fdump-ada-spec-slim (gcc)
6695 @table @asis
6697 @item @code{-fdump-ada-spec-slim}
6699 Generate Ada spec files for the header files specified on the command line
6700 only.
6701 @end table
6703 @geindex -fada-spec-parent (gcc)
6706 @table @asis
6708 @item @code{-fada-spec-parent=`unit'}
6710 Specifies that all files generated by @code{-fdump-ada-spec} are
6711 to be child units of the specified parent unit.
6712 @end table
6714 @geindex -C (gcc)
6717 @table @asis
6719 @item @code{-C}
6721 Extract comments from headers and generate Ada comments in the Ada spec files.
6722 @end table
6724 @node Generating C Headers for Ada Specifications,,Generating Ada Bindings for C and C++ headers,Mixed Language Programming
6725 @anchor{gnat_ugn/the_gnat_compilation_model generating-c-headers-for-ada-specifications}@anchor{b9}@anchor{gnat_ugn/the_gnat_compilation_model id74}@anchor{ba}
6726 @subsection Generating C Headers for Ada Specifications
6729 @geindex Binding generation (for Ada specs)
6731 @geindex C headers (binding generation)
6733 GNAT includes a C header generator for Ada specifications which supports
6734 Ada types that have a direct mapping to C types. This includes in particular
6735 support for:
6738 @itemize *
6740 @item 
6741 Scalar types
6743 @item 
6744 Constrained arrays
6746 @item 
6747 Records (untagged)
6749 @item 
6750 Composition of the above types
6752 @item 
6753 Constant declarations
6755 @item 
6756 Object declarations
6758 @item 
6759 Subprogram declarations
6760 @end itemize
6762 @menu
6763 * Running the C Header Generator:: 
6765 @end menu
6767 @node Running the C Header Generator,,,Generating C Headers for Ada Specifications
6768 @anchor{gnat_ugn/the_gnat_compilation_model running-the-c-header-generator}@anchor{bb}
6769 @subsubsection Running the C Header Generator
6772 The C header generator is part of the GNAT compiler and can be invoked via
6773 the @code{-gnatceg} combination of switches, which will generate a @code{.h}
6774 file corresponding to the given input file (Ada spec or body). Note that
6775 only spec files are processed in any case, so giving a spec or a body file
6776 as input is equivalent. For example:
6778 @example
6779 $ gcc -c -gnatceg pack1.ads
6780 @end example
6782 will generate a self-contained file called @code{pack1.h} including
6783 common definitions from the Ada Standard package, followed by the
6784 definitions included in @code{pack1.ads}, as well as all the other units
6785 withed by this file.
6787 For instance, given the following Ada files:
6789 @example
6790 package Pack2 is
6791    type Int is range 1 .. 10;
6792 end Pack2;
6793 @end example
6795 @example
6796 with Pack2;
6798 package Pack1 is
6799    type Rec is record
6800       Field1, Field2 : Pack2.Int;
6801    end record;
6803    Global : Rec := (1, 2);
6805    procedure Proc1 (R : Rec);
6806    procedure Proc2 (R : in out Rec);
6807 end Pack1;
6808 @end example
6810 The above @code{gcc} command will generate the following @code{pack1.h} file:
6812 @example
6813 /* Standard definitions skipped */
6814 #ifndef PACK2_ADS
6815 #define PACK2_ADS
6816 typedef short_short_integer pack2__TintB;
6817 typedef pack2__TintB pack2__int;
6818 #endif /* PACK2_ADS */
6820 #ifndef PACK1_ADS
6821 #define PACK1_ADS
6822 typedef struct _pack1__rec @{
6823   pack2__int field1;
6824   pack2__int field2;
6825 @} pack1__rec;
6826 extern pack1__rec pack1__global;
6827 extern void pack1__proc1(const pack1__rec r);
6828 extern void pack1__proc2(pack1__rec *r);
6829 #endif /* PACK1_ADS */
6830 @end example
6832 You can then @code{include} @code{pack1.h} from a C source file and use the types,
6833 call subprograms, reference objects, and constants.
6835 @node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
6836 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{2d}@anchor{gnat_ugn/the_gnat_compilation_model id75}@anchor{bc}
6837 @section GNAT and Other Compilation Models
6840 This section compares the GNAT model with the approaches taken in
6841 other environments, first the C/C++ model and then the mechanism that
6842 has been used in other Ada systems, in particular those traditionally
6843 used for Ada 83.
6845 @menu
6846 * Comparison between GNAT and C/C++ Compilation Models:: 
6847 * Comparison between GNAT and Conventional Ada Library Models:: 
6849 @end menu
6851 @node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
6852 @anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-c-c-compilation-models}@anchor{bd}@anchor{gnat_ugn/the_gnat_compilation_model id76}@anchor{be}
6853 @subsection Comparison between GNAT and C/C++ Compilation Models
6856 The GNAT model of compilation is close to the C and C++ models. You can
6857 think of Ada specs as corresponding to header files in C. As in C, you
6858 don’t need to compile specs; they are compiled when they are used. The
6859 Ada `with' is similar in effect to the @code{#include} of a C
6860 header.
6862 One notable difference is that, in Ada, you may compile specs separately
6863 to check them for semantic and syntactic accuracy. This is not always
6864 possible with C headers because they are fragments of programs that have
6865 less specific syntactic or semantic rules.
6867 The other major difference is the requirement for running the binder,
6868 which performs two important functions. First, it checks for
6869 consistency. In C or C++, the only defense against assembling
6870 inconsistent programs lies outside the compiler, in a makefile, for
6871 example. The binder satisfies the Ada requirement that it be impossible
6872 to construct an inconsistent program when the compiler is used in normal
6873 mode.
6875 @geindex Elaboration order control
6877 The other important function of the binder is to deal with elaboration
6878 issues. There are also elaboration issues in C++ that are handled
6879 automatically. This automatic handling has the advantage of being
6880 simpler to use, but the C++ programmer has no control over elaboration.
6881 Where @code{gnatbind} might complain there was no valid order of
6882 elaboration, a C++ compiler would simply construct a program that
6883 malfunctioned at run time.
6885 @node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
6886 @anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-conventional-ada-library-models}@anchor{bf}@anchor{gnat_ugn/the_gnat_compilation_model id77}@anchor{c0}
6887 @subsection Comparison between GNAT and Conventional Ada Library Models
6890 This section is intended for Ada programmers who have
6891 used an Ada compiler implementing the traditional Ada library
6892 model, as described in the Ada Reference Manual.
6894 @geindex GNAT library
6896 In GNAT, there is no ‘library’ in the normal sense. Instead, the set of
6897 source files themselves acts as the library. Compiling Ada programs does
6898 not generate any centralized information, but rather an object file and
6899 a ALI file, which are of interest only to the binder and linker.
6900 In a traditional system, the compiler reads information not only from
6901 the source file being compiled, but also from the centralized library.
6902 This means that the effect of a compilation depends on what has been
6903 previously compiled. In particular:
6906 @itemize *
6908 @item 
6909 When a unit is `with'ed, the unit seen by the compiler corresponds
6910 to the version of the unit most recently compiled into the library.
6912 @item 
6913 Inlining is effective only if the necessary body has already been
6914 compiled into the library.
6916 @item 
6917 Compiling a unit may obsolete other units in the library.
6918 @end itemize
6920 In GNAT, compiling one unit never affects the compilation of any other
6921 units because the compiler reads only source files. Only changes to source
6922 files can affect the results of a compilation. In particular:
6925 @itemize *
6927 @item 
6928 When a unit is `with'ed, the unit seen by the compiler corresponds
6929 to the source version of the unit that is currently accessible to the
6930 compiler.
6932 @geindex Inlining
6934 @item 
6935 Inlining requires the appropriate source files for the package or
6936 subprogram bodies to be available to the compiler. Inlining is always
6937 effective, independent of the order in which units are compiled.
6939 @item 
6940 Compiling a unit never affects any other compilations. The editing of
6941 sources may cause previous compilations to be out of date if they
6942 depended on the source file being modified.
6943 @end itemize
6945 The most important result of these differences is that order of compilation
6946 is never significant in GNAT. There is no situation in which one is
6947 required to do one compilation before another. What shows up as order of
6948 compilation requirements in the traditional Ada library becomes, in
6949 GNAT, simple source dependencies; in other words, there is only a set
6950 of rules saying what source files must be present when a file is
6951 compiled.
6953 @node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
6954 @anchor{gnat_ugn/the_gnat_compilation_model id78}@anchor{c1}@anchor{gnat_ugn/the_gnat_compilation_model using-gnat-files-with-external-tools}@anchor{2e}
6955 @section Using GNAT Files with External Tools
6958 This section explains how files that are produced by GNAT may be
6959 used with tools designed for other languages.
6961 @menu
6962 * Using Other Utility Programs with GNAT:: 
6963 * The External Symbol Naming Scheme of GNAT:: 
6965 @end menu
6967 @node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
6968 @anchor{gnat_ugn/the_gnat_compilation_model id79}@anchor{c2}@anchor{gnat_ugn/the_gnat_compilation_model using-other-utility-programs-with-gnat}@anchor{c3}
6969 @subsection Using Other Utility Programs with GNAT
6972 The object files generated by GNAT are in standard system format and in
6973 particular the debugging information uses this format. This means
6974 programs generated by GNAT can be used with existing utilities that
6975 depend on these formats.
6977 In general, any utility program that works with C will also often work with
6978 Ada programs generated by GNAT. This includes software utilities such as
6979 gprof (a profiling program), gdb (the FSF debugger), and utilities such
6980 as Purify.
6982 @node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
6983 @anchor{gnat_ugn/the_gnat_compilation_model id80}@anchor{c4}@anchor{gnat_ugn/the_gnat_compilation_model the-external-symbol-naming-scheme-of-gnat}@anchor{c5}
6984 @subsection The External Symbol Naming Scheme of GNAT
6987 In order to interpret the output from GNAT, when using tools that are
6988 originally intended for use with other languages, it is useful to
6989 understand the conventions used to generate link names from the Ada
6990 entity names.
6992 All link names are in all lowercase letters. With the exception of library
6993 procedure names, the mechanism used is simply to use the full expanded
6994 Ada name with dots replaced by double underscores. For example, suppose
6995 we have the following package spec:
6997 @example
6998 package QRS is
6999    MN : Integer;
7000 end QRS;
7001 @end example
7003 @geindex pragma Export
7005 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
7006 the corresponding link name is @code{qrs__mn}.
7007 Of course if a @code{pragma Export} is used this may be overridden:
7009 @example
7010 package Exports is
7011    Var1 : Integer;
7012    pragma Export (Var1, C, External_Name => "var1_name");
7013    Var2 : Integer;
7014    pragma Export (Var2, C, Link_Name => "var2_link_name");
7015 end Exports;
7016 @end example
7018 In this case, the link name for @code{Var1} is whatever link name the
7019 C compiler would assign for the C function @code{var1_name}. This typically
7020 would be either @code{var1_name} or @code{_var1_name}, depending on operating
7021 system conventions, but other possibilities exist. The link name for
7022 @code{Var2} is @code{var2_link_name}, and this is not operating system
7023 dependent.
7025 One exception occurs for library level procedures. A potential ambiguity
7026 arises between the required name @code{_main} for the C main program,
7027 and the name we would otherwise assign to an Ada library level procedure
7028 called @code{Main} (which might well not be the main program).
7030 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
7031 names. So if we have a library level procedure such as:
7033 @example
7034 procedure Hello (S : String);
7035 @end example
7037 the external name of this procedure will be @code{_ada_hello}.
7039 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7041 @node Building Executable Programs with GNAT,GNAT Utility Programs,The GNAT Compilation Model,Top
7042 @anchor{gnat_ugn/building_executable_programs_with_gnat doc}@anchor{c6}@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{c7}
7043 @chapter Building Executable Programs with GNAT
7046 This chapter describes first the gnatmake tool
7047 (@ref{c8,,Building with gnatmake}),
7048 which automatically determines the set of sources
7049 needed by an Ada compilation unit and executes the necessary
7050 (re)compilations, binding and linking.
7051 It also explains how to use each tool individually: the
7052 compiler (gcc, see @ref{c9,,Compiling with gcc}),
7053 binder (gnatbind, see @ref{ca,,Binding with gnatbind}),
7054 and linker (gnatlink, see @ref{cb,,Linking with gnatlink})
7055 to build executable programs.
7056 Finally, this chapter provides examples of
7057 how to make use of the general GNU make mechanism
7058 in a GNAT context (see @ref{70,,Using the GNU make Utility}).
7061 @menu
7062 * Building with gnatmake:: 
7063 * Compiling with gcc:: 
7064 * Compiler Switches:: 
7065 * Linker Switches:: 
7066 * Binding with gnatbind:: 
7067 * Linking with gnatlink:: 
7068 * Using the GNU make Utility:: 
7070 @end menu
7072 @node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7073 @anchor{gnat_ugn/building_executable_programs_with_gnat building-with-gnatmake}@anchor{cc}@anchor{gnat_ugn/building_executable_programs_with_gnat the-gnat-make-program-gnatmake}@anchor{c8}
7074 @section Building with @code{gnatmake}
7077 @geindex gnatmake
7079 A typical development cycle when working on an Ada program consists of
7080 the following steps:
7083 @enumerate 
7085 @item 
7086 Edit some sources to fix bugs;
7088 @item 
7089 Add enhancements;
7091 @item 
7092 Compile all sources affected;
7094 @item 
7095 Rebind and relink; and
7097 @item 
7098 Test.
7099 @end enumerate
7101 @geindex Dependency rules (compilation)
7103 The third step in particular can be tricky, because not only do the modified
7104 files have to be compiled, but any files depending on these files must also be
7105 recompiled. The dependency rules in Ada can be quite complex, especially
7106 in the presence of overloading, @code{use} clauses, generics and inlined
7107 subprograms.
7109 @code{gnatmake} automatically takes care of the third and fourth steps
7110 of this process. It determines which sources need to be compiled,
7111 compiles them, and binds and links the resulting object files.
7113 Unlike some other Ada make programs, the dependencies are always
7114 accurately recomputed from the new sources. The source based approach of
7115 the GNAT compilation model makes this possible. This means that if
7116 changes to the source program cause corresponding changes in
7117 dependencies, they will always be tracked exactly correctly by
7118 @code{gnatmake}.
7120 Note that for advanced forms of project structure, we recommend creating
7121 a project file as explained in the `GNAT_Project_Manager' chapter in the
7122 `GPRbuild User’s Guide', and using the
7123 @code{gprbuild} tool which supports building with project files and works similarly
7124 to @code{gnatmake}.
7126 @menu
7127 * Running gnatmake:: 
7128 * Switches for gnatmake:: 
7129 * Mode Switches for gnatmake:: 
7130 * Notes on the Command Line:: 
7131 * How gnatmake Works:: 
7132 * Examples of gnatmake Usage:: 
7134 @end menu
7136 @node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7137 @anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{cd}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{ce}
7138 @subsection Running @code{gnatmake}
7141 The usual form of the @code{gnatmake} command is
7143 @example
7144 $ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7145 @end example
7147 The only required argument is one @code{file_name}, which specifies
7148 a compilation unit that is a main program. Several @code{file_names} can be
7149 specified: this will result in several executables being built.
7150 If @code{switches} are present, they can be placed before the first
7151 @code{file_name}, between @code{file_names} or after the last @code{file_name}.
7152 If @code{mode_switches} are present, they must always be placed after
7153 the last @code{file_name} and all @code{switches}.
7155 If you are using standard file extensions (@code{.adb} and
7156 @code{.ads}), then the
7157 extension may be omitted from the @code{file_name} arguments. However, if
7158 you are using non-standard extensions, then it is required that the
7159 extension be given. A relative or absolute directory path can be
7160 specified in a @code{file_name}, in which case, the input source file will
7161 be searched for in the specified directory only. Otherwise, the input
7162 source file will first be searched in the directory where
7163 @code{gnatmake} was invoked and if it is not found, it will be search on
7164 the source path of the compiler as described in
7165 @ref{73,,Search Paths and the Run-Time Library (RTL)}.
7167 All @code{gnatmake} output (except when you specify @code{-M}) is sent to
7168 @code{stderr}. The output produced by the
7169 @code{-M} switch is sent to @code{stdout}.
7171 @node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7172 @anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{cf}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{d0}
7173 @subsection Switches for @code{gnatmake}
7176 You may specify any of the following switches to @code{gnatmake}:
7178 @geindex --version (gnatmake)
7181 @table @asis
7183 @item @code{--version}
7185 Display Copyright and version, then exit disregarding all other options.
7186 @end table
7188 @geindex --help (gnatmake)
7191 @table @asis
7193 @item @code{--help}
7195 If @code{--version} was not used, display usage, then exit disregarding
7196 all other options.
7197 @end table
7199 @geindex -P (gnatmake)
7202 @table @asis
7204 @item @code{-P`project'}
7206 Build GNAT project file @code{project} using GPRbuild. When this switch is
7207 present, all other command-line switches are treated as GPRbuild switches
7208 and not @code{gnatmake} switches.
7209 @end table
7211 @c -- Comment:
7212 @c :ref:`gnatmake_and_Project_Files`.
7214 @geindex --GCC=compiler_name (gnatmake)
7217 @table @asis
7219 @item @code{--GCC=`compiler_name'}
7221 Program used for compiling. The default is @code{gcc}. You need to use
7222 quotes around @code{compiler_name} if @code{compiler_name} contains
7223 spaces or other separator characters.
7224 As an example @code{--GCC="foo -x  -y"}
7225 will instruct @code{gnatmake} to use @code{foo -x -y} as your
7226 compiler. A limitation of this syntax is that the name and path name of
7227 the executable itself must not include any embedded spaces. Note that
7228 switch @code{-c} is always inserted after your command name. Thus in the
7229 above example the compiler command that will be used by @code{gnatmake}
7230 will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7231 used, only the last @code{compiler_name} is taken into account. However,
7232 all the additional switches are also taken into account. Thus,
7233 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7234 @code{--GCC="bar -x -y -z -t"}.
7235 @end table
7237 @geindex --GNATBIND=binder_name (gnatmake)
7240 @table @asis
7242 @item @code{--GNATBIND=`binder_name'}
7244 Program used for binding. The default is @code{gnatbind}. You need to
7245 use quotes around @code{binder_name} if @code{binder_name} contains spaces
7246 or other separator characters.
7247 As an example @code{--GNATBIND="bar -x  -y"}
7248 will instruct @code{gnatmake} to use @code{bar -x -y} as your
7249 binder. Binder switches that are normally appended by @code{gnatmake}
7250 to @code{gnatbind} are now appended to the end of @code{bar -x -y}.
7251 A limitation of this syntax is that the name and path name of the executable
7252 itself must not include any embedded spaces.
7253 @end table
7255 @geindex --GNATLINK=linker_name (gnatmake)
7258 @table @asis
7260 @item @code{--GNATLINK=`linker_name'}
7262 Program used for linking. The default is @code{gnatlink}. You need to
7263 use quotes around @code{linker_name} if @code{linker_name} contains spaces
7264 or other separator characters.
7265 As an example @code{--GNATLINK="lan -x  -y"}
7266 will instruct @code{gnatmake} to use @code{lan -x -y} as your
7267 linker. Linker switches that are normally appended by @code{gnatmake} to
7268 @code{gnatlink} are now appended to the end of @code{lan -x -y}.
7269 A limitation of this syntax is that the name and path name of the executable
7270 itself must not include any embedded spaces.
7272 @item @code{--create-map-file}
7274 When linking an executable, create a map file. The name of the map file
7275 has the same name as the executable with extension “.map”.
7277 @item @code{--create-map-file=`mapfile'}
7279 When linking an executable, create a map file with the specified name.
7280 @end table
7282 @geindex --create-missing-dirs (gnatmake)
7285 @table @asis
7287 @item @code{--create-missing-dirs}
7289 When using project files (@code{-P`project'}), automatically create
7290 missing object directories, library directories and exec
7291 directories.
7293 @item @code{--single-compile-per-obj-dir}
7295 Disallow simultaneous compilations in the same object directory when
7296 project files are used.
7298 @item @code{--subdirs=`subdir'}
7300 Actual object directory of each project file is the subdirectory subdir of the
7301 object directory specified or defaulted in the project file.
7303 @item @code{--unchecked-shared-lib-imports}
7305 By default, shared library projects are not allowed to import static library
7306 projects. When this switch is used on the command line, this restriction is
7307 relaxed.
7309 @item @code{--source-info=`source info file'}
7311 Specify a source info file. This switch is active only when project files
7312 are used. If the source info file is specified as a relative path, then it is
7313 relative to the object directory of the main project. If the source info file
7314 does not exist, then after the Project Manager has successfully parsed and
7315 processed the project files and found the sources, it creates the source info
7316 file. If the source info file already exists and can be read successfully,
7317 then the Project Manager will get all the needed information about the sources
7318 from the source info file and will not look for them. This reduces the time
7319 to process the project files, especially when looking for sources that take a
7320 long time. If the source info file exists but cannot be parsed successfully,
7321 the Project Manager will attempt to recreate it. If the Project Manager fails
7322 to create the source info file, a message is issued, but gnatmake does not
7323 fail. @code{gnatmake} “trusts” the source info file. This means that
7324 if the source files have changed (addition, deletion, moving to a different
7325 source directory), then the source info file need to be deleted and recreated.
7326 @end table
7328 @geindex -a (gnatmake)
7331 @table @asis
7333 @item @code{-a}
7335 Consider all files in the make process, even the GNAT internal system
7336 files (for example, the predefined Ada library files), as well as any
7337 locked files. Locked files are files whose ALI file is write-protected.
7338 By default,
7339 @code{gnatmake} does not check these files,
7340 because the assumption is that the GNAT internal files are properly up
7341 to date, and also that any write protected ALI files have been properly
7342 installed. Note that if there is an installation problem, such that one
7343 of these files is not up to date, it will be properly caught by the
7344 binder.
7345 You may have to specify this switch if you are working on GNAT
7346 itself. The switch @code{-a} is also useful
7347 in conjunction with @code{-f}
7348 if you need to recompile an entire application,
7349 including run-time files, using special configuration pragmas,
7350 such as a @code{Normalize_Scalars} pragma.
7352 By default
7353 @code{gnatmake -a} compiles all GNAT
7354 internal files with
7355 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7356 @end table
7358 @geindex -b (gnatmake)
7361 @table @asis
7363 @item @code{-b}
7365 Bind only. Can be combined with @code{-c} to do
7366 compilation and binding, but no link.
7367 Can be combined with @code{-l}
7368 to do binding and linking. When not combined with
7369 @code{-c}
7370 all the units in the closure of the main program must have been previously
7371 compiled and must be up to date. The root unit specified by @code{file_name}
7372 may be given without extension, with the source extension or, if no GNAT
7373 Project File is specified, with the ALI file extension.
7374 @end table
7376 @geindex -c (gnatmake)
7379 @table @asis
7381 @item @code{-c}
7383 Compile only. Do not perform binding, except when @code{-b}
7384 is also specified. Do not perform linking, except if both
7385 @code{-b} and
7386 @code{-l} are also specified.
7387 If the root unit specified by @code{file_name} is not a main unit, this is the
7388 default. Otherwise @code{gnatmake} will attempt binding and linking
7389 unless all objects are up to date and the executable is more recent than
7390 the objects.
7391 @end table
7393 @geindex -C (gnatmake)
7396 @table @asis
7398 @item @code{-C}
7400 Use a temporary mapping file. A mapping file is a way to communicate
7401 to the compiler two mappings: from unit names to file names (without
7402 any directory information) and from file names to path names (with
7403 full directory information). A mapping file can make the compiler’s
7404 file searches faster, especially if there are many source directories,
7405 or the sources are read over a slow network connection. If
7406 @code{-P} is used, a mapping file is always used, so
7407 @code{-C} is unnecessary; in this case the mapping file
7408 is initially populated based on the project file. If
7409 @code{-C} is used without
7410 @code{-P},
7411 the mapping file is initially empty. Each invocation of the compiler
7412 will add any newly accessed sources to the mapping file.
7413 @end table
7415 @geindex -C= (gnatmake)
7418 @table @asis
7420 @item @code{-C=`file'}
7422 Use a specific mapping file. The file, specified as a path name (absolute or
7423 relative) by this switch, should already exist, otherwise the switch is
7424 ineffective. The specified mapping file will be communicated to the compiler.
7425 This switch is not compatible with a project file
7426 (-P`file`) or with multiple compiling processes
7427 (-jnnn, when nnn is greater than 1).
7428 @end table
7430 @geindex -d (gnatmake)
7433 @table @asis
7435 @item @code{-d}
7437 Display progress for each source, up to date or not, as a single line:
7439 @example
7440 completed x out of y (zz%)
7441 @end example
7443 If the file needs to be compiled this is displayed after the invocation of
7444 the compiler. These lines are displayed even in quiet output mode.
7445 @end table
7447 @geindex -D (gnatmake)
7450 @table @asis
7452 @item @code{-D `dir'}
7454 Put all object files and ALI file in directory @code{dir}.
7455 If the @code{-D} switch is not used, all object files
7456 and ALI files go in the current working directory.
7458 This switch cannot be used when using a project file.
7459 @end table
7461 @geindex -eI (gnatmake)
7464 @table @asis
7466 @item @code{-eI`nnn'}
7468 Indicates that the main source is a multi-unit source and the rank of the unit
7469 in the source file is nnn. nnn needs to be a positive number and a valid
7470 index in the source. This switch cannot be used when @code{gnatmake} is
7471 invoked for several mains.
7472 @end table
7474 @geindex -eL (gnatmake)
7476 @geindex symbolic links
7479 @table @asis
7481 @item @code{-eL}
7483 Follow all symbolic links when processing project files.
7484 This should be used if your project uses symbolic links for files or
7485 directories, but is not needed in other cases.
7487 @geindex naming scheme
7489 This also assumes that no directory matches the naming scheme for files (for
7490 instance that you do not have a directory called “sources.ads” when using the
7491 default GNAT naming scheme).
7493 When you do not have to use this switch (i.e., by default), gnatmake is able to
7494 save a lot of system calls (several per source file and object file), which
7495 can result in a significant speed up to load and manipulate a project file,
7496 especially when using source files from a remote system.
7497 @end table
7499 @geindex -eS (gnatmake)
7502 @table @asis
7504 @item @code{-eS}
7506 Output the commands for the compiler, the binder and the linker
7507 on standard output,
7508 instead of standard error.
7509 @end table
7511 @geindex -f (gnatmake)
7514 @table @asis
7516 @item @code{-f}
7518 Force recompilations. Recompile all sources, even though some object
7519 files may be up to date, but don’t recompile predefined or GNAT internal
7520 files or locked files (files with a write-protected ALI file),
7521 unless the @code{-a} switch is also specified.
7522 @end table
7524 @geindex -F (gnatmake)
7527 @table @asis
7529 @item @code{-F}
7531 When using project files, if some errors or warnings are detected during
7532 parsing and verbose mode is not in effect (no use of switch
7533 -v), then error lines start with the full path name of the project
7534 file, rather than its simple file name.
7535 @end table
7537 @geindex -g (gnatmake)
7540 @table @asis
7542 @item @code{-g}
7544 Enable debugging. This switch is simply passed to the compiler and to the
7545 linker.
7546 @end table
7548 @geindex -i (gnatmake)
7551 @table @asis
7553 @item @code{-i}
7555 In normal mode, @code{gnatmake} compiles all object files and ALI files
7556 into the current directory. If the @code{-i} switch is used,
7557 then instead object files and ALI files that already exist are overwritten
7558 in place. This means that once a large project is organized into separate
7559 directories in the desired manner, then @code{gnatmake} will automatically
7560 maintain and update this organization. If no ALI files are found on the
7561 Ada object path (see @ref{73,,Search Paths and the Run-Time Library (RTL)}),
7562 the new object and ALI files are created in the
7563 directory containing the source being compiled. If another organization
7564 is desired, where objects and sources are kept in different directories,
7565 a useful technique is to create dummy ALI files in the desired directories.
7566 When detecting such a dummy file, @code{gnatmake} will be forced to
7567 recompile the corresponding source file, and it will be put the resulting
7568 object and ALI files in the directory where it found the dummy file.
7569 @end table
7571 @geindex -j (gnatmake)
7573 @geindex Parallel make
7576 @table @asis
7578 @item @code{-j`n'}
7580 Use @code{n} processes to carry out the (re)compilations. On a multiprocessor
7581 machine compilations will occur in parallel. If @code{n} is 0, then the
7582 maximum number of parallel compilations is the number of core processors
7583 on the platform. In the event of compilation errors, messages from various
7584 compilations might get interspersed (but @code{gnatmake} will give you the
7585 full ordered list of failing compiles at the end). If this is problematic,
7586 rerun the make process with n set to 1 to get a clean list of messages.
7587 @end table
7589 @geindex -k (gnatmake)
7592 @table @asis
7594 @item @code{-k}
7596 Keep going. Continue as much as possible after a compilation error. To
7597 ease the programmer’s task in case of compilation errors, the list of
7598 sources for which the compile fails is given when @code{gnatmake}
7599 terminates.
7601 If @code{gnatmake} is invoked with several @code{file_names} and with this
7602 switch, if there are compilation errors when building an executable,
7603 @code{gnatmake} will not attempt to build the following executables.
7604 @end table
7606 @geindex -l (gnatmake)
7609 @table @asis
7611 @item @code{-l}
7613 Link only. Can be combined with @code{-b} to binding
7614 and linking. Linking will not be performed if combined with
7615 @code{-c}
7616 but not with @code{-b}.
7617 When not combined with @code{-b}
7618 all the units in the closure of the main program must have been previously
7619 compiled and must be up to date, and the main program needs to have been bound.
7620 The root unit specified by @code{file_name}
7621 may be given without extension, with the source extension or, if no GNAT
7622 Project File is specified, with the ALI file extension.
7623 @end table
7625 @geindex -m (gnatmake)
7628 @table @asis
7630 @item @code{-m}
7632 Specify that the minimum necessary amount of recompilations
7633 be performed. In this mode @code{gnatmake} ignores time
7634 stamp differences when the only
7635 modifications to a source file consist in adding/removing comments,
7636 empty lines, spaces or tabs. This means that if you have changed the
7637 comments in a source file or have simply reformatted it, using this
7638 switch will tell @code{gnatmake} not to recompile files that depend on it
7639 (provided other sources on which these files depend have undergone no
7640 semantic modifications). Note that the debugging information may be
7641 out of date with respect to the sources if the @code{-m} switch causes
7642 a compilation to be switched, so the use of this switch represents a
7643 trade-off between compilation time and accurate debugging information.
7644 @end table
7646 @geindex Dependencies
7647 @geindex producing list
7649 @geindex -M (gnatmake)
7652 @table @asis
7654 @item @code{-M}
7656 Check if all objects are up to date. If they are, output the object
7657 dependences to @code{stdout} in a form that can be directly exploited in
7658 a @code{Makefile}. By default, each source file is prefixed with its
7659 (relative or absolute) directory name. This name is whatever you
7660 specified in the various @code{-aI}
7661 and @code{-I} switches. If you use
7662 @code{gnatmake -M}  @code{-q}
7663 (see below), only the source file names,
7664 without relative paths, are output. If you just specify the  @code{-M}
7665 switch, dependencies of the GNAT internal system files are omitted. This
7666 is typically what you want. If you also specify
7667 the @code{-a} switch,
7668 dependencies of the GNAT internal files are also listed. Note that
7669 dependencies of the objects in external Ada libraries (see
7670 switch  @code{-aL`dir'} in the following list)
7671 are never reported.
7672 @end table
7674 @geindex -n (gnatmake)
7677 @table @asis
7679 @item @code{-n}
7681 Don’t compile, bind, or link. Checks if all objects are up to date.
7682 If they are not, the full name of the first file that needs to be
7683 recompiled is printed.
7684 Repeated use of this option, followed by compiling the indicated source
7685 file, will eventually result in recompiling all required units.
7686 @end table
7688 @geindex -o (gnatmake)
7691 @table @asis
7693 @item @code{-o `exec_name'}
7695 Output executable name. The name of the final executable program will be
7696 @code{exec_name}. If the @code{-o} switch is omitted the default
7697 name for the executable will be the name of the input file in appropriate form
7698 for an executable file on the host system.
7700 This switch cannot be used when invoking @code{gnatmake} with several
7701 @code{file_names}.
7702 @end table
7704 @geindex -p (gnatmake)
7707 @table @asis
7709 @item @code{-p}
7711 Same as @code{--create-missing-dirs}
7712 @end table
7714 @geindex -q (gnatmake)
7717 @table @asis
7719 @item @code{-q}
7721 Quiet. When this flag is not set, the commands carried out by
7722 @code{gnatmake} are displayed.
7723 @end table
7725 @geindex -s (gnatmake)
7728 @table @asis
7730 @item @code{-s}
7732 Recompile if compiler switches have changed since last compilation.
7733 All compiler switches but -I and -o are taken into account in the
7734 following way:
7735 orders between different ‘first letter’ switches are ignored, but
7736 orders between same switches are taken into account. For example,
7737 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O}
7738 is equivalent to @code{-O -g}.
7740 This switch is recommended when Integrated Preprocessing is used.
7741 @end table
7743 @geindex -u (gnatmake)
7746 @table @asis
7748 @item @code{-u}
7750 Unique. Recompile at most the main files. It implies -c. Combined with
7751 -f, it is equivalent to calling the compiler directly. Note that using
7752 -u with a project file and no main has a special meaning.
7753 @end table
7755 @c --Comment
7756 @c (See :ref:`Project_Files_and_Main_Subprograms`.)
7758 @geindex -U (gnatmake)
7761 @table @asis
7763 @item @code{-U}
7765 When used without a project file or with one or several mains on the command
7766 line, is equivalent to -u. When used with a project file and no main
7767 on the command line, all sources of all project files are checked and compiled
7768 if not up to date, and libraries are rebuilt, if necessary.
7769 @end table
7771 @geindex -v (gnatmake)
7774 @table @asis
7776 @item @code{-v}
7778 Verbose. Display the reason for all recompilations @code{gnatmake}
7779 decides are necessary, with the highest verbosity level.
7780 @end table
7782 @geindex -vl (gnatmake)
7785 @table @asis
7787 @item @code{-vl}
7789 Verbosity level Low. Display fewer lines than in verbosity Medium.
7790 @end table
7792 @geindex -vm (gnatmake)
7795 @table @asis
7797 @item @code{-vm}
7799 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7800 @end table
7802 @geindex -vm (gnatmake)
7805 @table @asis
7807 @item @code{-vh}
7809 Verbosity level High. Equivalent to -v.
7811 @item @code{-vP`x'}
7813 Indicate the verbosity of the parsing of GNAT project files.
7814 See @ref{d1,,Switches Related to Project Files}.
7815 @end table
7817 @geindex -x (gnatmake)
7820 @table @asis
7822 @item @code{-x}
7824 Indicate that sources that are not part of any Project File may be compiled.
7825 Normally, when using Project Files, only sources that are part of a Project
7826 File may be compile. When this switch is used, a source outside of all Project
7827 Files may be compiled. The ALI file and the object file will be put in the
7828 object directory of the main Project. The compilation switches used will only
7829 be those specified on the command line. Even when
7830 @code{-x} is used, mains specified on the
7831 command line need to be sources of a project file.
7833 @item @code{-X`name'=`value'}
7835 Indicate that external variable @code{name} has the value @code{value}.
7836 The Project Manager will use this value for occurrences of
7837 @code{external(name)} when parsing the project file.
7838 @ref{d1,,Switches Related to Project Files}.
7839 @end table
7841 @geindex -z (gnatmake)
7844 @table @asis
7846 @item @code{-z}
7848 No main subprogram. Bind and link the program even if the unit name
7849 given on the command line is a package name. The resulting executable
7850 will execute the elaboration routines of the package and its closure,
7851 then the finalization routines.
7852 @end table
7854 @subsubheading GCC switches
7857 Any uppercase or multi-character switch that is not a @code{gnatmake} switch
7858 is passed to @code{gcc} (e.g., @code{-O}, @code{-gnato,} etc.)
7860 @subsubheading Source and library search path switches
7863 @geindex -aI (gnatmake)
7866 @table @asis
7868 @item @code{-aI`dir'}
7870 When looking for source files also look in directory @code{dir}.
7871 The order in which source files search is undertaken is
7872 described in @ref{73,,Search Paths and the Run-Time Library (RTL)}.
7873 @end table
7875 @geindex -aL (gnatmake)
7878 @table @asis
7880 @item @code{-aL`dir'}
7882 Consider @code{dir} as being an externally provided Ada library.
7883 Instructs @code{gnatmake} to skip compilation units whose @code{.ALI}
7884 files have been located in directory @code{dir}. This allows you to have
7885 missing bodies for the units in @code{dir} and to ignore out of date bodies
7886 for the same units. You still need to specify
7887 the location of the specs for these units by using the switches
7888 @code{-aI`dir'}  or @code{-I`dir'}.
7889 Note: this switch is provided for compatibility with previous versions
7890 of @code{gnatmake}. The easier method of causing standard libraries
7891 to be excluded from consideration is to write-protect the corresponding
7892 ALI files.
7893 @end table
7895 @geindex -aO (gnatmake)
7898 @table @asis
7900 @item @code{-aO`dir'}
7902 When searching for library and object files, look in directory
7903 @code{dir}. The order in which library files are searched is described in
7904 @ref{76,,Search Paths for gnatbind}.
7905 @end table
7907 @geindex Search paths
7908 @geindex for gnatmake
7910 @geindex -A (gnatmake)
7913 @table @asis
7915 @item @code{-A`dir'}
7917 Equivalent to @code{-aL`dir'} @code{-aI`dir'}.
7919 @geindex -I (gnatmake)
7921 @item @code{-I`dir'}
7923 Equivalent to @code{-aO`dir' -aI`dir'}.
7924 @end table
7926 @geindex -I- (gnatmake)
7928 @geindex Source files
7929 @geindex suppressing search
7932 @table @asis
7934 @item @code{-I-}
7936 Do not look for source files in the directory containing the source
7937 file named in the command line.
7938 Do not look for ALI or object files in the directory
7939 where @code{gnatmake} was invoked.
7940 @end table
7942 @geindex -L (gnatmake)
7944 @geindex Linker libraries
7947 @table @asis
7949 @item @code{-L`dir'}
7951 Add directory @code{dir} to the list of directories in which the linker
7952 will search for libraries. This is equivalent to
7953 @code{-largs} @code{-L`dir'}.
7954 Furthermore, under Windows, the sources pointed to by the libraries path
7955 set in the registry are not searched for.
7956 @end table
7958 @geindex -nostdinc (gnatmake)
7961 @table @asis
7963 @item @code{-nostdinc}
7965 Do not look for source files in the system default directory.
7966 @end table
7968 @geindex -nostdlib (gnatmake)
7971 @table @asis
7973 @item @code{-nostdlib}
7975 Do not look for library files in the system default directory.
7976 @end table
7978 @geindex --RTS (gnatmake)
7981 @table @asis
7983 @item @code{--RTS=`rts-path'}
7985 Specifies the default location of the run-time library. GNAT looks for the
7986 run-time
7987 in the following directories, and stops as soon as a valid run-time is found
7988 (@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
7989 @code{ada_object_path} present):
7992 @itemize *
7994 @item 
7995 `<current directory>/$rts_path'
7997 @item 
7998 `<default-search-dir>/$rts_path'
8000 @item 
8001 `<default-search-dir>/rts-$rts_path'
8003 @item 
8004 The selected path is handled like a normal RTS path.
8005 @end itemize
8006 @end table
8008 @node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
8009 @anchor{gnat_ugn/building_executable_programs_with_gnat id4}@anchor{d2}@anchor{gnat_ugn/building_executable_programs_with_gnat mode-switches-for-gnatmake}@anchor{d3}
8010 @subsection Mode Switches for @code{gnatmake}
8013 The mode switches (referred to as @code{mode_switches}) allow the
8014 inclusion of switches that are to be passed to the compiler itself, the
8015 binder or the linker. The effect of a mode switch is to cause all
8016 subsequent switches up to the end of the switch list, or up to the next
8017 mode switch, to be interpreted as switches to be passed on to the
8018 designated component of GNAT.
8020 @geindex -cargs (gnatmake)
8023 @table @asis
8025 @item @code{-cargs `switches'}
8027 Compiler switches. Here @code{switches} is a list of switches
8028 that are valid switches for @code{gcc}. They will be passed on to
8029 all compile steps performed by @code{gnatmake}.
8030 @end table
8032 @geindex -bargs (gnatmake)
8035 @table @asis
8037 @item @code{-bargs `switches'}
8039 Binder switches. Here @code{switches} is a list of switches
8040 that are valid switches for @code{gnatbind}. They will be passed on to
8041 all bind steps performed by @code{gnatmake}.
8042 @end table
8044 @geindex -largs (gnatmake)
8047 @table @asis
8049 @item @code{-largs `switches'}
8051 Linker switches. Here @code{switches} is a list of switches
8052 that are valid switches for @code{gnatlink}. They will be passed on to
8053 all link steps performed by @code{gnatmake}.
8054 @end table
8056 @geindex -margs (gnatmake)
8059 @table @asis
8061 @item @code{-margs `switches'}
8063 Make switches. The switches are directly interpreted by @code{gnatmake},
8064 regardless of any previous occurrence of @code{-cargs}, @code{-bargs}
8065 or @code{-largs}.
8066 @end table
8068 @node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8069 @anchor{gnat_ugn/building_executable_programs_with_gnat id5}@anchor{d4}@anchor{gnat_ugn/building_executable_programs_with_gnat notes-on-the-command-line}@anchor{d5}
8070 @subsection Notes on the Command Line
8073 This section contains some additional useful notes on the operation
8074 of the @code{gnatmake} command.
8076 @geindex Recompilation (by gnatmake)
8079 @itemize *
8081 @item 
8082 If @code{gnatmake} finds no ALI files, it recompiles the main program
8083 and all other units required by the main program.
8084 This means that @code{gnatmake}
8085 can be used for the initial compile, as well as during subsequent steps of
8086 the development cycle.
8088 @item 
8089 If you enter @code{gnatmake foo.adb}, where @code{foo}
8090 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8091 @code{foo.adb} (because it finds no ALI) and stops, issuing a
8092 warning.
8094 @item 
8095 In @code{gnatmake} the switch @code{-I}
8096 is used to specify both source and
8097 library file paths. Use @code{-aI}
8098 instead if you just want to specify
8099 source paths only and @code{-aO}
8100 if you want to specify library paths
8101 only.
8103 @item 
8104 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8105 This may conveniently be used to exclude standard libraries from
8106 consideration and in particular it means that the use of the
8107 @code{-f} switch will not recompile these files
8108 unless @code{-a} is also specified.
8110 @item 
8111 @code{gnatmake} has been designed to make the use of Ada libraries
8112 particularly convenient. Assume you have an Ada library organized
8113 as follows: `obj-dir' contains the objects and ALI files for
8114 of your Ada compilation units,
8115 whereas `include-dir' contains the
8116 specs of these units, but no bodies. Then to compile a unit
8117 stored in @code{main.adb}, which uses this Ada library you would just type:
8119 @example
8120 $ gnatmake -aI`include-dir`  -aL`obj-dir`  main
8121 @end example
8123 @item 
8124 Using @code{gnatmake} along with the @code{-m (minimal recompilation)}
8125 switch provides a mechanism for avoiding unnecessary recompilations. Using
8126 this switch,
8127 you can update the comments/format of your
8128 source files without having to recompile everything. Note, however, that
8129 adding or deleting lines in a source files may render its debugging
8130 info obsolete. If the file in question is a spec, the impact is rather
8131 limited, as that debugging info will only be useful during the
8132 elaboration phase of your program. For bodies the impact can be more
8133 significant. In all events, your debugger will warn you if a source file
8134 is more recent than the corresponding object, and alert you to the fact
8135 that the debugging information may be out of date.
8136 @end itemize
8138 @node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8139 @anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{d6}@anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{d7}
8140 @subsection How @code{gnatmake} Works
8143 Generally @code{gnatmake} automatically performs all necessary
8144 recompilations and you don’t need to worry about how it works. However,
8145 it may be useful to have some basic understanding of the @code{gnatmake}
8146 approach and in particular to understand how it uses the results of
8147 previous compilations without incorrectly depending on them.
8149 First a definition: an object file is considered `up to date' if the
8150 corresponding ALI file exists and if all the source files listed in the
8151 dependency section of this ALI file have time stamps matching those in
8152 the ALI file. This means that neither the source file itself nor any
8153 files that it depends on have been modified, and hence there is no need
8154 to recompile this file.
8156 @code{gnatmake} works by first checking if the specified main unit is up
8157 to date. If so, no compilations are required for the main unit. If not,
8158 @code{gnatmake} compiles the main program to build a new ALI file that
8159 reflects the latest sources. Then the ALI file of the main unit is
8160 examined to find all the source files on which the main program depends,
8161 and @code{gnatmake} recursively applies the above procedure on all these
8162 files.
8164 This process ensures that @code{gnatmake} only trusts the dependencies
8165 in an existing ALI file if they are known to be correct. Otherwise it
8166 always recompiles to determine a new, guaranteed accurate set of
8167 dependencies. As a result the program is compiled ‘upside down’ from what may
8168 be more familiar as the required order of compilation in some other Ada
8169 systems. In particular, clients are compiled before the units on which
8170 they depend. The ability of GNAT to compile in any order is critical in
8171 allowing an order of compilation to be chosen that guarantees that
8172 @code{gnatmake} will recompute a correct set of new dependencies if
8173 necessary.
8175 When invoking @code{gnatmake} with several @code{file_names}, if a unit is
8176 imported by several of the executables, it will be recompiled at most once.
8178 Note: when using non-standard naming conventions
8179 (@ref{1c,,Using Other File Names}), changing through a configuration pragmas
8180 file the version of a source and invoking @code{gnatmake} to recompile may
8181 have no effect, if the previous version of the source is still accessible
8182 by @code{gnatmake}. It may be necessary to use the switch
8185 @node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8186 @anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatmake-usage}@anchor{d8}@anchor{gnat_ugn/building_executable_programs_with_gnat id7}@anchor{d9}
8187 @subsection Examples of @code{gnatmake} Usage
8191 @table @asis
8193 @item @code{gnatmake hello.adb}
8195 Compile all files necessary to bind and link the main program
8196 @code{hello.adb} (containing unit @code{Hello}) and bind and link the
8197 resulting object files to generate an executable file @code{hello}.
8199 @item @code{gnatmake main1 main2 main3}
8201 Compile all files necessary to bind and link the main programs
8202 @code{main1.adb} (containing unit @code{Main1}), @code{main2.adb}
8203 (containing unit @code{Main2}) and @code{main3.adb}
8204 (containing unit @code{Main3}) and bind and link the resulting object files
8205 to generate three executable files @code{main1},
8206 @code{main2}  and @code{main3}.
8208 @item @code{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8210 Compile all files necessary to bind and link the main program unit
8211 @code{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8212 be done with optimization level 2 and the order of elaboration will be
8213 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8214 displaying commands it is executing.
8215 @end table
8217 @node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8218 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{c9}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{da}
8219 @section Compiling with @code{gcc}
8222 This section discusses how to compile Ada programs using the @code{gcc}
8223 command. It also describes the set of switches
8224 that can be used to control the behavior of the compiler.
8226 @menu
8227 * Compiling Programs:: 
8228 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
8229 * Order of Compilation Issues:: 
8230 * Examples:: 
8232 @end menu
8234 @node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8235 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{db}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{dc}
8236 @subsection Compiling Programs
8239 The first step in creating an executable program is to compile the units
8240 of the program using the @code{gcc} command. You must compile the
8241 following files:
8244 @itemize *
8246 @item 
8247 the body file (@code{.adb}) for a library level subprogram or generic
8248 subprogram
8250 @item 
8251 the spec file (@code{.ads}) for a library level package or generic
8252 package that has no body
8254 @item 
8255 the body file (@code{.adb}) for a library level package
8256 or generic package that has a body
8257 @end itemize
8259 You need `not' compile the following files
8262 @itemize *
8264 @item 
8265 the spec of a library unit which has a body
8267 @item 
8268 subunits
8269 @end itemize
8271 because they are compiled as part of compiling related units. GNAT compiles
8272 package specs
8273 when the corresponding body is compiled, and subunits when the parent is
8274 compiled.
8276 @geindex cannot generate code
8278 If you attempt to compile any of these files, you will get one of the
8279 following error messages (where @code{fff} is the name of the file you
8280 compiled):
8282 @quotation
8284 @example
8285 cannot generate code for file `@w{`}fff`@w{`} (package spec)
8286 to check package spec, use -gnatc
8288 cannot generate code for file `@w{`}fff`@w{`} (missing subunits)
8289 to check parent unit, use -gnatc
8291 cannot generate code for file `@w{`}fff`@w{`} (subprogram spec)
8292 to check subprogram spec, use -gnatc
8294 cannot generate code for file `@w{`}fff`@w{`} (subunit)
8295 to check subunit, use -gnatc
8296 @end example
8297 @end quotation
8299 As indicated by the above error messages, if you want to submit
8300 one of these files to the compiler to check for correct semantics
8301 without generating code, then use the @code{-gnatc} switch.
8303 The basic command for compiling a file containing an Ada unit is:
8305 @example
8306 $ gcc -c [switches] <file name>
8307 @end example
8309 where @code{file name} is the name of the Ada file (usually
8310 having an extension @code{.ads} for a spec or @code{.adb} for a body).
8311 You specify the
8312 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
8313 The result of a successful compilation is an object file, which has the
8314 same name as the source file but an extension of @code{.o} and an Ada
8315 Library Information (ALI) file, which also has the same name as the
8316 source file, but with @code{.ali} as the extension. GNAT creates these
8317 two output files in the current directory, but you may specify a source
8318 file in any directory using an absolute or relative path specification
8319 containing the directory information.
8321 @geindex gnat1
8323 @code{gcc} is actually a driver program that looks at the extensions of
8324 the file arguments and loads the appropriate compiler. For example, the
8325 GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8326 These programs are in directories known to the driver program (in some
8327 configurations via environment variables you set), but need not be in
8328 your path. The @code{gcc} driver also calls the assembler and any other
8329 utilities needed to complete the generation of the required object
8330 files.
8332 It is possible to supply several file names on the same @code{gcc}
8333 command. This causes @code{gcc} to call the appropriate compiler for
8334 each file. For example, the following command lists two separate
8335 files to be compiled:
8337 @example
8338 $ gcc -c x.adb y.adb
8339 @end example
8341 calls @code{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8342 @code{y.adb}.
8343 The compiler generates two object files @code{x.o} and @code{y.o}
8344 and the two ALI files @code{x.ali} and @code{y.ali}.
8346 Any switches apply to all the files listed, see @ref{dd,,Compiler Switches} for a
8347 list of available @code{gcc} switches.
8349 @node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8350 @anchor{gnat_ugn/building_executable_programs_with_gnat id10}@anchor{de}@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-and-the-run-time-library-rtl}@anchor{73}
8351 @subsection Search Paths and the Run-Time Library (RTL)
8354 With the GNAT source-based library system, the compiler must be able to
8355 find source files for units that are needed by the unit being compiled.
8356 Search paths are used to guide this process.
8358 The compiler compiles one source file whose name must be given
8359 explicitly on the command line. In other words, no searching is done
8360 for this file. To find all other source files that are needed (the most
8361 common being the specs of units), the compiler examines the following
8362 directories, in the following order:
8365 @itemize *
8367 @item 
8368 The directory containing the source file of the main unit being compiled
8369 (the file name on the command line).
8371 @item 
8372 Each directory named by an @code{-I} switch given on the @code{gcc}
8373 command line, in the order given.
8375 @geindex ADA_PRJ_INCLUDE_FILE
8377 @item 
8378 Each of the directories listed in the text file whose name is given
8379 by the 
8380 @geindex ADA_PRJ_INCLUDE_FILE
8381 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8382 @code{ADA_PRJ_INCLUDE_FILE} environment variable.
8383 @geindex ADA_PRJ_INCLUDE_FILE
8384 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8385 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8386 driver when project files are used. It should not normally be set
8387 by other means.
8389 @geindex ADA_INCLUDE_PATH
8391 @item 
8392 Each of the directories listed in the value of the
8393 @geindex ADA_INCLUDE_PATH
8394 @geindex environment variable; ADA_INCLUDE_PATH
8395 @code{ADA_INCLUDE_PATH} environment variable.
8396 Construct this value
8397 exactly as the 
8398 @geindex PATH
8399 @geindex environment variable; PATH
8400 @code{PATH} environment variable: a list of directory
8401 names separated by colons (semicolons when working with the NT version).
8403 @item 
8404 The content of the @code{ada_source_path} file which is part of the GNAT
8405 installation tree and is used to store standard libraries such as the
8406 GNAT Run Time Library (RTL) source files.
8407 See also @ref{72,,Installing a library}.
8408 @end itemize
8410 Specifying the switch @code{-I-}
8411 inhibits the use of the directory
8412 containing the source file named in the command line. You can still
8413 have this directory on your search path, but in this case it must be
8414 explicitly requested with a @code{-I} switch.
8416 Specifying the switch @code{-nostdinc}
8417 inhibits the search of the default location for the GNAT Run Time
8418 Library (RTL) source files.
8420 The compiler outputs its object files and ALI files in the current
8421 working directory.
8422 Caution: The object file can be redirected with the @code{-o} switch;
8423 however, @code{gcc} and @code{gnat1} have not been coordinated on this
8424 so the @code{ALI} file will not go to the right place. Therefore, you should
8425 avoid using the @code{-o} switch.
8427 @geindex System.IO
8429 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8430 children make up the GNAT RTL, together with the simple @code{System.IO}
8431 package used in the @code{"Hello World"} example. The sources for these units
8432 are needed by the compiler and are kept together in one directory. Not
8433 all of the bodies are needed, but all of the sources are kept together
8434 anyway. In a normal installation, you need not specify these directory
8435 names when compiling or binding. Either the environment variables or
8436 the built-in defaults cause these files to be found.
8438 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8439 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8440 consisting of child units of @code{GNAT}. This is a collection of generally
8441 useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8442 for further details.
8444 Besides simplifying access to the RTL, a major use of search paths is
8445 in compiling sources from multiple directories. This can make
8446 development environments much more flexible.
8448 @node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8449 @anchor{gnat_ugn/building_executable_programs_with_gnat id11}@anchor{df}@anchor{gnat_ugn/building_executable_programs_with_gnat order-of-compilation-issues}@anchor{e0}
8450 @subsection Order of Compilation Issues
8453 If, in our earlier example, there was a spec for the @code{hello}
8454 procedure, it would be contained in the file @code{hello.ads}; yet this
8455 file would not have to be explicitly compiled. This is the result of the
8456 model we chose to implement library management. Some of the consequences
8457 of this model are as follows:
8460 @itemize *
8462 @item 
8463 There is no point in compiling specs (except for package
8464 specs with no bodies) because these are compiled as needed by clients. If
8465 you attempt a useless compilation, you will receive an error message.
8466 It is also useless to compile subunits because they are compiled as needed
8467 by the parent.
8469 @item 
8470 There are no order of compilation requirements: performing a
8471 compilation never obsoletes anything. The only way you can obsolete
8472 something and require recompilations is to modify one of the
8473 source files on which it depends.
8475 @item 
8476 There is no library as such, apart from the ALI files
8477 (@ref{28,,The Ada Library Information Files}, for information on the format
8478 of these files). For now we find it convenient to create separate ALI files,
8479 but eventually the information therein may be incorporated into the object
8480 file directly.
8482 @item 
8483 When you compile a unit, the source files for the specs of all units
8484 that it `with's, all its subunits, and the bodies of any generics it
8485 instantiates must be available (reachable by the search-paths mechanism
8486 described above), or you will receive a fatal error message.
8487 @end itemize
8489 @node Examples,,Order of Compilation Issues,Compiling with gcc
8490 @anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{e1}@anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{e2}
8491 @subsection Examples
8494 The following are some typical Ada compilation command line examples:
8496 @example
8497 $ gcc -c xyz.adb
8498 @end example
8500 Compile body in file @code{xyz.adb} with all default options.
8502 @example
8503 $ gcc -c -O2 -gnata xyz-def.adb
8504 @end example
8506 Compile the child unit package in file @code{xyz-def.adb} with extensive
8507 optimizations, and pragma @code{Assert}/@code{Debug} statements
8508 enabled.
8510 @example
8511 $ gcc -c -gnatc abc-def.adb
8512 @end example
8514 Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8515 mode.
8517 @node Compiler Switches,Linker Switches,Compiling with gcc,Building Executable Programs with GNAT
8518 @anchor{gnat_ugn/building_executable_programs_with_gnat compiler-switches}@anchor{e3}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gcc}@anchor{dd}
8519 @section Compiler Switches
8522 The @code{gcc} command accepts switches that control the
8523 compilation process. These switches are fully described in this section:
8524 first an alphabetical listing of all switches with a brief description,
8525 and then functionally grouped sets of switches with more detailed
8526 information.
8528 More switches exist for GCC than those documented here, especially
8529 for specific targets. However, their use is not recommended as
8530 they may change code generation in ways that are incompatible with
8531 the Ada run-time library, or can cause inconsistencies between
8532 compilation units.
8534 @menu
8535 * Alphabetical List of All Switches:: 
8536 * Output and Error Message Control:: 
8537 * Warning Message Control:: 
8538 * Debugging and Assertion Control:: 
8539 * Validity Checking:: 
8540 * Style Checking:: 
8541 * Run-Time Checks:: 
8542 * Using gcc for Syntax Checking:: 
8543 * Using gcc for Semantic Checking:: 
8544 * Compiling Different Versions of Ada:: 
8545 * Character Set Control:: 
8546 * File Naming Control:: 
8547 * Subprogram Inlining Control:: 
8548 * Auxiliary Output Control:: 
8549 * Debugging Control:: 
8550 * Exception Handling Control:: 
8551 * Units to Sources Mapping Files:: 
8552 * Code Generation Control:: 
8554 @end menu
8556 @node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8557 @anchor{gnat_ugn/building_executable_programs_with_gnat alphabetical-list-of-all-switches}@anchor{e4}@anchor{gnat_ugn/building_executable_programs_with_gnat id13}@anchor{e5}
8558 @subsection Alphabetical List of All Switches
8561 @geindex -b (gcc)
8564 @table @asis
8566 @item @code{-b `target'}
8568 Compile your program to run on @code{target}, which is the name of a
8569 system configuration. You must have a GNAT cross-compiler built if
8570 @code{target} is not the same as your host system.
8571 @end table
8573 @geindex -B (gcc)
8576 @table @asis
8578 @item @code{-B`dir'}
8580 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8581 from @code{dir} instead of the default location. Only use this switch
8582 when multiple versions of the GNAT compiler are available.
8583 See the “Options for Directory Search” section in the
8584 @cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8585 You would normally use the @code{-b} or @code{-V} switch instead.
8586 @end table
8588 @geindex -c (gcc)
8591 @table @asis
8593 @item @code{-c}
8595 Compile. Always use this switch when compiling Ada programs.
8597 Note: for some other languages when using @code{gcc}, notably in
8598 the case of C and C++, it is possible to use
8599 use @code{gcc} without a @code{-c} switch to
8600 compile and link in one step. In the case of GNAT, you
8601 cannot use this approach, because the binder must be run
8602 and @code{gcc} cannot be used to run the GNAT binder.
8603 @end table
8605 @geindex -fcallgraph-info (gcc)
8608 @table @asis
8610 @item @code{-fcallgraph-info[=su,da]}
8612 Makes the compiler output callgraph information for the program, on a
8613 per-file basis. The information is generated in the VCG format.  It can
8614 be decorated with additional, per-node and/or per-edge information, if a
8615 list of comma-separated markers is additionally specified. When the
8616 @code{su} marker is specified, the callgraph is decorated with stack usage
8617 information; it is equivalent to @code{-fstack-usage}. When the @code{da}
8618 marker is specified, the callgraph is decorated with information about
8619 dynamically allocated objects.
8620 @end table
8622 @geindex -fdiagnostics-format (gcc)
8625 @table @asis
8627 @item @code{-fdiagnostics-format=json}
8629 Makes GNAT emit warning and error messages as JSON. Inhibits printing of
8630 text warning and errors messages except if @code{-gnatv} or
8631 @code{-gnatl} are present. Uses absolute file paths when used along
8632 @code{-gnatef}.
8633 @end table
8635 @geindex -fdump-scos (gcc)
8638 @table @asis
8640 @item @code{-fdump-scos}
8642 Generates SCO (Source Coverage Obligation) information in the ALI file.
8643 This information is used by advanced coverage tools. See unit @code{SCOs}
8644 in the compiler sources for details in files @code{scos.ads} and
8645 @code{scos.adb}.
8646 @end table
8648 @geindex -fgnat-encodings (gcc)
8651 @table @asis
8653 @item @code{-fgnat-encodings=[all|gdb|minimal]}
8655 This switch controls the balance between GNAT encodings and standard DWARF
8656 emitted in the debug information.
8657 @end table
8659 @geindex -flto (gcc)
8662 @table @asis
8664 @item @code{-flto[=`n']}
8666 Enables Link Time Optimization. This switch must be used in conjunction
8667 with the @code{-Ox} switches (but not with the @code{-gnatn} switch
8668 since it is a full replacement for the latter) and instructs the compiler
8669 to defer most optimizations until the link stage. The advantage of this
8670 approach is that the compiler can do a whole-program analysis and choose
8671 the best interprocedural optimization strategy based on a complete view
8672 of the program, instead of a fragmentary view with the usual approach.
8673 This can also speed up the compilation of big programs and reduce the
8674 size of the executable, compared with a traditional per-unit compilation
8675 with inlining across units enabled by the @code{-gnatn} switch.
8676 The drawback of this approach is that it may require more memory and that
8677 the debugging information generated by @code{-g} with it might be hardly usable.
8678 The switch, as well as the accompanying @code{-Ox} switches, must be
8679 specified both for the compilation and the link phases.
8680 If the @code{n} parameter is specified, the optimization and final code
8681 generation at link time are executed using @code{n} parallel jobs by
8682 means of an installed @code{make} program.
8683 @end table
8685 @geindex -fno-inline (gcc)
8688 @table @asis
8690 @item @code{-fno-inline}
8692 Suppresses all inlining, unless requested with pragma @code{Inline_Always}. The
8693 effect is enforced regardless of other optimization or inlining switches.
8694 Note that inlining can also be suppressed on a finer-grained basis with
8695 pragma @code{No_Inline}.
8696 @end table
8698 @geindex -fno-inline-functions (gcc)
8701 @table @asis
8703 @item @code{-fno-inline-functions}
8705 Suppresses automatic inlining of subprograms, which is enabled
8706 if @code{-O3} is used.
8707 @end table
8709 @geindex -fno-inline-small-functions (gcc)
8712 @table @asis
8714 @item @code{-fno-inline-small-functions}
8716 Suppresses automatic inlining of small subprograms, which is enabled
8717 if @code{-O2} is used.
8718 @end table
8720 @geindex -fno-inline-functions-called-once (gcc)
8723 @table @asis
8725 @item @code{-fno-inline-functions-called-once}
8727 Suppresses inlining of subprograms local to the unit and called once
8728 from within it, which is enabled if @code{-O1} is used.
8729 @end table
8731 @geindex -fno-ivopts (gcc)
8734 @table @asis
8736 @item @code{-fno-ivopts}
8738 Suppresses high-level loop induction variable optimizations, which are
8739 enabled if @code{-O1} is used. These optimizations are generally
8740 profitable but, for some specific cases of loops with numerous uses
8741 of the iteration variable that follow a common pattern, they may end
8742 up destroying the regularity that could be exploited at a lower level
8743 and thus producing inferior code.
8744 @end table
8746 @geindex -fno-strict-aliasing (gcc)
8749 @table @asis
8751 @item @code{-fno-strict-aliasing}
8753 Causes the compiler to avoid assumptions regarding non-aliasing
8754 of objects of different types. See
8755 @ref{e6,,Optimization and Strict Aliasing} for details.
8756 @end table
8758 @geindex -fno-strict-overflow (gcc)
8761 @table @asis
8763 @item @code{-fno-strict-overflow}
8765 Causes the compiler to avoid assumptions regarding the rules of signed
8766 integer overflow. These rules specify that signed integer overflow will
8767 result in a Constraint_Error exception at run time and are enforced in
8768 default mode by the compiler, so this switch should not be necessary in
8769 normal operating mode. It might be useful in conjunction with @code{-gnato0}
8770 for very peculiar cases of low-level programming.
8771 @end table
8773 @geindex -fstack-check (gcc)
8776 @table @asis
8778 @item @code{-fstack-check}
8780 Activates stack checking.
8781 See @ref{e7,,Stack Overflow Checking} for details.
8782 @end table
8784 @geindex -fstack-usage (gcc)
8787 @table @asis
8789 @item @code{-fstack-usage}
8791 Makes the compiler output stack usage information for the program, on a
8792 per-subprogram basis. See @ref{e8,,Static Stack Usage Analysis} for details.
8793 @end table
8795 @geindex -g (gcc)
8798 @table @asis
8800 @item @code{-g}
8802 Generate debugging information. This information is stored in the object
8803 file and copied from there to the final executable file by the linker,
8804 where it can be read by the debugger. You must use the
8805 @code{-g} switch if you plan on using the debugger.
8806 @end table
8808 @geindex -gnat05 (gcc)
8811 @table @asis
8813 @item @code{-gnat05}
8815 Allow full Ada 2005 features.
8816 @end table
8818 @geindex -gnat12 (gcc)
8821 @table @asis
8823 @item @code{-gnat12}
8825 Allow full Ada 2012 features.
8826 @end table
8828 @geindex -gnat83 (gcc)
8830 @geindex -gnat2005 (gcc)
8833 @table @asis
8835 @item @code{-gnat2005}
8837 Allow full Ada 2005 features (same as @code{-gnat05})
8838 @end table
8840 @geindex -gnat2012 (gcc)
8843 @table @asis
8845 @item @code{-gnat2012}
8847 Allow full Ada 2012 features (same as @code{-gnat12})
8848 @end table
8850 @geindex -gnat2022 (gcc)
8853 @table @asis
8855 @item @code{-gnat2022}
8857 Allow full Ada 2022 features
8859 @item @code{-gnat83}
8861 Enforce Ada 83 restrictions.
8862 @end table
8864 @geindex -gnat95 (gcc)
8867 @table @asis
8869 @item @code{-gnat95}
8871 Enforce Ada 95 restrictions.
8873 Note: for compatibility with some Ada 95 compilers which support only
8874 the @code{overriding} keyword of Ada 2005, the @code{-gnatd.D} switch can
8875 be used along with @code{-gnat95} to achieve a similar effect with GNAT.
8877 @code{-gnatd.D} instructs GNAT to consider @code{overriding} as a keyword
8878 and handle its associated semantic checks, even in Ada 95 mode.
8879 @end table
8881 @geindex -gnata (gcc)
8884 @table @asis
8886 @item @code{-gnata}
8888 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
8889 activated. Note that these pragmas can also be controlled using the
8890 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
8891 It also activates pragmas @code{Check}, @code{Precondition}, and
8892 @code{Postcondition}. Note that these pragmas can also be controlled
8893 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
8894 also activates all assertions defined in the RM as aspects: preconditions,
8895 postconditions, type invariants and (sub)type predicates. In all Ada modes,
8896 corresponding pragmas for type invariants and (sub)type predicates are
8897 also activated. The default is that all these assertions are disabled,
8898 and have no effect, other than being checked for syntactic validity, and
8899 in the case of subtype predicates, constructions such as membership tests
8900 still test predicates even if assertions are turned off.
8901 @end table
8903 @geindex -gnatA (gcc)
8906 @table @asis
8908 @item @code{-gnatA}
8910 Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
8911 it will be ignored.
8912 @end table
8914 @geindex -gnatb (gcc)
8917 @table @asis
8919 @item @code{-gnatb}
8921 Generate brief messages to @code{stderr} even if verbose mode set.
8922 @end table
8924 @geindex -gnatB (gcc)
8927 @table @asis
8929 @item @code{-gnatB}
8931 Assume no invalid (bad) values except for ‘Valid attribute use
8932 (@ref{e9,,Validity Checking}).
8933 @end table
8935 @geindex -gnatc (gcc)
8938 @table @asis
8940 @item @code{-gnatc}
8942 Check syntax and semantics only (no code generation attempted). When the
8943 compiler is invoked by @code{gnatmake}, if the switch @code{-gnatc} is
8944 only given to the compiler (after @code{-cargs} or in package Compiler of
8945 the project file), @code{gnatmake} will fail because it will not find the
8946 object file after compilation. If @code{gnatmake} is called with
8947 @code{-gnatc} as a builder switch (before @code{-cargs} or in package
8948 Builder of the project file) then @code{gnatmake} will not fail because
8949 it will not look for the object files after compilation, and it will not try
8950 to build and link.
8951 @end table
8953 @geindex -gnatC (gcc)
8956 @table @asis
8958 @item @code{-gnatC}
8960 Generate CodePeer intermediate format (no code generation attempted).
8961 This switch will generate an intermediate representation suitable for
8962 use by CodePeer (@code{.scil} files). This switch is not compatible with
8963 code generation (it will, among other things, disable some switches such
8964 as @code{-gnatn}, and enable others such as @code{-gnata}).
8965 @end table
8967 @geindex -gnatd (gcc)
8970 @table @asis
8972 @item @code{-gnatd}
8974 Specify debug options for the compiler. The string of characters after
8975 the @code{-gnatd} specifies the specific debug options. The possible
8976 characters are 0-9, a-z, A-Z, optionally preceded by a dot or underscore.
8977 See compiler source file @code{debug.adb} for details of the implemented
8978 debug options. Certain debug options are relevant to application
8979 programmers, and these are documented at appropriate points in this
8980 user’s guide.
8981 @end table
8983 @geindex -gnatD[nn] (gcc)
8986 @table @asis
8988 @item @code{-gnatD}
8990 Create expanded source files for source level debugging. This switch
8991 also suppresses generation of cross-reference information
8992 (see @code{-gnatx}). Note that this switch is not allowed if a previous
8993 @code{-gnatR} switch has been given, since these two switches are not compatible.
8994 @end table
8996 @geindex -gnateA (gcc)
8999 @table @asis
9001 @item @code{-gnateA}
9003 Check that the actual parameters of a subprogram call are not aliases of one
9004 another. To qualify as aliasing, their memory locations must be identical or
9005 overlapping, at least one of the corresponding formal parameters must be of
9006 mode OUT or IN OUT, and at least one of the corresponding formal parameters
9007 must have its parameter passing mechanism not specified.
9009 @example
9010 type Rec_Typ is record
9011    Data : Integer := 0;
9012 end record;
9014 function Self (Val : Rec_Typ) return Rec_Typ is
9015 begin
9016    return Val;
9017 end Self;
9019 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
9020 begin
9021    null;
9022 end Detect_Aliasing;
9024 Obj : Rec_Typ;
9026 Detect_Aliasing (Obj, Obj);
9027 Detect_Aliasing (Obj, Self (Obj));
9028 @end example
9030 In the example above, the first call to @code{Detect_Aliasing} fails with a
9031 @code{Program_Error} at run time because the actuals for @code{Val_1} and
9032 @code{Val_2} denote the same object. The second call executes without raising
9033 an exception because @code{Self(Obj)} produces an anonymous object which does
9034 not share the memory location of @code{Obj}.
9035 @end table
9037 @geindex -gnateb (gcc)
9040 @table @asis
9042 @item @code{-gnateb}
9044 Store configuration files by their basename in ALI files. This switch is
9045 used for instance by gprbuild for distributed builds in order to prevent
9046 issues where machine-specific absolute paths could end up being stored in
9047 ALI files.
9048 @end table
9050 @geindex -gnatec (gcc)
9053 @table @asis
9055 @item @code{-gnatec=`path'}
9057 Specify a configuration pragma file
9058 (the equal sign is optional)
9059 (@ref{63,,The Configuration Pragmas Files}).
9060 @end table
9062 @geindex -gnateC (gcc)
9065 @table @asis
9067 @item @code{-gnateC}
9069 Generate CodePeer messages in a compiler-like format. This switch is only
9070 effective if @code{-gnatcC} is also specified and requires an installation
9071 of CodePeer.
9072 @end table
9074 @geindex -gnated (gcc)
9077 @table @asis
9079 @item @code{-gnated}
9081 Disable atomic synchronization
9082 @end table
9084 @geindex -gnateD (gcc)
9087 @table @asis
9089 @item @code{-gnateDsymbol[=`value']}
9091 Defines a symbol, associated with @code{value}, for preprocessing.
9092 (@ref{91,,Integrated Preprocessing}).
9093 @end table
9095 @geindex -gnateE (gcc)
9098 @table @asis
9100 @item @code{-gnateE}
9102 Generate extra information in exception messages. In particular, display
9103 extra column information and the value and range associated with index and
9104 range check failures, and extra column information for access checks.
9105 In cases where the compiler is able to determine at compile time that
9106 a check will fail, it gives a warning, and the extra information is not
9107 produced at run time.
9108 @end table
9110 @geindex -gnatef (gcc)
9113 @table @asis
9115 @item @code{-gnatef}
9117 Display full source path name in brief error messages and absolute paths in
9118 @code{-fdiagnostics-format=json}’s output.
9119 @end table
9121 @geindex -gnateF (gcc)
9124 @table @asis
9126 @item @code{-gnateF}
9128 Check for overflow on all floating-point operations, including those
9129 for unconstrained predefined types. See description of pragma
9130 @code{Check_Float_Overflow} in GNAT RM.
9131 @end table
9133 @geindex -gnateg (gcc)
9135 @code{-gnateg}
9136 @code{-gnatceg}
9138 @quotation
9140 The @code{-gnatc} switch must always be specified before this switch, e.g.
9141 @code{-gnatceg}. Generate a C header from the Ada input file. See
9142 @ref{b9,,Generating C Headers for Ada Specifications} for more
9143 information.
9144 @end quotation
9146 @geindex -gnateG (gcc)
9149 @table @asis
9151 @item @code{-gnateG}
9153 Save result of preprocessing in a text file.
9154 @end table
9156 @geindex -gnateH (gcc)
9159 @table @asis
9161 @item @code{-gnateH}
9163 Set the threshold from which the RM 13.5.1(13.3/2) clause applies to 64.
9164 This is useful only on 64-bit plaforms where this threshold is 128, but
9165 used to be 64 in earlier versions of the compiler.
9166 @end table
9168 @geindex -gnatei (gcc)
9171 @table @asis
9173 @item @code{-gnatei`nnn'}
9175 Set maximum number of instantiations during compilation of a single unit to
9176 @code{nnn}. This may be useful in increasing the default maximum of 8000 for
9177 the rare case when a single unit legitimately exceeds this limit.
9178 @end table
9180 @geindex -gnateI (gcc)
9183 @table @asis
9185 @item @code{-gnateI`nnn'}
9187 Indicates that the source is a multi-unit source and that the index of the
9188 unit to compile is @code{nnn}. @code{nnn} needs to be a positive number and need
9189 to be a valid index in the multi-unit source.
9190 @end table
9192 @geindex -gnatel (gcc)
9195 @table @asis
9197 @item @code{-gnatel}
9199 This switch can be used with the static elaboration model to issue info
9200 messages showing
9201 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
9202 are generated. This is useful in diagnosing elaboration circularities
9203 caused by these implicit pragmas when using the static elaboration
9204 model. See the section in this guide on elaboration checking for
9205 further details. These messages are not generated by default, and are
9206 intended only for temporary use when debugging circularity problems.
9207 @end table
9209 @geindex -gnatel (gcc)
9212 @table @asis
9214 @item @code{-gnateL}
9216 This switch turns off the info messages about implicit elaboration pragmas.
9217 @end table
9219 @geindex -gnatem (gcc)
9222 @table @asis
9224 @item @code{-gnatem=`path'}
9226 Specify a mapping file
9227 (the equal sign is optional)
9228 (@ref{ea,,Units to Sources Mapping Files}).
9229 @end table
9231 @geindex -gnatep (gcc)
9234 @table @asis
9236 @item @code{-gnatep=`file'}
9238 Specify a preprocessing data file
9239 (the equal sign is optional)
9240 (@ref{91,,Integrated Preprocessing}).
9241 @end table
9243 @geindex -gnateP (gcc)
9246 @table @asis
9248 @item @code{-gnateP}
9250 Turn categorization dependency errors into warnings.
9251 Ada requires that units that WITH one another have compatible categories, for
9252 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9253 these errors become warnings (which can be ignored, or suppressed in the usual
9254 manner). This can be useful in some specialized circumstances such as the
9255 temporary use of special test software.
9256 @end table
9258 @geindex -gnateS (gcc)
9261 @table @asis
9263 @item @code{-gnateS}
9265 Synonym of @code{-fdump-scos}, kept for backwards compatibility.
9266 @end table
9268 @geindex -gnatet=file (gcc)
9271 @table @asis
9273 @item @code{-gnatet=`path'}
9275 Generate target dependent information. The format of the output file is
9276 described in the section about switch @code{-gnateT}.
9277 @end table
9279 @geindex -gnateT (gcc)
9282 @table @asis
9284 @item @code{-gnateT=`path'}
9286 Read target dependent information, such as endianness or sizes and alignments
9287 of base type. If this switch is passed, the default target dependent
9288 information of the compiler is replaced by the one read from the input file.
9289 This is used by tools other than the compiler, e.g. to do
9290 semantic analysis of programs that will run on some other target than
9291 the machine on which the tool is run.
9293 The following target dependent values should be defined,
9294 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
9295 positive integer value, and fields marked with a question mark are
9296 boolean fields, where a value of 0 is False, and a value of 1 is True:
9298 @example
9299 Bits_BE                    : Nat; -- Bits stored big-endian?
9300 Bits_Per_Unit              : Pos; -- Bits in a storage unit
9301 Bits_Per_Word              : Pos; -- Bits in a word
9302 Bytes_BE                   : Nat; -- Bytes stored big-endian?
9303 Char_Size                  : Pos; -- Standard.Character'Size
9304 Double_Float_Alignment     : Nat; -- Alignment of double float
9305 Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
9306 Double_Size                : Pos; -- Standard.Long_Float'Size
9307 Float_Size                 : Pos; -- Standard.Float'Size
9308 Float_Words_BE             : Nat; -- Float words stored big-endian?
9309 Int_Size                   : Pos; -- Standard.Integer'Size
9310 Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
9311 Long_Long_Long_Size        : Pos; -- Standard.Long_Long_Long_Integer'Size
9312 Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
9313 Long_Size                  : Pos; -- Standard.Long_Integer'Size
9314 Maximum_Alignment          : Pos; -- Maximum permitted alignment
9315 Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
9316 Pointer_Size               : Pos; -- System.Address'Size
9317 Short_Enums                : Nat; -- Foreign enums use short size?
9318 Short_Size                 : Pos; -- Standard.Short_Integer'Size
9319 Strict_Alignment           : Nat; -- Strict alignment?
9320 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9321 Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
9322 Words_BE                   : Nat; -- Words stored big-endian?
9323 @end example
9325 @code{Bits_Per_Unit} is the number of bits in a storage unit, the equivalent of
9326 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.}
9328 @code{Bits_Per_Word} is the number of bits in a machine word, the equivalent of
9329 GCC macro @code{BITS_PER_WORD} documented as follows: @cite{Number of bits in a word; normally 32.}
9331 @code{Double_Float_Alignment}, if not zero, is the maximum alignment that the
9332 compiler can choose by default for a 64-bit floating-point type or object.
9334 @code{Double_Scalar_Alignment}, if not zero, is the maximum alignment that the
9335 compiler can choose by default for a 64-bit or larger scalar type or object.
9337 @code{Maximum_Alignment} is the maximum alignment that the compiler can choose
9338 by default for a type or object, which is also the maximum alignment that can
9339 be specified in GNAT. It is computed for GCC backends as @code{BIGGEST_ALIGNMENT
9340 / BITS_PER_UNIT} where GCC macro @code{BIGGEST_ALIGNMENT} is documented as
9341 follows: @cite{Biggest alignment that any data type can require on this machine@comma{} in bits.}
9343 @code{Max_Unaligned_Field} is the maximum size for unaligned bit field, which is
9344 64 for the majority of GCC targets (but can be different on some targets).
9346 @code{Strict_Alignment} is the equivalent of GCC macro @code{STRICT_ALIGNMENT}
9347 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.}
9349 @code{System_Allocator_Alignment} is the guaranteed alignment of data returned
9350 by calls to @code{malloc}.
9352 The format of the input file is as follows. First come the values of
9353 the variables defined above, with one line per value:
9355 @example
9356 name  value
9357 @end example
9359 where @code{name} is the name of the parameter, spelled out in full,
9360 and cased as in the above list, and @code{value} is an unsigned decimal
9361 integer. Two or more blanks separates the name from the value.
9363 All the variables must be present, in alphabetical order (i.e. the
9364 same order as the list above).
9366 Then there is a blank line to separate the two parts of the file. Then
9367 come the lines showing the floating-point types to be registered, with
9368 one line per registered mode:
9370 @example
9371 name  digs float_rep size alignment
9372 @end example
9374 where @code{name} is the string name of the type (which can have
9375 single spaces embedded in the name, e.g. long double), @code{digs} is
9376 the number of digits for the floating-point type, @code{float_rep} is
9377 the float representation (I for IEEE-754-Binary, which is
9378 the only one supported at this time),
9379 @code{size} is the size in bits, @code{alignment} is the
9380 alignment in bits. The name is followed by at least two blanks, fields
9381 are separated by at least one blank, and a LF character immediately
9382 follows the alignment field.
9384 Here is an example of a target parameterization file:
9386 @example
9387 Bits_BE                       0
9388 Bits_Per_Unit                 8
9389 Bits_Per_Word                64
9390 Bytes_BE                      0
9391 Char_Size                     8
9392 Double_Float_Alignment        0
9393 Double_Scalar_Alignment       0
9394 Double_Size                  64
9395 Float_Size                   32
9396 Float_Words_BE                0
9397 Int_Size                     64
9398 Long_Double_Size            128
9399 Long_Long_Long_Size         128
9400 Long_Long_Size               64
9401 Long_Size                    64
9402 Maximum_Alignment            16
9403 Max_Unaligned_Field          64
9404 Pointer_Size                 64
9405 Short_Size                   16
9406 Strict_Alignment              0
9407 System_Allocator_Alignment   16
9408 Wchar_T_Size                 32
9409 Words_BE                      0
9411 float         15  I  64  64
9412 double        15  I  64  64
9413 long double   18  I  80 128
9414 TF            33  I 128 128
9415 @end example
9416 @end table
9418 @geindex -gnateu (gcc)
9421 @table @asis
9423 @item @code{-gnateu}
9425 Ignore unrecognized validity, warning, and style switches that
9426 appear after this switch is given. This may be useful when
9427 compiling sources developed on a later version of the compiler
9428 with an earlier version. Of course the earlier version must
9429 support this switch.
9430 @end table
9432 @geindex -gnateV (gcc)
9435 @table @asis
9437 @item @code{-gnateV}
9439 Check that all actual parameters of a subprogram call are valid according to
9440 the rules of validity checking (@ref{e9,,Validity Checking}).
9441 @end table
9443 @geindex -gnateY (gcc)
9446 @table @asis
9448 @item @code{-gnateY}
9450 Ignore all STYLE_CHECKS pragmas. Full legality checks
9451 are still carried out, but the pragmas have no effect
9452 on what style checks are active. This allows all style
9453 checking options to be controlled from the command line.
9454 @end table
9456 @geindex -gnatE (gcc)
9459 @table @asis
9461 @item @code{-gnatE}
9463 Dynamic elaboration checking mode enabled. For further details see
9464 @ref{f,,Elaboration Order Handling in GNAT}.
9465 @end table
9467 @geindex -gnatf (gcc)
9470 @table @asis
9472 @item @code{-gnatf}
9474 Full errors. Multiple errors per line, all undefined references, do not
9475 attempt to suppress cascaded errors.
9476 @end table
9478 @geindex -gnatF (gcc)
9481 @table @asis
9483 @item @code{-gnatF}
9485 Externals names are folded to all uppercase.
9486 @end table
9488 @geindex -gnatg (gcc)
9491 @table @asis
9493 @item @code{-gnatg}
9495 Internal GNAT implementation mode. This should not be used for applications
9496 programs, it is intended only for use by the compiler and its run-time
9497 library. For documentation, see the GNAT sources. Note that @code{-gnatg}
9498 implies @code{-gnatw.ge} and @code{-gnatyg} so that all standard
9499 warnings and all standard style options are turned on. All warnings and style
9500 messages are treated as errors.
9501 @end table
9503 @geindex -gnatG[nn] (gcc)
9506 @table @asis
9508 @item @code{-gnatG=nn}
9510 List generated expanded code in source form.
9511 @end table
9513 @geindex -gnath (gcc)
9516 @table @asis
9518 @item @code{-gnath}
9520 Output usage information. The output is written to @code{stdout}.
9521 @end table
9523 @geindex -gnatH (gcc)
9526 @table @asis
9528 @item @code{-gnatH}
9530 Legacy elaboration-checking mode enabled. When this switch is in effect,
9531 the pre-18.x access-before-elaboration model becomes the de facto model.
9532 For further details see @ref{f,,Elaboration Order Handling in GNAT}.
9533 @end table
9535 @geindex -gnati (gcc)
9538 @table @asis
9540 @item @code{-gnati`c'}
9542 Identifier character set (@code{c} = 1/2/3/4/5/9/p/8/f/n/w).
9543 For details of the possible selections for @code{c},
9544 see @ref{31,,Character Set Control}.
9545 @end table
9547 @geindex -gnatI (gcc)
9550 @table @asis
9552 @item @code{-gnatI}
9554 Ignore representation clauses. When this switch is used,
9555 representation clauses are treated as comments. This is useful
9556 when initially porting code where you want to ignore rep clause
9557 problems, and also for compiling foreign code (particularly
9558 for use with ASIS). The representation clauses that are ignored
9559 are: enumeration_representation_clause, record_representation_clause,
9560 and attribute_definition_clause for the following attributes:
9561 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9562 Object_Size, Scalar_Storage_Order, Size, Small, Stream_Size,
9563 and Value_Size. Pragma Default_Scalar_Storage_Order is also ignored.
9564 Note that this option should be used only for compiling – the
9565 code is likely to malfunction at run time.
9566 @end table
9568 @geindex -gnatjnn (gcc)
9571 @table @asis
9573 @item @code{-gnatj`nn'}
9575 Reformat error messages to fit on @code{nn} character lines
9576 @end table
9578 @geindex -gnatJ (gcc)
9581 @table @asis
9583 @item @code{-gnatJ}
9585 Permissive elaboration-checking mode enabled. When this switch is in effect,
9586 the post-18.x access-before-elaboration model ignores potential issues with:
9589 @itemize -
9591 @item 
9592 Accept statements
9594 @item 
9595 Activations of tasks defined in instances
9597 @item 
9598 Assertion pragmas
9600 @item 
9601 Calls from within an instance to its enclosing context
9603 @item 
9604 Calls through generic formal parameters
9606 @item 
9607 Calls to subprograms defined in instances
9609 @item 
9610 Entry calls
9612 @item 
9613 Indirect calls using ‘Access
9615 @item 
9616 Requeue statements
9618 @item 
9619 Select statements
9621 @item 
9622 Synchronous task suspension
9623 @end itemize
9625 and does not emit compile-time diagnostics or run-time checks. For further
9626 details see @ref{f,,Elaboration Order Handling in GNAT}.
9627 @end table
9629 @geindex -gnatk (gcc)
9632 @table @asis
9634 @item @code{-gnatk=`n'}
9636 Limit file names to @code{n} (1-999) characters (@code{k} = krunch).
9637 @end table
9639 @geindex -gnatl (gcc)
9642 @table @asis
9644 @item @code{-gnatl}
9646 Output full source listing with embedded error messages.
9647 @end table
9649 @geindex -gnatL (gcc)
9652 @table @asis
9654 @item @code{-gnatL}
9656 Used in conjunction with -gnatG or -gnatD to intersperse original
9657 source lines (as comment lines with line numbers) in the expanded
9658 source output.
9659 @end table
9661 @geindex -gnatm (gcc)
9664 @table @asis
9666 @item @code{-gnatm=`n'}
9668 Limit number of detected error or warning messages to @code{n}
9669 where @code{n} is in the range 1..999999. The default setting if
9670 no switch is given is 9999. If the number of warnings reaches this
9671 limit, then a message is output and further warnings are suppressed,
9672 but the compilation is continued. If the number of error messages
9673 reaches this limit, then a message is output and the compilation
9674 is abandoned. The equal sign here is optional. A value of zero
9675 means that no limit applies.
9676 @end table
9678 @geindex -gnatn (gcc)
9681 @table @asis
9683 @item @code{-gnatn[12]}
9685 Activate inlining across units for subprograms for which pragma @code{Inline}
9686 is specified. This inlining is performed by the GCC back-end. An optional
9687 digit sets the inlining level: 1 for moderate inlining across units
9688 or 2 for full inlining across units. If no inlining level is specified,
9689 the compiler will pick it based on the optimization level.
9690 @end table
9692 @geindex -gnatN (gcc)
9695 @table @asis
9697 @item @code{-gnatN}
9699 Activate front end inlining for subprograms for which
9700 pragma @code{Inline} is specified. This inlining is performed
9701 by the front end and will be visible in the
9702 @code{-gnatG} output.
9704 When using a gcc-based back end, then the use of
9705 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
9706 Historically front end inlining was more extensive than the gcc back end
9707 inlining, but that is no longer the case.
9708 @end table
9710 @geindex -gnato0 (gcc)
9713 @table @asis
9715 @item @code{-gnato0}
9717 Suppresses overflow checking. This causes the behavior of the compiler to
9718 match the default for older versions where overflow checking was suppressed
9719 by default. This is equivalent to having
9720 @code{pragma Suppress (Overflow_Check)} in a configuration pragma file.
9721 @end table
9723 @geindex -gnato?? (gcc)
9726 @table @asis
9728 @item @code{-gnato??}
9730 Set default mode for handling generation of code to avoid intermediate
9731 arithmetic overflow. Here @code{??} is two digits, a
9732 single digit, or nothing. Each digit is one of the digits @code{1}
9733 through @code{3}:
9736 @multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
9737 @item
9739 Digit
9741 @tab
9743 Interpretation
9745 @item
9749 @tab
9751 All intermediate overflows checked against base type (@code{STRICT})
9753 @item
9757 @tab
9759 Minimize intermediate overflows (@code{MINIMIZED})
9761 @item
9765 @tab
9767 Eliminate intermediate overflows (@code{ELIMINATED})
9769 @end multitable
9772 If only one digit appears, then it applies to all
9773 cases; if two digits are given, then the first applies outside
9774 assertions, pre/postconditions, and type invariants, and the second
9775 applies within assertions, pre/postconditions, and type invariants.
9777 If no digits follow the @code{-gnato}, then it is equivalent to
9778 @code{-gnato11},
9779 causing all intermediate overflows to be handled in strict
9780 mode.
9782 This switch also causes arithmetic overflow checking to be performed
9783 (as though @code{pragma Unsuppress (Overflow_Check)} had been specified).
9785 The default if no option @code{-gnato} is given is that overflow handling
9786 is in @code{STRICT} mode (computations done using the base type), and that
9787 overflow checking is enabled.
9789 Note that division by zero is a separate check that is not
9790 controlled by this switch (divide-by-zero checking is on by default).
9792 See also @ref{eb,,Specifying the Desired Mode}.
9793 @end table
9795 @geindex -gnatp (gcc)
9798 @table @asis
9800 @item @code{-gnatp}
9802 Suppress all checks. See @ref{ec,,Run-Time Checks} for details. This switch
9803 has no effect if cancelled by a subsequent @code{-gnat-p} switch.
9804 @end table
9806 @geindex -gnat-p (gcc)
9809 @table @asis
9811 @item @code{-gnat-p}
9813 Cancel effect of previous @code{-gnatp} switch.
9814 @end table
9816 @geindex -gnatq (gcc)
9819 @table @asis
9821 @item @code{-gnatq}
9823 Don’t quit. Try semantics, even if parse errors.
9824 @end table
9826 @geindex -gnatQ (gcc)
9829 @table @asis
9831 @item @code{-gnatQ}
9833 Don’t quit. Generate @code{ALI} and tree files even if illegalities.
9834 Note that code generation is still suppressed in the presence of any
9835 errors, so even with @code{-gnatQ} no object file is generated.
9836 @end table
9838 @geindex -gnatr (gcc)
9841 @table @asis
9843 @item @code{-gnatr}
9845 Treat pragma Restrictions as Restriction_Warnings.
9846 @end table
9848 @geindex -gnatR (gcc)
9851 @table @asis
9853 @item @code{-gnatR[0|1|2|3|4][e][j][m][s]}
9855 Output representation information for declared types, objects and
9856 subprograms. Note that this switch is not allowed if a previous
9857 @code{-gnatD} switch has been given, since these two switches
9858 are not compatible.
9859 @end table
9861 @geindex -gnats (gcc)
9864 @table @asis
9866 @item @code{-gnats}
9868 Syntax check only.
9869 @end table
9871 @geindex -gnatS (gcc)
9874 @table @asis
9876 @item @code{-gnatS}
9878 Print package Standard.
9879 @end table
9881 @geindex -gnatT (gcc)
9884 @table @asis
9886 @item @code{-gnatT`nnn'}
9888 All compiler tables start at @code{nnn} times usual starting size.
9889 @end table
9891 @geindex -gnatu (gcc)
9894 @table @asis
9896 @item @code{-gnatu}
9898 List units for this compilation.
9899 @end table
9901 @geindex -gnatU (gcc)
9904 @table @asis
9906 @item @code{-gnatU}
9908 Tag all error messages with the unique string ‘error:’
9909 @end table
9911 @geindex -gnatv (gcc)
9914 @table @asis
9916 @item @code{-gnatv}
9918 Verbose mode. Full error output with source lines to @code{stdout}.
9919 @end table
9921 @geindex -gnatV (gcc)
9924 @table @asis
9926 @item @code{-gnatV}
9928 Control level of validity checking (@ref{e9,,Validity Checking}).
9929 @end table
9931 @geindex -gnatw (gcc)
9934 @table @asis
9936 @item @code{-gnatw`xxx'}
9938 Warning mode where
9939 @code{xxx} is a string of option letters that denotes
9940 the exact warnings that
9941 are enabled or disabled (@ref{ed,,Warning Message Control}).
9942 @end table
9944 @geindex -gnatW (gcc)
9947 @table @asis
9949 @item @code{-gnatW`e'}
9951 Wide character encoding method
9952 (@code{e}=n/h/u/s/e/8).
9953 @end table
9955 @geindex -gnatx (gcc)
9958 @table @asis
9960 @item @code{-gnatx}
9962 Suppress generation of cross-reference information.
9963 @end table
9965 @geindex -gnatX (gcc)
9968 @table @asis
9970 @item @code{-gnatX}
9972 Enable core GNAT implementation extensions and latest Ada version.
9973 @end table
9975 @geindex -gnatX0 (gcc)
9978 @table @asis
9980 @item @code{-gnatX0}
9982 Enable all GNAT implementation extensions and latest Ada version.
9983 @end table
9985 @geindex -gnaty (gcc)
9988 @table @asis
9990 @item @code{-gnaty}
9992 Enable built-in style checks (@ref{ee,,Style Checking}).
9993 @end table
9995 @geindex -gnatz (gcc)
9998 @table @asis
10000 @item @code{-gnatz`m'}
10002 Distribution stub generation and compilation
10003 (@code{m}=r/c for receiver/caller stubs).
10004 @end table
10006 @geindex -I (gcc)
10009 @table @asis
10011 @item @code{-I`dir'}
10013 @geindex RTL
10015 Direct GNAT to search the @code{dir} directory for source files needed by
10016 the current compilation
10017 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
10018 @end table
10020 @geindex -I- (gcc)
10023 @table @asis
10025 @item @code{-I-}
10027 @geindex RTL
10029 Except for the source file named in the command line, do not look for source
10030 files in the directory containing the source file named in the command line
10031 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
10032 @end table
10034 @geindex -o (gcc)
10037 @table @asis
10039 @item @code{-o `file'}
10041 This switch is used in @code{gcc} to redirect the generated object file
10042 and its associated ALI file. Beware of this switch with GNAT, because it may
10043 cause the object file and ALI file to have different names which in turn
10044 may confuse the binder and the linker.
10045 @end table
10047 @geindex -nostdinc (gcc)
10050 @table @asis
10052 @item @code{-nostdinc}
10054 Inhibit the search of the default location for the GNAT Run Time
10055 Library (RTL) source files.
10056 @end table
10058 @geindex -nostdlib (gcc)
10061 @table @asis
10063 @item @code{-nostdlib}
10065 Inhibit the search of the default location for the GNAT Run Time
10066 Library (RTL) ALI files.
10067 @end table
10069 @geindex -O (gcc)
10072 @table @asis
10074 @item @code{-O[`n']}
10076 @code{n} controls the optimization level:
10079 @multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
10080 @item
10084 @tab
10086 Effect
10088 @item
10092 @tab
10094 No optimization, the default setting if no @code{-O} appears
10096 @item
10100 @tab
10102 Normal optimization, the default if you specify @code{-O} without an
10103 operand. A good compromise between code quality and compilation
10104 time.
10106 @item
10110 @tab
10112 Extensive optimization, may improve execution time, possibly at
10113 the cost of substantially increased compilation time.
10115 @item
10119 @tab
10121 Same as @code{-O2}, and also includes inline expansion for small
10122 subprograms in the same unit.
10124 @item
10128 @tab
10130 Optimize space usage
10132 @end multitable
10135 See also @ref{ef,,Optimization Levels}.
10136 @end table
10138 @geindex -pass-exit-codes (gcc)
10141 @table @asis
10143 @item @code{-pass-exit-codes}
10145 Catch exit codes from the compiler and use the most meaningful as
10146 exit status.
10147 @end table
10149 @geindex --RTS (gcc)
10152 @table @asis
10154 @item @code{--RTS=`rts-path'}
10156 Specifies the default location of the run-time library. Same meaning as the
10157 equivalent @code{gnatmake} flag (@ref{d0,,Switches for gnatmake}).
10158 @end table
10160 @geindex -S (gcc)
10163 @table @asis
10165 @item @code{-S}
10167 Used in place of @code{-c} to
10168 cause the assembler source file to be
10169 generated, using @code{.s} as the extension,
10170 instead of the object file.
10171 This may be useful if you need to examine the generated assembly code.
10172 @end table
10174 @geindex -fverbose-asm (gcc)
10177 @table @asis
10179 @item @code{-fverbose-asm}
10181 Used in conjunction with @code{-S}
10182 to cause the generated assembly code file to be annotated with variable
10183 names, making it significantly easier to follow.
10184 @end table
10186 @geindex -v (gcc)
10189 @table @asis
10191 @item @code{-v}
10193 Show commands generated by the @code{gcc} driver. Normally used only for
10194 debugging purposes or if you need to be sure what version of the
10195 compiler you are executing.
10196 @end table
10198 @geindex -V (gcc)
10201 @table @asis
10203 @item @code{-V `ver'}
10205 Execute @code{ver} version of the compiler. This is the @code{gcc}
10206 version, not the GNAT version.
10207 @end table
10209 @geindex -w (gcc)
10212 @table @asis
10214 @item @code{-w}
10216 Turn off warnings generated by the back end of the compiler. Use of
10217 this switch also causes the default for front end warnings to be set
10218 to suppress (as though @code{-gnatws} had appeared at the start of
10219 the options).
10220 @end table
10222 @geindex Combining GNAT switches
10224 You may combine a sequence of GNAT switches into a single switch. For
10225 example, the combined switch
10227 @quotation
10229 @example
10230 -gnatofi3
10231 @end example
10232 @end quotation
10234 is equivalent to specifying the following sequence of switches:
10236 @quotation
10238 @example
10239 -gnato -gnatf -gnati3
10240 @end example
10241 @end quotation
10243 The following restrictions apply to the combination of switches
10244 in this manner:
10247 @itemize *
10249 @item 
10250 The switch @code{-gnatc} if combined with other switches must come
10251 first in the string.
10253 @item 
10254 The switch @code{-gnats} if combined with other switches must come
10255 first in the string.
10257 @item 
10258 The switches
10259 @code{-gnatzc} and @code{-gnatzr} may not be combined with any other
10260 switches, and only one of them may appear in the command line.
10262 @item 
10263 The switch @code{-gnat-p} may not be combined with any other switch.
10265 @item 
10266 Once a ‘y’ appears in the string (that is a use of the @code{-gnaty}
10267 switch), then all further characters in the switch are interpreted
10268 as style modifiers (see description of @code{-gnaty}).
10270 @item 
10271 Once a ‘d’ appears in the string (that is a use of the @code{-gnatd}
10272 switch), then all further characters in the switch are interpreted
10273 as debug flags (see description of @code{-gnatd}).
10275 @item 
10276 Once a ‘w’ appears in the string (that is a use of the @code{-gnatw}
10277 switch), then all further characters in the switch are interpreted
10278 as warning mode modifiers (see description of @code{-gnatw}).
10280 @item 
10281 Once a ‘V’ appears in the string (that is a use of the @code{-gnatV}
10282 switch), then all further characters in the switch are interpreted
10283 as validity checking options (@ref{e9,,Validity Checking}).
10285 @item 
10286 Option ‘em’, ‘ec’, ‘ep’, ‘l=’ and ‘R’ must be the last options in
10287 a combined list of options.
10288 @end itemize
10290 @node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10291 @anchor{gnat_ugn/building_executable_programs_with_gnat id14}@anchor{f0}@anchor{gnat_ugn/building_executable_programs_with_gnat output-and-error-message-control}@anchor{f1}
10292 @subsection Output and Error Message Control
10295 @geindex stderr
10297 The standard default format for error messages is called ‘brief format’.
10298 Brief format messages are written to @code{stderr} (the standard error
10299 file) and have the following form:
10301 @example
10302 e.adb:3:04: Incorrect spelling of keyword "function"
10303 e.adb:4:20: ";" should be "is"
10304 @end example
10306 The first integer after the file name is the line number in the file,
10307 and the second integer is the column number within the line.
10308 @code{GNAT Studio} can parse the error messages
10309 and point to the referenced character.
10310 The following switches provide control over the error message
10311 format:
10313 @geindex -gnatv (gcc)
10316 @table @asis
10318 @item @code{-gnatv}
10320 The @code{v} stands for verbose.
10321 The effect of this setting is to write long-format error
10322 messages to @code{stdout} (the standard output file).
10323 The same program compiled with the
10324 @code{-gnatv} switch would generate:
10326 @example
10327 3. funcion X (Q : Integer)
10328    |
10329 >>> Incorrect spelling of keyword "function"
10330 4. return Integer;
10331                  |
10332 >>> ";" should be "is"
10333 @end example
10335 The vertical bar indicates the location of the error, and the @code{>>>}
10336 prefix can be used to search for error messages. When this switch is
10337 used the only source lines output are those with errors.
10338 @end table
10340 @geindex -gnatl (gcc)
10343 @table @asis
10345 @item @code{-gnatl}
10347 The @code{l} stands for list.
10348 This switch causes a full listing of
10349 the file to be generated. In the case where a body is
10350 compiled, the corresponding spec is also listed, along
10351 with any subunits. Typical output from compiling a package
10352 body @code{p.adb} might look like:
10354 @example
10355 Compiling: p.adb
10357      1. package body p is
10358      2.    procedure a;
10359      3.    procedure a is separate;
10360      4. begin
10361      5.    null
10362                |
10363         >>> missing ";"
10365      6. end;
10367 Compiling: p.ads
10369      1. package p is
10370      2.    pragma Elaborate_Body
10371                                 |
10372         >>> missing ";"
10374      3. end p;
10376 Compiling: p-a.adb
10378      1. separate p
10379                 |
10380         >>> missing "("
10382      2. procedure a is
10383      3. begin
10384      4.    null
10385                |
10386         >>> missing ";"
10388      5. end;
10389 @end example
10391 When you specify the @code{-gnatv} or @code{-gnatl} switches and
10392 standard output is redirected, a brief summary is written to
10393 @code{stderr} (standard error) giving the number of error messages and
10394 warning messages generated.
10395 @end table
10397 @geindex -gnatl=fname (gcc)
10400 @table @asis
10402 @item @code{-gnatl=`fname'}
10404 This has the same effect as @code{-gnatl} except that the output is
10405 written to a file instead of to standard output. If the given name
10406 @code{fname} does not start with a period, then it is the full name
10407 of the file to be written. If @code{fname} is an extension, it is
10408 appended to the name of the file being compiled. For example, if
10409 file @code{xyz.adb} is compiled with @code{-gnatl=.lst},
10410 then the output is written to file xyz.adb.lst.
10411 @end table
10413 @geindex -gnatU (gcc)
10416 @table @asis
10418 @item @code{-gnatU}
10420 This switch forces all error messages to be preceded by the unique
10421 string ‘error:’. This means that error messages take a few more
10422 characters in space, but allows easy searching for and identification
10423 of error messages.
10424 @end table
10426 @geindex -gnatb (gcc)
10429 @table @asis
10431 @item @code{-gnatb}
10433 The @code{b} stands for brief.
10434 This switch causes GNAT to generate the
10435 brief format error messages to @code{stderr} (the standard error
10436 file) as well as the verbose
10437 format message or full listing (which as usual is written to
10438 @code{stdout}, the standard output file).
10439 @end table
10441 @geindex -gnatm (gcc)
10444 @table @asis
10446 @item @code{-gnatm=`n'}
10448 The @code{m} stands for maximum.
10449 @code{n} is a decimal integer in the
10450 range of 1 to 999999 and limits the number of error or warning
10451 messages to be generated. For example, using
10452 @code{-gnatm2} might yield
10454 @example
10455 e.adb:3:04: Incorrect spelling of keyword "function"
10456 e.adb:5:35: missing ".."
10457 fatal error: maximum number of errors detected
10458 compilation abandoned
10459 @end example
10461 The default setting if
10462 no switch is given is 9999. If the number of warnings reaches this
10463 limit, then a message is output and further warnings are suppressed,
10464 but the compilation is continued. If the number of error messages
10465 reaches this limit, then a message is output and the compilation
10466 is abandoned. A value of zero means that no limit applies.
10468 Note that the equal sign is optional, so the switches
10469 @code{-gnatm2} and @code{-gnatm=2} are equivalent.
10470 @end table
10472 @geindex -gnatf (gcc)
10475 @table @asis
10477 @item @code{-gnatf}
10479 @geindex Error messages
10480 @geindex suppressing
10482 The @code{f} stands for full.
10483 Normally, the compiler suppresses error messages that are likely to be
10484 redundant. This switch causes all error
10485 messages to be generated. In particular, in the case of
10486 references to undefined variables. If a given variable is referenced
10487 several times, the normal format of messages is
10489 @example
10490 e.adb:7:07: "V" is undefined (more references follow)
10491 @end example
10493 where the parenthetical comment warns that there are additional
10494 references to the variable @code{V}. Compiling the same program with the
10495 @code{-gnatf} switch yields
10497 @example
10498 e.adb:7:07: "V" is undefined
10499 e.adb:8:07: "V" is undefined
10500 e.adb:8:12: "V" is undefined
10501 e.adb:8:16: "V" is undefined
10502 e.adb:9:07: "V" is undefined
10503 e.adb:9:12: "V" is undefined
10504 @end example
10506 The @code{-gnatf} switch also generates additional information for
10507 some error messages.  Some examples are:
10510 @itemize *
10512 @item 
10513 Details on possibly non-portable unchecked conversion
10515 @item 
10516 List possible interpretations for ambiguous calls
10518 @item 
10519 Additional details on incorrect parameters
10520 @end itemize
10521 @end table
10523 @geindex -gnatjnn (gcc)
10526 @table @asis
10528 @item @code{-gnatjnn}
10530 In normal operation mode (or if @code{-gnatj0} is used), then error messages
10531 with continuation lines are treated as though the continuation lines were
10532 separate messages (and so a warning with two continuation lines counts as
10533 three warnings, and is listed as three separate messages).
10535 If the @code{-gnatjnn} switch is used with a positive value for nn, then
10536 messages are output in a different manner. A message and all its continuation
10537 lines are treated as a unit, and count as only one warning or message in the
10538 statistics totals. Furthermore, the message is reformatted so that no line
10539 is longer than nn characters.
10540 @end table
10542 @geindex -gnatq (gcc)
10545 @table @asis
10547 @item @code{-gnatq}
10549 The @code{q} stands for quit (really ‘don’t quit’).
10550 In normal operation mode, the compiler first parses the program and
10551 determines if there are any syntax errors. If there are, appropriate
10552 error messages are generated and compilation is immediately terminated.
10553 This switch tells
10554 GNAT to continue with semantic analysis even if syntax errors have been
10555 found. This may enable the detection of more errors in a single run. On
10556 the other hand, the semantic analyzer is more likely to encounter some
10557 internal fatal error when given a syntactically invalid tree.
10558 @end table
10560 @geindex -gnatQ (gcc)
10563 @table @asis
10565 @item @code{-gnatQ}
10567 In normal operation mode, the @code{ALI} file is not generated if any
10568 illegalities are detected in the program. The use of @code{-gnatQ} forces
10569 generation of the @code{ALI} file. This file is marked as being in
10570 error, so it cannot be used for binding purposes, but it does contain
10571 reasonably complete cross-reference information, and thus may be useful
10572 for use by tools (e.g., semantic browsing tools or integrated development
10573 environments) that are driven from the @code{ALI} file. This switch
10574 implies @code{-gnatq}, since the semantic phase must be run to get a
10575 meaningful ALI file.
10577 When @code{-gnatQ} is used and the generated @code{ALI} file is marked as
10578 being in error, @code{gnatmake} will attempt to recompile the source when it
10579 finds such an @code{ALI} file, including with switch @code{-gnatc}.
10581 Note that @code{-gnatQ} has no effect if @code{-gnats} is specified,
10582 since ALI files are never generated if @code{-gnats} is set.
10583 @end table
10585 @node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10586 @anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{f2}@anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{ed}
10587 @subsection Warning Message Control
10590 @geindex Warning messages
10592 In addition to error messages, which correspond to illegalities as defined
10593 in the Ada Reference Manual, the compiler detects two kinds of warning
10594 situations.
10596 First, the compiler considers some constructs suspicious and generates a
10597 warning message to alert you to a possible error. Second, if the
10598 compiler detects a situation that is sure to raise an exception at
10599 run time, it generates a warning message. The following shows an example
10600 of warning messages:
10602 @example
10603 e.adb:4:24: warning: creation of object may raise Storage_Error
10604 e.adb:10:17: warning: static value out of range
10605 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10606 @end example
10608 GNAT considers a large number of situations as appropriate
10609 for the generation of warning messages. As always, warnings are not
10610 definite indications of errors. For example, if you do an out-of-range
10611 assignment with the deliberate intention of raising a
10612 @code{Constraint_Error} exception, then the warning that may be
10613 issued does not indicate an error. Some of the situations for which GNAT
10614 issues warnings (at least some of the time) are given in the following
10615 list. This list is not complete, and new warnings are often added to
10616 subsequent versions of GNAT. The list is intended to give a general idea
10617 of the kinds of warnings that are generated.
10620 @itemize *
10622 @item 
10623 Possible infinitely recursive calls
10625 @item 
10626 Out-of-range values being assigned
10628 @item 
10629 Possible order of elaboration problems
10631 @item 
10632 Size not a multiple of alignment for a record type
10634 @item 
10635 Assertions (pragma Assert) that are sure to fail
10637 @item 
10638 Unreachable code
10640 @item 
10641 Address clauses with possibly unaligned values, or where an attempt is
10642 made to overlay a smaller variable with a larger one.
10644 @item 
10645 Fixed-point type declarations with a null range
10647 @item 
10648 Direct_IO or Sequential_IO instantiated with a type that has access values
10650 @item 
10651 Variables that are never assigned a value
10653 @item 
10654 Variables that are referenced before being initialized
10656 @item 
10657 Task entries with no corresponding @code{accept} statement
10659 @item 
10660 Duplicate accepts for the same task entry in a @code{select}
10662 @item 
10663 Objects that take too much storage
10665 @item 
10666 Unchecked conversion between types of differing sizes
10668 @item 
10669 Missing @code{return} statement along some execution path in a function
10671 @item 
10672 Incorrect (unrecognized) pragmas
10674 @item 
10675 Incorrect external names
10677 @item 
10678 Allocation from empty storage pool
10680 @item 
10681 Potentially blocking operation in protected type
10683 @item 
10684 Suspicious parenthesization of expressions
10686 @item 
10687 Mismatching bounds in an aggregate
10689 @item 
10690 Attempt to return local value by reference
10692 @item 
10693 Premature instantiation of a generic body
10695 @item 
10696 Attempt to pack aliased components
10698 @item 
10699 Out of bounds array subscripts
10701 @item 
10702 Wrong length on string assignment
10704 @item 
10705 Violations of style rules if style checking is enabled
10707 @item 
10708 Unused `with' clauses
10710 @item 
10711 @code{Bit_Order} usage that does not have any effect
10713 @item 
10714 @code{Standard.Duration} used to resolve universal fixed expression
10716 @item 
10717 Dereference of possibly null value
10719 @item 
10720 Declaration that is likely to cause storage error
10722 @item 
10723 Internal GNAT unit `with'ed by application unit
10725 @item 
10726 Values known to be out of range at compile time
10728 @item 
10729 Unreferenced or unmodified variables. Note that a special
10730 exemption applies to variables which contain any of the substrings
10731 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
10732 are considered likely to be intentionally used in a situation where
10733 otherwise a warning would be given, so warnings of this kind are
10734 always suppressed for such variables.
10736 @item 
10737 Address overlays that could clobber memory
10739 @item 
10740 Unexpected initialization when address clause present
10742 @item 
10743 Bad alignment for address clause
10745 @item 
10746 Useless type conversions
10748 @item 
10749 Redundant assignment statements and other redundant constructs
10751 @item 
10752 Useless exception handlers
10754 @item 
10755 Accidental hiding of name by child unit
10757 @item 
10758 Access before elaboration detected at compile time
10760 @item 
10761 A range in a @code{for} loop that is known to be null or might be null
10762 @end itemize
10764 The following section lists compiler switches that are available
10765 to control the handling of warning messages. It is also possible
10766 to exercise much finer control over what warnings are issued and
10767 suppressed using the GNAT pragma Warnings (see the description
10768 of the pragma in the @cite{GNAT_Reference_manual}).
10770 @geindex -gnatwa (gcc)
10773 @table @asis
10775 @item @code{-gnatwa}
10777 `Activate most optional warnings.'
10779 This switch activates most optional warning messages. See the remaining list
10780 in this section for details on optional warning messages that can be
10781 individually controlled.  The warnings that are not turned on by this
10782 switch are:
10785 @itemize *
10787 @item 
10788 @code{-gnatwd} (implicit dereferencing)
10790 @item 
10791 @code{-gnatw.d} (tag warnings with -gnatw switch)
10793 @item 
10794 @code{-gnatwh} (hiding)
10796 @item 
10797 @code{-gnatw.h} (holes in record layouts)
10799 @item 
10800 @code{-gnatw.j} (late primitives of tagged types)
10802 @item 
10803 @code{-gnatw.k} (redefinition of names in standard)
10805 @item 
10806 @code{-gnatwl} (elaboration warnings)
10808 @item 
10809 @code{-gnatw.l} (inherited aspects)
10811 @item 
10812 @code{-gnatw.n} (atomic synchronization)
10814 @item 
10815 @code{-gnatwo} (address clause overlay)
10817 @item 
10818 @code{-gnatw.o} (values set by out parameters ignored)
10820 @item 
10821 @code{-gnatw.q} (questionable layout of record types)
10823 @item 
10824 @code{-gnatw_q} (ignored equality)
10826 @item 
10827 @code{-gnatw_r} (out-of-order record representation clauses)
10829 @item 
10830 @code{-gnatw.s} (overridden size clause)
10832 @item 
10833 @code{-gnatw_s} (ineffective predicate test)
10835 @item 
10836 @code{-gnatwt} (tracking of deleted conditional code)
10838 @item 
10839 @code{-gnatw.u} (unordered enumeration)
10841 @item 
10842 @code{-gnatw.w} (use of Warnings Off)
10844 @item 
10845 @code{-gnatw.y} (reasons for package needing body)
10846 @end itemize
10848 All other optional warnings are turned on.
10849 @end table
10851 @geindex -gnatwA (gcc)
10854 @table @asis
10856 @item @code{-gnatwA}
10858 `Suppress all optional errors.'
10860 This switch suppresses all optional warning messages, see remaining list
10861 in this section for details on optional warning messages that can be
10862 individually controlled. Note that unlike switch @code{-gnatws}, the
10863 use of switch @code{-gnatwA} does not suppress warnings that are
10864 normally given unconditionally and cannot be individually controlled
10865 (for example, the warning about a missing exit path in a function).
10866 Also, again unlike switch @code{-gnatws}, warnings suppressed by
10867 the use of switch @code{-gnatwA} can be individually turned back
10868 on. For example the use of switch @code{-gnatwA} followed by
10869 switch @code{-gnatwd} will suppress all optional warnings except
10870 the warnings for implicit dereferencing.
10871 @end table
10873 @geindex -gnatw.a (gcc)
10876 @table @asis
10878 @item @code{-gnatw.a}
10880 `Activate warnings on failing assertions.'
10882 @geindex Assert failures
10884 This switch activates warnings for assertions where the compiler can tell at
10885 compile time that the assertion will fail. Note that this warning is given
10886 even if assertions are disabled. The default is that such warnings are
10887 generated.
10888 @end table
10890 @geindex -gnatw.A (gcc)
10893 @table @asis
10895 @item @code{-gnatw.A}
10897 `Suppress warnings on failing assertions.'
10899 @geindex Assert failures
10901 This switch suppresses warnings for assertions where the compiler can tell at
10902 compile time that the assertion will fail.
10903 @end table
10905 @geindex -gnatw_a
10908 @table @asis
10910 @item @code{-gnatw_a}
10912 `Activate warnings on anonymous allocators.'
10914 @geindex Anonymous allocators
10916 This switch activates warnings for allocators of anonymous access types,
10917 which can involve run-time accessibility checks and lead to unexpected
10918 accessibility violations. For more details on the rules involved, see
10919 RM 3.10.2 (14).
10920 @end table
10922 @geindex -gnatw_A
10925 @table @asis
10927 @item @code{-gnatw_A}
10929 `Suppress warnings on anonymous allocators.'
10931 @geindex Anonymous allocators
10933 This switch suppresses warnings for anonymous access type allocators.
10934 @end table
10936 @geindex -gnatwb (gcc)
10939 @table @asis
10941 @item @code{-gnatwb}
10943 `Activate warnings on bad fixed values.'
10945 @geindex Bad fixed values
10947 @geindex Fixed-point Small value
10949 @geindex Small value
10951 This switch activates warnings for static fixed-point expressions whose
10952 value is not an exact multiple of Small. Such values are implementation
10953 dependent, since an implementation is free to choose either of the multiples
10954 that surround the value. GNAT always chooses the closer one, but this is not
10955 required behavior, and it is better to specify a value that is an exact
10956 multiple, ensuring predictable execution. The default is that such warnings
10957 are not generated.
10958 @end table
10960 @geindex -gnatwB (gcc)
10963 @table @asis
10965 @item @code{-gnatwB}
10967 `Suppress warnings on bad fixed values.'
10969 This switch suppresses warnings for static fixed-point expressions whose
10970 value is not an exact multiple of Small.
10971 @end table
10973 @geindex -gnatw.b (gcc)
10976 @table @asis
10978 @item @code{-gnatw.b}
10980 `Activate warnings on biased representation.'
10982 @geindex Biased representation
10984 This switch activates warnings when a size clause, value size clause, component
10985 clause, or component size clause forces the use of biased representation for an
10986 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
10987 to represent 10/11). The default is that such warnings are generated.
10988 @end table
10990 @geindex -gnatwB (gcc)
10993 @table @asis
10995 @item @code{-gnatw.B}
10997 `Suppress warnings on biased representation.'
10999 This switch suppresses warnings for representation clauses that force the use
11000 of biased representation.
11001 @end table
11003 @geindex -gnatwc (gcc)
11006 @table @asis
11008 @item @code{-gnatwc}
11010 `Activate warnings on conditionals.'
11012 @geindex Conditionals
11013 @geindex constant
11015 This switch activates warnings for boolean expressions that are known to
11016 be True or False at compile time. The default
11017 is that such warnings are not generated.
11018 Note that this warning does
11019 not get issued for the use of boolean constants whose
11020 values are known at compile time, since this is a standard technique
11021 for conditional compilation in Ada, and this would generate too many
11022 false positive warnings.
11024 This warning option also activates a special test for comparisons using
11025 the operators ‘>=’ and’ <=’.
11026 If the compiler can tell that only the equality condition is possible,
11027 then it will warn that the ‘>’ or ‘<’ part of the test
11028 is useless and that the operator could be replaced by ‘=’.
11029 An example would be comparing a @code{Natural} variable <= 0.
11031 This warning option also generates warnings if
11032 one or both tests is optimized away in a membership test for integer
11033 values if the result can be determined at compile time. Range tests on
11034 enumeration types are not included, since it is common for such tests
11035 to include an end point.
11037 This warning can also be turned on using @code{-gnatwa}.
11038 @end table
11040 @geindex -gnatwC (gcc)
11043 @table @asis
11045 @item @code{-gnatwC}
11047 `Suppress warnings on conditionals.'
11049 This switch suppresses warnings for conditional expressions used in
11050 tests that are known to be True or False at compile time.
11051 @end table
11053 @geindex -gnatw.c (gcc)
11056 @table @asis
11058 @item @code{-gnatw.c}
11060 `Activate warnings on missing component clauses.'
11062 @geindex Component clause
11063 @geindex missing
11065 This switch activates warnings for record components where a record
11066 representation clause is present and has component clauses for the
11067 majority, but not all, of the components. A warning is given for each
11068 component for which no component clause is present.
11069 @end table
11071 @geindex -gnatw.C (gcc)
11074 @table @asis
11076 @item @code{-gnatw.C}
11078 `Suppress warnings on missing component clauses.'
11080 This switch suppresses warnings for record components that are
11081 missing a component clause in the situation described above.
11082 @end table
11084 @geindex -gnatw_c (gcc)
11087 @table @asis
11089 @item @code{-gnatw_c}
11091 `Activate warnings on unknown condition in Compile_Time_Warning.'
11093 @geindex Compile_Time_Warning
11095 @geindex Compile_Time_Error
11097 This switch activates warnings on a pragma Compile_Time_Warning
11098 or Compile_Time_Error whose condition has a value that is not
11099 known at compile time.
11100 The default is that such warnings are generated.
11101 @end table
11103 @geindex -gnatw_C (gcc)
11106 @table @asis
11108 @item @code{-gnatw_C}
11110 `Suppress warnings on unknown condition in Compile_Time_Warning.'
11112 This switch suppresses warnings on a pragma Compile_Time_Warning
11113 or Compile_Time_Error whose condition has a value that is not
11114 known at compile time.
11115 @end table
11117 @geindex -gnatwd (gcc)
11120 @table @asis
11122 @item @code{-gnatwd}
11124 `Activate warnings on implicit dereferencing.'
11126 If this switch is set, then the use of a prefix of an access type
11127 in an indexed component, slice, or selected component without an
11128 explicit @code{.all} will generate a warning. With this warning
11129 enabled, access checks occur only at points where an explicit
11130 @code{.all} appears in the source code (assuming no warnings are
11131 generated as a result of this switch). The default is that such
11132 warnings are not generated.
11133 @end table
11135 @geindex -gnatwD (gcc)
11138 @table @asis
11140 @item @code{-gnatwD}
11142 `Suppress warnings on implicit dereferencing.'
11144 @geindex Implicit dereferencing
11146 @geindex Dereferencing
11147 @geindex implicit
11149 This switch suppresses warnings for implicit dereferences in
11150 indexed components, slices, and selected components.
11151 @end table
11153 @geindex -gnatw.d (gcc)
11156 @table @asis
11158 @item @code{-gnatw.d}
11160 `Activate tagging of warning and info messages.'
11162 If this switch is set, then warning messages are tagged, with one of the
11163 following strings:
11165 @quotation
11168 @itemize -
11170 @item 
11171 `[-gnatw?]'
11172 Used to tag warnings controlled by the switch @code{-gnatwx} where x
11173 is a letter a-z.
11175 @item 
11176 `[-gnatw.?]'
11177 Used to tag warnings controlled by the switch @code{-gnatw.x} where x
11178 is a letter a-z.
11180 @item 
11181 `[-gnatel]'
11182 Used to tag elaboration information (info) messages generated when the
11183 static model of elaboration is used and the @code{-gnatel} switch is set.
11185 @item 
11186 `[restriction warning]'
11187 Used to tag warning messages for restriction violations, activated by use
11188 of the pragma @code{Restriction_Warnings}.
11190 @item 
11191 `[warning-as-error]'
11192 Used to tag warning messages that have been converted to error messages by
11193 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
11194 the string “error: ” rather than “warning: “.
11196 @item 
11197 `[enabled by default]'
11198 Used to tag all other warnings that are always given by default, unless
11199 warnings are completely suppressed using pragma `Warnings(Off)' or
11200 the switch @code{-gnatws}.
11201 @end itemize
11202 @end quotation
11203 @end table
11205 @geindex -gnatw.d (gcc)
11208 @table @asis
11210 @item @code{-gnatw.D}
11212 `Deactivate tagging of warning and info messages messages.'
11214 If this switch is set, then warning messages return to the default
11215 mode in which warnings and info messages are not tagged as described above for
11216 @code{-gnatw.d}.
11217 @end table
11219 @geindex -gnatwe (gcc)
11221 @geindex Warnings
11222 @geindex treat as error
11225 @table @asis
11227 @item @code{-gnatwe}
11229 `Treat warnings and style checks as errors.'
11231 This switch causes warning messages and style check messages to be
11232 treated as errors.
11233 The warning string still appears, but the warning messages are counted
11234 as errors, and prevent the generation of an object file. Note that this
11235 is the only -gnatw switch that affects the handling of style check messages.
11236 Note also that this switch has no effect on info (information) messages, which
11237 are not treated as errors if this switch is present.
11238 @end table
11240 @geindex -gnatw.e (gcc)
11243 @table @asis
11245 @item @code{-gnatw.e}
11247 `Activate every optional warning.'
11249 @geindex Warnings
11250 @geindex activate every optional warning
11252 This switch activates all optional warnings, including those which
11253 are not activated by @code{-gnatwa}. The use of this switch is not
11254 recommended for normal use. If you turn this switch on, it is almost
11255 certain that you will get large numbers of useless warnings. The
11256 warnings that are excluded from @code{-gnatwa} are typically highly
11257 specialized warnings that are suitable for use only in code that has
11258 been specifically designed according to specialized coding rules.
11259 @end table
11261 @geindex -gnatwE (gcc)
11263 @geindex Warnings
11264 @geindex treat as error
11267 @table @asis
11269 @item @code{-gnatwE}
11271 `Treat all run-time exception warnings as errors.'
11273 This switch causes warning messages regarding errors that will be raised
11274 during run-time execution to be treated as errors.
11275 @end table
11277 @geindex -gnatwf (gcc)
11280 @table @asis
11282 @item @code{-gnatwf}
11284 `Activate warnings on unreferenced formals.'
11286 @geindex Formals
11287 @geindex unreferenced
11289 This switch causes a warning to be generated if a formal parameter
11290 is not referenced in the body of the subprogram. This warning can
11291 also be turned on using @code{-gnatwu}. The
11292 default is that these warnings are not generated.
11293 @end table
11295 @geindex -gnatwF (gcc)
11298 @table @asis
11300 @item @code{-gnatwF}
11302 `Suppress warnings on unreferenced formals.'
11304 This switch suppresses warnings for unreferenced formal
11305 parameters. Note that the
11306 combination @code{-gnatwu} followed by @code{-gnatwF} has the
11307 effect of warning on unreferenced entities other than subprogram
11308 formals.
11309 @end table
11311 @geindex -gnatwg (gcc)
11314 @table @asis
11316 @item @code{-gnatwg}
11318 `Activate warnings on unrecognized pragmas.'
11320 @geindex Pragmas
11321 @geindex unrecognized
11323 This switch causes a warning to be generated if an unrecognized
11324 pragma is encountered. Apart from issuing this warning, the
11325 pragma is ignored and has no effect. The default
11326 is that such warnings are issued (satisfying the Ada Reference
11327 Manual requirement that such warnings appear).
11328 @end table
11330 @geindex -gnatwG (gcc)
11333 @table @asis
11335 @item @code{-gnatwG}
11337 `Suppress warnings on unrecognized pragmas.'
11339 This switch suppresses warnings for unrecognized pragmas.
11340 @end table
11342 @geindex -gnatw.g (gcc)
11345 @table @asis
11347 @item @code{-gnatw.g}
11349 `Warnings used for GNAT sources.'
11351 This switch sets the warning categories that are used by the standard
11352 GNAT style. Currently this is equivalent to
11353 @code{-gnatwAao.q.s.CI.V.X.Z}
11354 but more warnings may be added in the future without advanced notice.
11355 @end table
11357 @geindex -gnatwh (gcc)
11360 @table @asis
11362 @item @code{-gnatwh}
11364 `Activate warnings on hiding.'
11366 @geindex Hiding of Declarations
11368 This switch activates warnings on hiding declarations that are considered
11369 potentially confusing. Not all cases of hiding cause warnings; for example an
11370 overriding declaration hides an implicit declaration, which is just normal
11371 code. The default is that warnings on hiding are not generated.
11372 @end table
11374 @geindex -gnatwH (gcc)
11377 @table @asis
11379 @item @code{-gnatwH}
11381 `Suppress warnings on hiding.'
11383 This switch suppresses warnings on hiding declarations.
11384 @end table
11386 @geindex -gnatw.h (gcc)
11389 @table @asis
11391 @item @code{-gnatw.h}
11393 `Activate warnings on holes/gaps in records.'
11395 @geindex Record Representation (gaps)
11397 This switch activates warnings on component clauses in record
11398 representation clauses that leave holes (gaps) in the record layout.
11399 If a record representation clause does not specify a location for
11400 every component of the record type, then the warnings generated (or not
11401 generated) are unspecified. For example, there may be gaps for which
11402 either no warning is generated or a warning is generated that
11403 incorrectly describes the location of the gap. This undesirable situation
11404 can sometimes be avoided by adding (and specifying the location for) unused
11405 fill fields.
11406 @end table
11408 @geindex -gnatw.H (gcc)
11411 @table @asis
11413 @item @code{-gnatw.H}
11415 `Suppress warnings on holes/gaps in records.'
11417 This switch suppresses warnings on component clauses in record
11418 representation clauses that leave holes (haps) in the record layout.
11419 @end table
11421 @geindex -gnatwi (gcc)
11424 @table @asis
11426 @item @code{-gnatwi}
11428 `Activate warnings on implementation units.'
11430 This switch activates warnings for a `with' of an internal GNAT
11431 implementation unit, defined as any unit from the @code{Ada},
11432 @code{Interfaces}, @code{GNAT},
11433 or @code{System}
11434 hierarchies that is not
11435 documented in either the Ada Reference Manual or the GNAT
11436 Programmer’s Reference Manual. Such units are intended only
11437 for internal implementation purposes and should not be `with'ed
11438 by user programs. The default is that such warnings are generated
11439 @end table
11441 @geindex -gnatwI (gcc)
11444 @table @asis
11446 @item @code{-gnatwI}
11448 `Disable warnings on implementation units.'
11450 This switch disables warnings for a `with' of an internal GNAT
11451 implementation unit.
11452 @end table
11454 @geindex -gnatw.i (gcc)
11457 @table @asis
11459 @item @code{-gnatw.i}
11461 `Activate warnings on overlapping actuals.'
11463 This switch enables a warning on statically detectable overlapping actuals in
11464 a subprogram call, when one of the actuals is an in-out parameter, and the
11465 types of the actuals are not by-copy types. This warning is off by default.
11466 @end table
11468 @geindex -gnatw.I (gcc)
11471 @table @asis
11473 @item @code{-gnatw.I}
11475 `Disable warnings on overlapping actuals.'
11477 This switch disables warnings on overlapping actuals in a call.
11478 @end table
11480 @geindex -gnatwj (gcc)
11483 @table @asis
11485 @item @code{-gnatwj}
11487 `Activate warnings on obsolescent features (Annex J).'
11489 @geindex Features
11490 @geindex obsolescent
11492 @geindex Obsolescent features
11494 If this warning option is activated, then warnings are generated for
11495 calls to subprograms marked with @code{pragma Obsolescent} and
11496 for use of features in Annex J of the Ada Reference Manual. In the
11497 case of Annex J, not all features are flagged. In particular, uses of package
11498 @code{ASCII} are not flagged, since these are very common and
11499 would generate many annoying positive warnings. The default is that
11500 such warnings are not generated.
11502 In addition to the above cases, warnings are also generated for
11503 GNAT features that have been provided in past versions but which
11504 have been superseded (typically by features in the new Ada standard).
11505 For example, @code{pragma Ravenscar} will be flagged since its
11506 function is replaced by @code{pragma Profile(Ravenscar)}, and
11507 @code{pragma Interface_Name} will be flagged since its function
11508 is replaced by @code{pragma Import}.
11510 Note that this warning option functions differently from the
11511 restriction @code{No_Obsolescent_Features} in two respects.
11512 First, the restriction applies only to annex J features.
11513 Second, the restriction does flag uses of package @code{ASCII}.
11514 @end table
11516 @geindex -gnatwJ (gcc)
11519 @table @asis
11521 @item @code{-gnatwJ}
11523 `Suppress warnings on obsolescent features (Annex J).'
11525 This switch disables warnings on use of obsolescent features.
11526 @end table
11528 @geindex -gnatw.j (gcc)
11531 @table @asis
11533 @item @code{-gnatw.j}
11535 `Activate warnings on late declarations of tagged type primitives.'
11537 This switch activates warnings on visible primitives added to a
11538 tagged type after deriving a private extension from it.
11539 @end table
11541 @geindex -gnatw.J (gcc)
11544 @table @asis
11546 @item @code{-gnatw.J}
11548 `Suppress warnings on late declarations of tagged type primitives.'
11550 This switch suppresses warnings on visible primitives added to a
11551 tagged type after deriving a private extension from it.
11552 @end table
11554 @geindex -gnatwk (gcc)
11557 @table @asis
11559 @item @code{-gnatwk}
11561 `Activate warnings on variables that could be constants.'
11563 This switch activates warnings for variables that are initialized but
11564 never modified, and then could be declared constants. The default is that
11565 such warnings are not given.
11566 @end table
11568 @geindex -gnatwK (gcc)
11571 @table @asis
11573 @item @code{-gnatwK}
11575 `Suppress warnings on variables that could be constants.'
11577 This switch disables warnings on variables that could be declared constants.
11578 @end table
11580 @geindex -gnatw.k (gcc)
11583 @table @asis
11585 @item @code{-gnatw.k}
11587 `Activate warnings on redefinition of names in standard.'
11589 This switch activates warnings for declarations that declare a name that
11590 is defined in package Standard. Such declarations can be confusing,
11591 especially since the names in package Standard continue to be directly
11592 visible, meaning that use visibility on such redeclared names does not
11593 work as expected. Names of discriminants and components in records are
11594 not included in this check.
11595 @end table
11597 @geindex -gnatwK (gcc)
11600 @table @asis
11602 @item @code{-gnatw.K}
11604 `Suppress warnings on redefinition of names in standard.'
11606 This switch disables warnings for declarations that declare a name that
11607 is defined in package Standard.
11608 @end table
11610 @geindex -gnatwl (gcc)
11613 @table @asis
11615 @item @code{-gnatwl}
11617 `Activate warnings for elaboration pragmas.'
11619 @geindex Elaboration
11620 @geindex warnings
11622 This switch activates warnings for possible elaboration problems,
11623 including suspicious use
11624 of @code{Elaborate} pragmas, when using the static elaboration model, and
11625 possible situations that may raise @code{Program_Error} when using the
11626 dynamic elaboration model.
11627 See the section in this guide on elaboration checking for further details.
11628 The default is that such warnings
11629 are not generated.
11630 @end table
11632 @geindex -gnatwL (gcc)
11635 @table @asis
11637 @item @code{-gnatwL}
11639 `Suppress warnings for elaboration pragmas.'
11641 This switch suppresses warnings for possible elaboration problems.
11642 @end table
11644 @geindex -gnatw.l (gcc)
11647 @table @asis
11649 @item @code{-gnatw.l}
11651 `List inherited aspects.'
11653 This switch causes the compiler to list inherited invariants,
11654 preconditions, and postconditions from Type_Invariant’Class, Invariant’Class,
11655 Pre’Class, and Post’Class aspects. Also list inherited subtype predicates.
11656 @end table
11658 @geindex -gnatw.L (gcc)
11661 @table @asis
11663 @item @code{-gnatw.L}
11665 `Suppress listing of inherited aspects.'
11667 This switch suppresses listing of inherited aspects.
11668 @end table
11670 @geindex -gnatwm (gcc)
11673 @table @asis
11675 @item @code{-gnatwm}
11677 `Activate warnings on modified but unreferenced variables.'
11679 This switch activates warnings for variables that are assigned (using
11680 an initialization value or with one or more assignment statements) but
11681 whose value is never read. The warning is suppressed for volatile
11682 variables and also for variables that are renamings of other variables
11683 or for which an address clause is given.
11684 The default is that these warnings are not given.
11685 @end table
11687 @geindex -gnatwM (gcc)
11690 @table @asis
11692 @item @code{-gnatwM}
11694 `Disable warnings on modified but unreferenced variables.'
11696 This switch disables warnings for variables that are assigned or
11697 initialized, but never read.
11698 @end table
11700 @geindex -gnatw.m (gcc)
11703 @table @asis
11705 @item @code{-gnatw.m}
11707 `Activate warnings on suspicious modulus values.'
11709 This switch activates warnings for modulus values that seem suspicious.
11710 The cases caught are where the size is the same as the modulus (e.g.
11711 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11712 with no size clause. The guess in both cases is that 2**x was intended
11713 rather than x. In addition expressions of the form 2*x for small x
11714 generate a warning (the almost certainly accurate guess being that
11715 2**x was intended). This switch also activates warnings for negative
11716 literal values of a modular type, which are interpreted as large positive
11717 integers after wrap-around. The default is that these warnings are given.
11718 @end table
11720 @geindex -gnatw.M (gcc)
11723 @table @asis
11725 @item @code{-gnatw.M}
11727 `Disable warnings on suspicious modulus values.'
11729 This switch disables warnings for suspicious modulus values.
11730 @end table
11732 @geindex -gnatwn (gcc)
11735 @table @asis
11737 @item @code{-gnatwn}
11739 `Set normal warnings mode.'
11741 This switch sets normal warning mode, in which enabled warnings are
11742 issued and treated as warnings rather than errors. This is the default
11743 mode. the switch @code{-gnatwn} can be used to cancel the effect of
11744 an explicit @code{-gnatws} or
11745 @code{-gnatwe}. It also cancels the effect of the
11746 implicit @code{-gnatwe} that is activated by the
11747 use of @code{-gnatg}.
11748 @end table
11750 @geindex -gnatw.n (gcc)
11752 @geindex Atomic Synchronization
11753 @geindex warnings
11756 @table @asis
11758 @item @code{-gnatw.n}
11760 `Activate warnings on atomic synchronization.'
11762 This switch actives warnings when an access to an atomic variable
11763 requires the generation of atomic synchronization code. These
11764 warnings are off by default.
11765 @end table
11767 @geindex -gnatw.N (gcc)
11770 @table @asis
11772 @item @code{-gnatw.N}
11774 `Suppress warnings on atomic synchronization.'
11776 @geindex Atomic Synchronization
11777 @geindex warnings
11779 This switch suppresses warnings when an access to an atomic variable
11780 requires the generation of atomic synchronization code.
11781 @end table
11783 @geindex -gnatwo (gcc)
11785 @geindex Address Clauses
11786 @geindex warnings
11789 @table @asis
11791 @item @code{-gnatwo}
11793 `Activate warnings on address clause overlays.'
11795 This switch activates warnings for possibly unintended initialization
11796 effects of defining address clauses that cause one variable to overlap
11797 another. The default is that such warnings are generated.
11798 @end table
11800 @geindex -gnatwO (gcc)
11803 @table @asis
11805 @item @code{-gnatwO}
11807 `Suppress warnings on address clause overlays.'
11809 This switch suppresses warnings on possibly unintended initialization
11810 effects of defining address clauses that cause one variable to overlap
11811 another.
11812 @end table
11814 @geindex -gnatw.o (gcc)
11817 @table @asis
11819 @item @code{-gnatw.o}
11821 `Activate warnings on modified but unreferenced out parameters.'
11823 This switch activates warnings for variables that are modified by using
11824 them as actuals for a call to a procedure with an out mode formal, where
11825 the resulting assigned value is never read. It is applicable in the case
11826 where there is more than one out mode formal. If there is only one out
11827 mode formal, the warning is issued by default (controlled by -gnatwu).
11828 The warning is suppressed for volatile
11829 variables and also for variables that are renamings of other variables
11830 or for which an address clause is given.
11831 The default is that these warnings are not given.
11832 @end table
11834 @geindex -gnatw.O (gcc)
11837 @table @asis
11839 @item @code{-gnatw.O}
11841 `Disable warnings on modified but unreferenced out parameters.'
11843 This switch suppresses warnings for variables that are modified by using
11844 them as actuals for a call to a procedure with an out mode formal, where
11845 the resulting assigned value is never read.
11846 @end table
11848 @geindex -gnatwp (gcc)
11850 @geindex Inlining
11851 @geindex warnings
11854 @table @asis
11856 @item @code{-gnatwp}
11858 `Activate warnings on ineffective pragma Inlines.'
11860 This switch activates warnings for failure of front end inlining
11861 (activated by @code{-gnatN}) to inline a particular call. There are
11862 many reasons for not being able to inline a call, including most
11863 commonly that the call is too complex to inline. The default is
11864 that such warnings are not given.
11865 Warnings on ineffective inlining by the gcc back-end can be activated
11866 separately, using the gcc switch -Winline.
11867 @end table
11869 @geindex -gnatwP (gcc)
11872 @table @asis
11874 @item @code{-gnatwP}
11876 `Suppress warnings on ineffective pragma Inlines.'
11878 This switch suppresses warnings on ineffective pragma Inlines. If the
11879 inlining mechanism cannot inline a call, it will simply ignore the
11880 request silently.
11881 @end table
11883 @geindex -gnatw.p (gcc)
11885 @geindex Parameter order
11886 @geindex warnings
11889 @table @asis
11891 @item @code{-gnatw.p}
11893 `Activate warnings on parameter ordering.'
11895 This switch activates warnings for cases of suspicious parameter
11896 ordering when the list of arguments are all simple identifiers that
11897 match the names of the formals, but are in a different order. The
11898 warning is suppressed if any use of named parameter notation is used,
11899 so this is the appropriate way to suppress a false positive (and
11900 serves to emphasize that the “misordering” is deliberate). The
11901 default is that such warnings are not given.
11902 @end table
11904 @geindex -gnatw.P (gcc)
11907 @table @asis
11909 @item @code{-gnatw.P}
11911 `Suppress warnings on parameter ordering.'
11913 This switch suppresses warnings on cases of suspicious parameter
11914 ordering.
11915 @end table
11917 @geindex -gnatw_p (gcc)
11920 @table @asis
11922 @item @code{-gnatw_p}
11924 `Activate warnings for pedantic checks.'
11926 This switch activates warnings for the failure of certain pedantic checks.
11927 The only case currently supported is a check that the subtype_marks given
11928 for corresponding formal parameter and function results in a subprogram
11929 declaration and its body denote the same subtype declaration. The default
11930 is that such warnings are not given.
11931 @end table
11933 @geindex -gnatw_P (gcc)
11936 @table @asis
11938 @item @code{-gnatw_P}
11940 `Suppress warnings for pedantic checks.'
11942 This switch suppresses warnings on violations of pedantic checks.
11943 @end table
11945 @geindex -gnatwq (gcc)
11947 @geindex Parentheses
11948 @geindex warnings
11951 @table @asis
11953 @item @code{-gnatwq}
11955 `Activate warnings on questionable missing parentheses.'
11957 This switch activates warnings for cases where parentheses are not used and
11958 the result is potential ambiguity from a readers point of view. For example
11959 (not a > b) when a and b are modular means ((not a) > b) and very likely the
11960 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11961 quite likely ((-x) mod 5) was intended. In such situations it seems best to
11962 follow the rule of always parenthesizing to make the association clear, and
11963 this warning switch warns if such parentheses are not present. The default
11964 is that these warnings are given.
11965 @end table
11967 @geindex -gnatwQ (gcc)
11970 @table @asis
11972 @item @code{-gnatwQ}
11974 `Suppress warnings on questionable missing parentheses.'
11976 This switch suppresses warnings for cases where the association is not
11977 clear and the use of parentheses is preferred.
11978 @end table
11980 @geindex -gnatw.q (gcc)
11982 @geindex Layout
11983 @geindex warnings
11986 @table @asis
11988 @item @code{-gnatw.q}
11990 `Activate warnings on questionable layout of record types.'
11992 This switch activates warnings for cases where the default layout of
11993 a record type, that is to say the layout of its components in textual
11994 order of the source code, would very likely cause inefficiencies in
11995 the code generated by the compiler, both in terms of space and speed
11996 during execution. One warning is issued for each problematic component
11997 without representation clause in the nonvariant part and then in each
11998 variant recursively, if any.
12000 The purpose of these warnings is neither to prescribe an optimal layout
12001 nor to force the use of representation clauses, but rather to get rid of
12002 the most blatant inefficiencies in the layout. Therefore, the default
12003 layout is matched against the following synthetic ordered layout and
12004 the deviations are flagged on a component-by-component basis:
12007 @itemize *
12009 @item 
12010 first all components or groups of components whose length is fixed
12011 and a multiple of the storage unit,
12013 @item 
12014 then the remaining components whose length is fixed and not a multiple
12015 of the storage unit,
12017 @item 
12018 then the remaining components whose length doesn’t depend on discriminants
12019 (that is to say, with variable but uniform length for all objects),
12021 @item 
12022 then all components whose length depends on discriminants,
12024 @item 
12025 finally the variant part (if any),
12026 @end itemize
12028 for the nonvariant part and for each variant recursively, if any.
12030 The exact wording of the warning depends on whether the compiler is allowed
12031 to reorder the components in the record type or precluded from doing it by
12032 means of pragma @code{No_Component_Reordering}.
12034 The default is that these warnings are not given.
12035 @end table
12037 @geindex -gnatw.Q (gcc)
12040 @table @asis
12042 @item @code{-gnatw.Q}
12044 `Suppress warnings on questionable layout of record types.'
12046 This switch suppresses warnings for cases where the default layout of
12047 a record type would very likely cause inefficiencies.
12048 @end table
12050 @geindex -gnatw_q (gcc)
12053 @table @asis
12055 @item @code{-gnatw_q}
12057 `Activate warnings for ignored equality operators.'
12059 This switch activates warnings for a user-defined “=” function that does
12060 not compose (i.e. is ignored for a predefined “=” for a composite type
12061 containing a component whose type has the user-defined “=” as
12062 primitive). Note that the user-defined “=” must be a primitive operator
12063 in order to trigger the warning.
12064 See RM-4.5.2(14/3-15/5, 21, 24/3, 32.1/1)
12065 for the exact Ada rules on composability of “=”.
12067 The default is that these warnings are not given.
12068 @end table
12070 @geindex -gnatw_Q (gcc)
12073 @table @asis
12075 @item @code{-gnatw_Q}
12077 `Suppress warnings for ignored equality operators.'
12078 @end table
12080 @geindex -gnatwr (gcc)
12083 @table @asis
12085 @item @code{-gnatwr}
12087 `Activate warnings on redundant constructs.'
12089 This switch activates warnings for redundant constructs. The following
12090 is the current list of constructs regarded as redundant:
12093 @itemize *
12095 @item 
12096 Assignment of an item to itself.
12098 @item 
12099 Type conversion that converts an expression to its own type.
12101 @item 
12102 Use of the attribute @code{Base} where @code{typ'Base} is the same
12103 as @code{typ}.
12105 @item 
12106 Use of pragma @code{Pack} when all components are placed by a record
12107 representation clause.
12109 @item 
12110 Exception handler containing only a reraise statement (raise with no
12111 operand) which has no effect.
12113 @item 
12114 Use of the operator abs on an operand that is known at compile time
12115 to be non-negative
12117 @item 
12118 Comparison of an object or (unary or binary) operation of boolean type to
12119 an explicit True value.
12121 @item 
12122 Import of parent package.
12123 @end itemize
12125 The default is that warnings for redundant constructs are not given.
12126 @end table
12128 @geindex -gnatwR (gcc)
12131 @table @asis
12133 @item @code{-gnatwR}
12135 `Suppress warnings on redundant constructs.'
12137 This switch suppresses warnings for redundant constructs.
12138 @end table
12140 @geindex -gnatw.r (gcc)
12143 @table @asis
12145 @item @code{-gnatw.r}
12147 `Activate warnings for object renaming function.'
12149 This switch activates warnings for an object renaming that renames a
12150 function call, which is equivalent to a constant declaration (as
12151 opposed to renaming the function itself).  The default is that these
12152 warnings are given.
12153 @end table
12155 @geindex -gnatw.R (gcc)
12158 @table @asis
12160 @item @code{-gnatw.R}
12162 `Suppress warnings for object renaming function.'
12164 This switch suppresses warnings for object renaming function.
12165 @end table
12167 @geindex -gnatw_r (gcc)
12170 @table @asis
12172 @item @code{-gnatw_r}
12174 `Activate warnings for out-of-order record representation clauses.'
12176 This switch activates warnings for record representation clauses,
12177 if the order of component declarations, component clauses,
12178 and bit-level layout do not all agree.
12179 The default is that these warnings are not given.
12180 @end table
12182 @geindex -gnatw_R (gcc)
12185 @table @asis
12187 @item @code{-gnatw_R}
12189 `Suppress warnings for out-of-order record representation clauses.'
12190 @end table
12192 @geindex -gnatws (gcc)
12195 @table @asis
12197 @item @code{-gnatws}
12199 `Suppress all warnings.'
12201 This switch completely suppresses the
12202 output of all warning messages from the GNAT front end, including
12203 both warnings that can be controlled by switches described in this
12204 section, and those that are normally given unconditionally. The
12205 effect of this suppress action can only be cancelled by a subsequent
12206 use of the switch @code{-gnatwn}.
12208 Note that switch @code{-gnatws} does not suppress
12209 warnings from the @code{gcc} back end.
12210 To suppress these back end warnings as well, use the switch @code{-w}
12211 in addition to @code{-gnatws}. Also this switch has no effect on the
12212 handling of style check messages.
12213 @end table
12215 @geindex -gnatw.s (gcc)
12217 @geindex Record Representation (component sizes)
12220 @table @asis
12222 @item @code{-gnatw.s}
12224 `Activate warnings on overridden size clauses.'
12226 This switch activates warnings on component clauses in record
12227 representation clauses where the length given overrides that
12228 specified by an explicit size clause for the component type. A
12229 warning is similarly given in the array case if a specified
12230 component size overrides an explicit size clause for the array
12231 component type.
12232 @end table
12234 @geindex -gnatw.S (gcc)
12237 @table @asis
12239 @item @code{-gnatw.S}
12241 `Suppress warnings on overridden size clauses.'
12243 This switch suppresses warnings on component clauses in record
12244 representation clauses that override size clauses, and similar
12245 warnings when an array component size overrides a size clause.
12246 @end table
12248 @geindex -gnatw_s (gcc)
12250 @geindex Warnings
12253 @table @asis
12255 @item @code{-gnatw_s}
12257 `Activate warnings on ineffective predicate tests.'
12259 This switch activates warnings on Static_Predicate aspect
12260 specifications that test for values that do not belong to
12261 the parent subtype. Not all such ineffective tests are detected.
12262 @end table
12264 @geindex -gnatw_S (gcc)
12267 @table @asis
12269 @item @code{-gnatw_S}
12271 `Suppress warnings on ineffective predicate tests.'
12273 This switch suppresses warnings on Static_Predicate aspect
12274 specifications that test for values that do not belong to
12275 the parent subtype.
12276 @end table
12278 @geindex -gnatwt (gcc)
12280 @geindex Deactivated code
12281 @geindex warnings
12283 @geindex Deleted code
12284 @geindex warnings
12287 @table @asis
12289 @item @code{-gnatwt}
12291 `Activate warnings for tracking of deleted conditional code.'
12293 This switch activates warnings for tracking of code in conditionals (IF and
12294 CASE statements) that is detected to be dead code which cannot be executed, and
12295 which is removed by the front end. This warning is off by default. This may be
12296 useful for detecting deactivated code in certified applications.
12297 @end table
12299 @geindex -gnatwT (gcc)
12302 @table @asis
12304 @item @code{-gnatwT}
12306 `Suppress warnings for tracking of deleted conditional code.'
12308 This switch suppresses warnings for tracking of deleted conditional code.
12309 @end table
12311 @geindex -gnatw.t (gcc)
12314 @table @asis
12316 @item @code{-gnatw.t}
12318 `Activate warnings on suspicious contracts.'
12320 This switch activates warnings on suspicious contracts. This includes
12321 warnings on suspicious postconditions (whether a pragma @code{Postcondition} or a
12322 @code{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
12323 @code{Contract_Cases}). A function postcondition or contract case is suspicious
12324 when no postcondition or contract case for this function mentions the result
12325 of the function.  A procedure postcondition or contract case is suspicious
12326 when it only refers to the pre-state of the procedure, because in that case
12327 it should rather be expressed as a precondition. This switch also controls
12328 warnings on suspicious cases of expressions typically found in contracts like
12329 quantified expressions and uses of Update attribute. The default is that such
12330 warnings are generated.
12331 @end table
12333 @geindex -gnatw.T (gcc)
12336 @table @asis
12338 @item @code{-gnatw.T}
12340 `Suppress warnings on suspicious contracts.'
12342 This switch suppresses warnings on suspicious contracts.
12343 @end table
12345 @geindex -gnatwu (gcc)
12348 @table @asis
12350 @item @code{-gnatwu}
12352 `Activate warnings on unused entities.'
12354 This switch activates warnings to be generated for entities that
12355 are declared but not referenced, and for units that are `with'ed
12356 and not
12357 referenced. In the case of packages, a warning is also generated if
12358 no entities in the package are referenced. This means that if a with’ed
12359 package is referenced but the only references are in @code{use}
12360 clauses or @code{renames}
12361 declarations, a warning is still generated. A warning is also generated
12362 for a generic package that is `with'ed but never instantiated.
12363 In the case where a package or subprogram body is compiled, and there
12364 is a `with' on the corresponding spec
12365 that is only referenced in the body,
12366 a warning is also generated, noting that the
12367 `with' can be moved to the body. The default is that
12368 such warnings are not generated.
12369 This switch also activates warnings on unreferenced formals
12370 (it includes the effect of @code{-gnatwf}).
12371 @end table
12373 @geindex -gnatwU (gcc)
12376 @table @asis
12378 @item @code{-gnatwU}
12380 `Suppress warnings on unused entities.'
12382 This switch suppresses warnings for unused entities and packages.
12383 It also turns off warnings on unreferenced formals (and thus includes
12384 the effect of @code{-gnatwF}).
12385 @end table
12387 @geindex -gnatw.u (gcc)
12390 @table @asis
12392 @item @code{-gnatw.u}
12394 `Activate warnings on unordered enumeration types.'
12396 This switch causes enumeration types to be considered as conceptually
12397 unordered, unless an explicit pragma @code{Ordered} is given for the type.
12398 The effect is to generate warnings in clients that use explicit comparisons
12399 or subranges, since these constructs both treat objects of the type as
12400 ordered. (A `client' is defined as a unit that is other than the unit in
12401 which the type is declared, or its body or subunits.) Please refer to
12402 the description of pragma @code{Ordered} in the
12403 @cite{GNAT Reference Manual} for further details.
12404 The default is that such warnings are not generated.
12405 @end table
12407 @geindex -gnatw.U (gcc)
12410 @table @asis
12412 @item @code{-gnatw.U}
12414 `Deactivate warnings on unordered enumeration types.'
12416 This switch causes all enumeration types to be considered as ordered, so
12417 that no warnings are given for comparisons or subranges for any type.
12418 @end table
12420 @geindex -gnatwv (gcc)
12422 @geindex Unassigned variable warnings
12425 @table @asis
12427 @item @code{-gnatwv}
12429 `Activate warnings on unassigned variables.'
12431 This switch activates warnings for access to variables which
12432 may not be properly initialized. The default is that
12433 such warnings are generated. This switch will also be emitted when
12434 initializing an array or record object via the following aggregate:
12436 @example
12437 Array_Or_Record : XXX := (others => <>);
12438 @end example
12440 unless the relevant type fully initializes all components.
12441 @end table
12443 @geindex -gnatwV (gcc)
12446 @table @asis
12448 @item @code{-gnatwV}
12450 `Suppress warnings on unassigned variables.'
12452 This switch suppresses warnings for access to variables which
12453 may not be properly initialized.
12454 @end table
12456 @geindex -gnatw.v (gcc)
12458 @geindex bit order warnings
12461 @table @asis
12463 @item @code{-gnatw.v}
12465 `Activate info messages for non-default bit order.'
12467 This switch activates messages (labeled “info”, they are not warnings,
12468 just informational messages) about the effects of non-default bit-order
12469 on records to which a component clause is applied. The effect of specifying
12470 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12471 these messages, which are given by default, are useful in understanding the
12472 exact consequences of using this feature.
12473 @end table
12475 @geindex -gnatw.V (gcc)
12478 @table @asis
12480 @item @code{-gnatw.V}
12482 `Suppress info messages for non-default bit order.'
12484 This switch suppresses information messages for the effects of specifying
12485 non-default bit order on record components with component clauses.
12486 @end table
12488 @geindex -gnatww (gcc)
12490 @geindex String indexing warnings
12493 @table @asis
12495 @item @code{-gnatww}
12497 `Activate warnings on wrong low bound assumption.'
12499 This switch activates warnings for indexing an unconstrained string parameter
12500 with a literal or S’Length. This is a case where the code is assuming that the
12501 low bound is one, which is in general not true (for example when a slice is
12502 passed). The default is that such warnings are generated.
12503 @end table
12505 @geindex -gnatwW (gcc)
12508 @table @asis
12510 @item @code{-gnatwW}
12512 `Suppress warnings on wrong low bound assumption.'
12514 This switch suppresses warnings for indexing an unconstrained string parameter
12515 with a literal or S’Length. Note that this warning can also be suppressed
12516 in a particular case by adding an assertion that the lower bound is 1,
12517 as shown in the following example:
12519 @example
12520 procedure K (S : String) is
12521    pragma Assert (S'First = 1);
12522    ...
12523 @end example
12524 @end table
12526 @geindex -gnatw.w (gcc)
12528 @geindex Warnings Off control
12531 @table @asis
12533 @item @code{-gnatw.w}
12535 `Activate warnings on Warnings Off pragmas.'
12537 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
12538 where either the pragma is entirely useless (because it suppresses no
12539 warnings), or it could be replaced by @code{pragma Unreferenced} or
12540 @code{pragma Unmodified}.
12541 Also activates warnings for the case of
12542 Warnings (Off, String), where either there is no matching
12543 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12544 The default is that these warnings are not given.
12545 @end table
12547 @geindex -gnatw.W (gcc)
12550 @table @asis
12552 @item @code{-gnatw.W}
12554 `Suppress warnings on unnecessary Warnings Off pragmas.'
12556 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
12557 @end table
12559 @geindex -gnatwx (gcc)
12561 @geindex Export/Import pragma warnings
12564 @table @asis
12566 @item @code{-gnatwx}
12568 `Activate warnings on Export/Import pragmas.'
12570 This switch activates warnings on Export/Import pragmas when
12571 the compiler detects a possible conflict between the Ada and
12572 foreign language calling sequences. For example, the use of
12573 default parameters in a convention C procedure is dubious
12574 because the C compiler cannot supply the proper default, so
12575 a warning is issued. The default is that such warnings are
12576 generated.
12577 @end table
12579 @geindex -gnatwX (gcc)
12582 @table @asis
12584 @item @code{-gnatwX}
12586 `Suppress warnings on Export/Import pragmas.'
12588 This switch suppresses warnings on Export/Import pragmas.
12589 The sense of this is that you are telling the compiler that
12590 you know what you are doing in writing the pragma, and it
12591 should not complain at you.
12592 @end table
12594 @geindex -gnatw.x (gcc)
12597 @table @asis
12599 @item @code{-gnatw.x}
12601 `Activate warnings for No_Exception_Propagation mode.'
12603 This switch activates warnings for exception usage when pragma Restrictions
12604 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
12605 explicit exception raises which are not covered by a local handler, and for
12606 exception handlers which do not cover a local raise. The default is that
12607 these warnings are given for units that contain exception handlers.
12609 @item @code{-gnatw.X}
12611 `Disable warnings for No_Exception_Propagation mode.'
12613 This switch disables warnings for exception usage when pragma Restrictions
12614 (No_Exception_Propagation) is in effect.
12615 @end table
12617 @geindex -gnatwy (gcc)
12619 @geindex Ada compatibility issues warnings
12622 @table @asis
12624 @item @code{-gnatwy}
12626 `Activate warnings for Ada compatibility issues.'
12628 For the most part, newer versions of Ada are upwards compatible
12629 with older versions. For example, Ada 2005 programs will almost
12630 always work when compiled as Ada 2012.
12631 However there are some exceptions (for example the fact that
12632 @code{some} is now a reserved word in Ada 2012). This
12633 switch activates several warnings to help in identifying
12634 and correcting such incompatibilities. The default is that
12635 these warnings are generated. Note that at one point Ada 2005
12636 was called Ada 0Y, hence the choice of character.
12637 @end table
12639 @geindex -gnatwY (gcc)
12641 @geindex Ada compatibility issues warnings
12644 @table @asis
12646 @item @code{-gnatwY}
12648 `Disable warnings for Ada compatibility issues.'
12650 This switch suppresses the warnings intended to help in identifying
12651 incompatibilities between Ada language versions.
12652 @end table
12654 @geindex -gnatw.y (gcc)
12656 @geindex Package spec needing body
12659 @table @asis
12661 @item @code{-gnatw.y}
12663 `Activate information messages for why package spec needs body.'
12665 There are a number of cases in which a package spec needs a body.
12666 For example, the use of pragma Elaborate_Body, or the declaration
12667 of a procedure specification requiring a completion. This switch
12668 causes information messages to be output showing why a package
12669 specification requires a body. This can be useful in the case of
12670 a large package specification which is unexpectedly requiring a
12671 body. The default is that such information messages are not output.
12672 @end table
12674 @geindex -gnatw.Y (gcc)
12676 @geindex No information messages for why package spec needs body
12679 @table @asis
12681 @item @code{-gnatw.Y}
12683 `Disable information messages for why package spec needs body.'
12685 This switch suppresses the output of information messages showing why
12686 a package specification needs a body.
12687 @end table
12689 @geindex -gnatwz (gcc)
12691 @geindex Unchecked_Conversion warnings
12694 @table @asis
12696 @item @code{-gnatwz}
12698 `Activate warnings on unchecked conversions.'
12700 This switch activates warnings for unchecked conversions
12701 where the types are known at compile time to have different
12702 sizes. The default is that such warnings are generated. Warnings are also
12703 generated for subprogram pointers with different conventions.
12704 @end table
12706 @geindex -gnatwZ (gcc)
12709 @table @asis
12711 @item @code{-gnatwZ}
12713 `Suppress warnings on unchecked conversions.'
12715 This switch suppresses warnings for unchecked conversions
12716 where the types are known at compile time to have different
12717 sizes or conventions.
12718 @end table
12720 @geindex -gnatw.z (gcc)
12722 @geindex Size/Alignment warnings
12725 @table @asis
12727 @item @code{-gnatw.z}
12729 `Activate warnings for size not a multiple of alignment.'
12731 This switch activates warnings for cases of array and record types
12732 with specified @code{Size} and @code{Alignment} attributes where the
12733 size is not a multiple of the alignment, resulting in an object
12734 size that is greater than the specified size. The default
12735 is that such warnings are generated.
12736 @end table
12738 @geindex -gnatw.Z (gcc)
12740 @geindex Size/Alignment warnings
12743 @table @asis
12745 @item @code{-gnatw.Z}
12747 `Suppress warnings for size not a multiple of alignment.'
12749 This switch suppresses warnings for cases of array and record types
12750 with specified @code{Size} and @code{Alignment} attributes where the
12751 size is not a multiple of the alignment, resulting in an object
12752 size that is greater than the specified size. The warning can also
12753 be suppressed by giving an explicit @code{Object_Size} value.
12754 @end table
12756 @geindex -Wunused (gcc)
12759 @table @asis
12761 @item @code{-Wunused}
12763 The warnings controlled by the @code{-gnatw} switch are generated by
12764 the front end of the compiler. The GCC back end can provide
12765 additional warnings and they are controlled by the @code{-W} switch.
12766 For example, @code{-Wunused} activates back end
12767 warnings for entities that are declared but not referenced.
12768 @end table
12770 @geindex -Wuninitialized (gcc)
12773 @table @asis
12775 @item @code{-Wuninitialized}
12777 Similarly, @code{-Wuninitialized} activates
12778 the back end warning for uninitialized variables. This switch must be
12779 used in conjunction with an optimization level greater than zero.
12780 @end table
12782 @geindex -Wstack-usage (gcc)
12785 @table @asis
12787 @item @code{-Wstack-usage=`len'}
12789 Warn if the stack usage of a subprogram might be larger than @code{len} bytes.
12790 See @ref{e8,,Static Stack Usage Analysis} for details.
12791 @end table
12793 @geindex -Wall (gcc)
12796 @table @asis
12798 @item @code{-Wall}
12800 This switch enables most warnings from the GCC back end.
12801 The code generator detects a number of warning situations that are missed
12802 by the GNAT front end, and this switch can be used to activate them.
12803 The use of this switch also sets the default front-end warning mode to
12804 @code{-gnatwa}, that is, most front-end warnings are activated as well.
12805 @end table
12807 @geindex -w (gcc)
12810 @table @asis
12812 @item @code{-w}
12814 Conversely, this switch suppresses warnings from the GCC back end.
12815 The use of this switch also sets the default front-end warning mode to
12816 @code{-gnatws}, that is, front-end warnings are suppressed as well.
12817 @end table
12819 @geindex -Werror (gcc)
12822 @table @asis
12824 @item @code{-Werror}
12826 This switch causes warnings from the GCC back end to be treated as
12827 errors.  The warning string still appears, but the warning messages are
12828 counted as errors, and prevent the generation of an object file.
12829 The use of this switch also sets the default front-end warning mode to
12830 @code{-gnatwe}, that is, front-end warning messages and style check
12831 messages are treated as errors as well.
12832 @end table
12834 A string of warning parameters can be used in the same parameter. For example:
12836 @example
12837 -gnatwaGe
12838 @end example
12840 will turn on all optional warnings except for unrecognized pragma warnings,
12841 and also specify that warnings should be treated as errors.
12843 When no switch @code{-gnatw} is used, this is equivalent to:
12845 @quotation
12848 @itemize *
12850 @item 
12851 @code{-gnatw.a}
12853 @item 
12854 @code{-gnatwB}
12856 @item 
12857 @code{-gnatw.b}
12859 @item 
12860 @code{-gnatwC}
12862 @item 
12863 @code{-gnatw.C}
12865 @item 
12866 @code{-gnatwD}
12868 @item 
12869 @code{-gnatw.D}
12871 @item 
12872 @code{-gnatwF}
12874 @item 
12875 @code{-gnatw.F}
12877 @item 
12878 @code{-gnatwg}
12880 @item 
12881 @code{-gnatwH}
12883 @item 
12884 @code{-gnatw.H}
12886 @item 
12887 @code{-gnatwi}
12889 @item 
12890 @code{-gnatwJ}
12892 @item 
12893 @code{-gnatw.J}
12895 @item 
12896 @code{-gnatwK}
12898 @item 
12899 @code{-gnatw.K}
12901 @item 
12902 @code{-gnatwL}
12904 @item 
12905 @code{-gnatw.L}
12907 @item 
12908 @code{-gnatwM}
12910 @item 
12911 @code{-gnatw.m}
12913 @item 
12914 @code{-gnatwn}
12916 @item 
12917 @code{-gnatw.N}
12919 @item 
12920 @code{-gnatwo}
12922 @item 
12923 @code{-gnatw.O}
12925 @item 
12926 @code{-gnatwP}
12928 @item 
12929 @code{-gnatw.P}
12931 @item 
12932 @code{-gnatwq}
12934 @item 
12935 @code{-gnatw.Q}
12937 @item 
12938 @code{-gnatwR}
12940 @item 
12941 @code{-gnatw.R}
12943 @item 
12944 @code{-gnatw.S}
12946 @item 
12947 @code{-gnatwT}
12949 @item 
12950 @code{-gnatw.t}
12952 @item 
12953 @code{-gnatwU}
12955 @item 
12956 @code{-gnatw.U}
12958 @item 
12959 @code{-gnatwv}
12961 @item 
12962 @code{-gnatw.v}
12964 @item 
12965 @code{-gnatww}
12967 @item 
12968 @code{-gnatw.W}
12970 @item 
12971 @code{-gnatwx}
12973 @item 
12974 @code{-gnatw.X}
12976 @item 
12977 @code{-gnatwy}
12979 @item 
12980 @code{-gnatw.Y}
12982 @item 
12983 @code{-gnatwz}
12985 @item 
12986 @code{-gnatw.z}
12987 @end itemize
12988 @end quotation
12990 @node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12991 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-and-assertion-control}@anchor{f3}@anchor{gnat_ugn/building_executable_programs_with_gnat id16}@anchor{f4}
12992 @subsection Debugging and Assertion Control
12995 @geindex -gnata (gcc)
12998 @table @asis
13000 @item @code{-gnata}
13002 @geindex Assert
13004 @geindex Debug
13006 @geindex Assertions
13008 @geindex Precondition
13010 @geindex Postcondition
13012 @geindex Type invariants
13014 @geindex Subtype predicates
13016 The @code{-gnata} option is equivalent to the following @code{Assertion_Policy} pragma:
13018 @example
13019 pragma Assertion_Policy (Check);
13020 @end example
13022 Which is a shorthand for:
13024 @example
13025 pragma Assertion_Policy
13026 --  Ada RM assertion pragmas
13027   (Assert                    => Check,
13028    Static_Predicate          => Check,
13029    Dynamic_Predicate         => Check,
13030    Pre                       => Check,
13031    Pre'Class                 => Check,
13032    Post                      => Check,
13033    Post'Class                => Check,
13034    Type_Invariant            => Check,
13035    Type_Invariant'Class      => Check,
13036    Default_Initial_Condition => Check,
13037 --  GNAT specific assertion pragmas
13038    Assert_And_Cut            => Check,
13039    Assume                    => Check,
13040    Contract_Cases            => Check,
13041    Debug                     => Check,
13042    Ghost                     => Check,
13043    Initial_Condition         => Check,
13044    Loop_Invariant            => Check,
13045    Loop_Variant              => Check,
13046    Postcondition             => Check,
13047    Precondition              => Check,
13048    Predicate                 => Check,
13049    Refined_Post              => Check,
13050    Subprogram_Variant        => Check);
13051 @end example
13053 The pragmas @code{Assert} and @code{Debug} normally have no effect and
13054 are ignored. This switch, where @code{a} stands for ‘assert’, causes
13055 pragmas @code{Assert} and @code{Debug} to be activated. This switch also
13056 causes preconditions, postconditions, subtype predicates, and
13057 type invariants to be activated.
13059 The pragmas have the form:
13061 @example
13062 pragma Assert (<Boolean-expression> [, <static-string-expression>])
13063 pragma Debug (<procedure call>)
13064 pragma Type_Invariant (<type-local-name>, <Boolean-expression>)
13065 pragma Predicate (<type-local-name>, <Boolean-expression>)
13066 pragma Precondition (<Boolean-expression>, <string-expression>)
13067 pragma Postcondition (<Boolean-expression>, <string-expression>)
13068 @end example
13070 The aspects have the form:
13072 @example
13073 with [Pre|Post|Type_Invariant|Dynamic_Predicate|Static_Predicate]
13074   => <Boolean-expression>;
13075 @end example
13077 The @code{Assert} pragma causes @code{Boolean-expression} to be tested.
13078 If the result is @code{True}, the pragma has no effect (other than
13079 possible side effects from evaluating the expression). If the result is
13080 @code{False}, the exception @code{Assert_Failure} declared in the package
13081 @code{System.Assertions} is raised (passing @code{static-string-expression}, if
13082 present, as the message associated with the exception). If no string
13083 expression is given, the default is a string containing the file name and
13084 line number of the pragma.
13086 The @code{Debug} pragma causes @code{procedure} to be called. Note that
13087 @code{pragma Debug} may appear within a declaration sequence, allowing
13088 debugging procedures to be called between declarations.
13090 For the aspect specification, the @code{Boolean-expression} is evaluated.
13091 If the result is @code{True}, the aspect has no effect. If the result
13092 is @code{False}, the exception @code{Assert_Failure} is raised.
13093 @end table
13095 @node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
13096 @anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{f5}@anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{e9}
13097 @subsection Validity Checking
13100 @geindex Validity Checking
13102 The Ada Reference Manual defines the concept of invalid values (see
13103 RM 13.9.1). The primary source of invalid values is uninitialized
13104 variables. A scalar variable that is left uninitialized may contain
13105 an invalid value; the concept of invalid does not apply to access or
13106 composite types.
13108 It is an error to read an invalid value, but the RM does not require
13109 run-time checks to detect such errors, except for some minimal
13110 checking to prevent erroneous execution (i.e. unpredictable
13111 behavior). This corresponds to the @code{-gnatVd} switch below,
13112 which is the default. For example, by default, if the expression of a
13113 case statement is invalid, it will raise Constraint_Error rather than
13114 causing a wild jump, and if an array index on the left-hand side of an
13115 assignment is invalid, it will raise Constraint_Error rather than
13116 overwriting an arbitrary memory location.
13118 The @code{-gnatVa} may be used to enable additional validity checks,
13119 which are not required by the RM. These checks are often very
13120 expensive (which is why the RM does not require them). These checks
13121 are useful in tracking down uninitialized variables, but they are
13122 not usually recommended for production builds, and in particular
13123 we do not recommend using these extra validity checking options in
13124 combination with optimization, since this can confuse the optimizer.
13125 If performance is a consideration, leading to the need to optimize,
13126 then the validity checking options should not be used.
13128 The other @code{-gnatV`x'} switches below allow finer-grained
13129 control; you can enable whichever validity checks you desire. However,
13130 for most debugging purposes, @code{-gnatVa} is sufficient, and the
13131 default @code{-gnatVd} (i.e. standard Ada behavior) is usually
13132 sufficient for non-debugging use.
13134 The @code{-gnatB} switch tells the compiler to assume that all
13135 values are valid (that is, within their declared subtype range)
13136 except in the context of a use of the Valid attribute. This means
13137 the compiler can generate more efficient code, since the range
13138 of values is better known at compile time. However, an uninitialized
13139 variable can cause wild jumps and memory corruption in this mode.
13141 The @code{-gnatV`x'} switch allows control over the validity
13142 checking mode as described below.
13143 The @code{x} argument is a string of letters that
13144 indicate validity checks that are performed or not performed in addition
13145 to the default checks required by Ada as described above.
13147 @geindex -gnatVa (gcc)
13150 @table @asis
13152 @item @code{-gnatVa}
13154 `All validity checks.'
13156 All validity checks are turned on.
13157 That is, @code{-gnatVa} is
13158 equivalent to @code{gnatVcdefimoprst}.
13159 @end table
13161 @geindex -gnatVc (gcc)
13164 @table @asis
13166 @item @code{-gnatVc}
13168 `Validity checks for copies.'
13170 The right-hand side of assignments, and the (explicit) initializing values
13171 of object declarations are validity checked.
13172 @end table
13174 @geindex -gnatVd (gcc)
13177 @table @asis
13179 @item @code{-gnatVd}
13181 `Default (RM) validity checks.'
13183 Some validity checks are required by Ada (see RM 13.9.1 (9-11)); these
13184 (and only these) validity checks are enabled by default.
13185 For case statements (and case expressions) that lack a “when others =>”
13186 choice, a check is made that the value of the selector expression
13187 belongs to its nominal subtype. If it does not, Constraint_Error is raised.
13188 For assignments to array components (and for indexed components in some
13189 other contexts), a check is made that each index expression belongs to the
13190 corresponding index subtype. If it does not, Constraint_Error is raised.
13191 Both these validity checks may be turned off using switch @code{-gnatVD}.
13192 They are turned on by default. If @code{-gnatVD} is specified, a subsequent
13193 switch @code{-gnatVd} will leave the checks turned on.
13194 Switch @code{-gnatVD} should be used only if you are sure that all such
13195 expressions have valid values. If you use this switch and invalid values
13196 are present, then the program is erroneous, and wild jumps or memory
13197 overwriting may occur.
13198 @end table
13200 @geindex -gnatVe (gcc)
13203 @table @asis
13205 @item @code{-gnatVe}
13207 `Validity checks for scalar components.'
13209 In the absence of this switch, assignments to scalar components of
13210 enclosing record or array objects are not validity checked, even if
13211 validity checks for assignments generally (@code{-gnatVc}) are turned on.
13212 Specifying this switch enables such checks.
13213 This switch has no effect if the @code{-gnatVc} switch is not specified.
13214 @end table
13216 @geindex -gnatVf (gcc)
13219 @table @asis
13221 @item @code{-gnatVf}
13223 `Validity checks for floating-point values.'
13225 Specifying this switch enables validity checking for floating-point
13226 values in the same contexts where validity checking is enabled for
13227 other scalar values.
13228 In the absence of this switch, validity checking is not performed for
13229 floating-point values. This takes precedence over other statements about
13230 performing validity checking for scalar objects in various scenarios.
13231 One way to look at it is that if this switch is not set, then whenever
13232 any of the other rules in this section use the word “scalar” they
13233 really mean “scalar and not floating-point”.
13234 If @code{-gnatVf} is specified, then validity checking also applies
13235 for floating-point values, and NaNs and infinities are considered invalid,
13236 as well as out-of-range values for constrained types. The exact contexts
13237 in which floating-point values are checked depends on the setting of other
13238 options. For example, @code{-gnatVif} or @code{-gnatVfi}
13239 (the order does not matter) specifies that floating-point parameters of mode
13240 @code{in} should be validity checked.
13241 @end table
13243 @geindex -gnatVi (gcc)
13246 @table @asis
13248 @item @code{-gnatVi}
13250 `Validity checks for `@w{`}in`@w{`} mode parameters.'
13252 Arguments for parameters of mode @code{in} are validity checked in function
13253 and procedure calls at the point of call.
13254 @end table
13256 @geindex -gnatVm (gcc)
13259 @table @asis
13261 @item @code{-gnatVm}
13263 `Validity checks for `@w{`}in out`@w{`} mode parameters.'
13265 Arguments for parameters of mode @code{in out} are validity checked in
13266 procedure calls at the point of call. The @code{'m'} here stands for
13267 modify, since this concerns parameters that can be modified by the call.
13268 Note that there is no specific option to test @code{out} parameters,
13269 but any reference within the subprogram will be tested in the usual
13270 manner, and if an invalid value is copied back, any reference to it
13271 will be subject to validity checking.
13272 @end table
13274 @geindex -gnatVn (gcc)
13277 @table @asis
13279 @item @code{-gnatVn}
13281 `No validity checks.'
13283 This switch turns off all validity checking, including the default checking
13284 for case statements and left hand side subscripts. Note that the use of
13285 the switch @code{-gnatp} suppresses all run-time checks, including
13286 validity checks, and thus implies @code{-gnatVn}. When this switch
13287 is used, it cancels any other @code{-gnatV} previously issued.
13288 @end table
13290 @geindex -gnatVo (gcc)
13293 @table @asis
13295 @item @code{-gnatVo}
13297 `Validity checks for operator and attribute operands.'
13299 Scalar arguments for predefined operators and for attributes are
13300 validity checked.
13301 This includes all operators in package @code{Standard},
13302 the shift operators defined as intrinsic in package @code{Interfaces}
13303 and operands for attributes such as @code{Pos}. Checks are also made
13304 on individual component values for composite comparisons, and on the
13305 expressions in type conversions and qualified expressions. Checks are
13306 also made on explicit ranges using @code{..} (e.g., slices, loops etc).
13307 @end table
13309 @geindex -gnatVp (gcc)
13312 @table @asis
13314 @item @code{-gnatVp}
13316 `Validity checks for parameters.'
13318 This controls the treatment of formal parameters within a subprogram (as
13319 opposed to @code{-gnatVi} and @code{-gnatVm}, which control validity
13320 testing of actual parameters of a call). If either of these call options is
13321 specified, then normally an assumption is made within a subprogram that
13322 the validity of any incoming formal parameters of the corresponding mode(s)
13323 has already been checked at the point of call and does not need rechecking.
13324 If @code{-gnatVp} is set, then this assumption is not made and so their
13325 validity may be checked (or rechecked) within the subprogram. If neither of
13326 the two call-related options is specified, then this switch has no effect.
13327 @end table
13329 @geindex -gnatVr (gcc)
13332 @table @asis
13334 @item @code{-gnatVr}
13336 `Validity checks for function returns.'
13338 The expression in simple @code{return} statements in functions is validity
13339 checked.
13340 @end table
13342 @geindex -gnatVs (gcc)
13345 @table @asis
13347 @item @code{-gnatVs}
13349 `Validity checks for subscripts.'
13351 All subscript expressions are checked for validity, whatever context
13352 they occur in (in default mode some subscripts are not validity checked;
13353 for example, validity checking may be omitted in some cases involving
13354 a read of a component of an array).
13355 @end table
13357 @geindex -gnatVt (gcc)
13360 @table @asis
13362 @item @code{-gnatVt}
13364 `Validity checks for tests.'
13366 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
13367 statements are checked, as well as guard expressions in entry calls.
13368 @end table
13370 The @code{-gnatV} switch may be followed by a string of letters
13371 to turn on a series of validity checking options.
13372 For example, @code{-gnatVcr}
13373 specifies that in addition to the default validity checking, copies and
13374 function return expressions are to be validity checked.
13375 In order to make it easier to specify the desired combination of effects,
13376 the upper case letters @code{CDFIMORST} may
13377 be used to turn off the corresponding lower case option.
13378 Thus @code{-gnatVaM} turns on all validity checking options except for
13379 checking of @code{in out} parameters.
13381 The specification of additional validity checking generates extra code (and
13382 in the case of @code{-gnatVa} the code expansion can be substantial).
13383 However, these additional checks can be very useful in detecting
13384 uninitialized variables, incorrect use of unchecked conversion, and other
13385 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
13386 is useful in conjunction with the extra validity checking, since this
13387 ensures that wherever possible uninitialized variables have invalid values.
13389 See also the pragma @code{Validity_Checks} which allows modification of
13390 the validity checking mode at the program source level, and also allows for
13391 temporary disabling of validity checks.
13393 @node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
13394 @anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{ee}
13395 @subsection Style Checking
13398 @geindex Style checking
13400 @geindex -gnaty (gcc)
13402 The @code{-gnaty} switch causes the compiler to
13403 enforce specified style rules. A limited set of style rules has been used
13404 in writing the GNAT sources themselves. This switch allows user programs
13405 to activate all or some of these checks. If the source program fails a
13406 specified style check, an appropriate message is given, preceded by
13407 the character sequence ‘(style)’. This message does not prevent
13408 successful compilation (unless the @code{-gnatwe} switch is used).
13410 Note that this is by no means intended to be a general facility for
13411 checking arbitrary coding standards. It is simply an embedding of the
13412 style rules we have chosen for the GNAT sources. If you are starting
13413 a project which does not have established style standards, you may
13414 find it useful to adopt the entire set of GNAT coding standards, or
13415 some subset of them.
13418 The string @code{x} is a sequence of letters or digits
13419 indicating the particular style
13420 checks to be performed. The following checks are defined:
13422 @geindex -gnaty[0-9] (gcc)
13425 @table @asis
13427 @item @code{-gnaty0}
13429 `Specify indentation level.'
13431 If a digit from 1-9 appears
13432 in the string after @code{-gnaty}
13433 then proper indentation is checked, with the digit indicating the
13434 indentation level required. A value of zero turns off this style check.
13435 The rule checks that the following constructs start on a column that is
13436 a multiple of the alignment level:
13439 @itemize *
13441 @item 
13442 beginnings of declarations (except record component declarations)
13443 and statements;
13445 @item 
13446 beginnings of the structural components of compound statements;
13448 @item 
13449 @code{end} keyword that completes the declaration of a program unit declaration
13450 or body or that completes a compound statement.
13451 @end itemize
13453 Full line comments must be
13454 aligned with the @code{--} starting on a column that is a multiple of
13455 the alignment level, or they may be aligned the same way as the following
13456 non-blank line (this is useful when full line comments appear in the middle
13457 of a statement, or they may be aligned with the source line on the previous
13458 non-blank line.
13459 @end table
13461 @geindex -gnatya (gcc)
13464 @table @asis
13466 @item @code{-gnatya}
13468 `Check attribute casing.'
13470 Attribute names, including the case of keywords such as @code{digits}
13471 used as attributes names, must be written in mixed case, that is, the
13472 initial letter and any letter following an underscore must be uppercase.
13473 All other letters must be lowercase.
13474 @end table
13476 @geindex -gnatyA (gcc)
13479 @table @asis
13481 @item @code{-gnatyA}
13483 `Use of array index numbers in array attributes.'
13485 When using the array attributes First, Last, Range,
13486 or Length, the index number must be omitted for one-dimensional arrays
13487 and is required for multi-dimensional arrays.
13488 @end table
13490 @geindex -gnatyb (gcc)
13493 @table @asis
13495 @item @code{-gnatyb}
13497 `Blanks not allowed at statement end.'
13499 Trailing blanks are not allowed at the end of statements. The purpose of this
13500 rule, together with h (no horizontal tabs), is to enforce a canonical format
13501 for the use of blanks to separate source tokens.
13502 @end table
13504 @geindex -gnatyB (gcc)
13507 @table @asis
13509 @item @code{-gnatyB}
13511 `Check Boolean operators.'
13513 The use of AND/OR operators is not permitted except in the cases of modular
13514 operands, array operands, and simple stand-alone boolean variables or
13515 boolean constants. In all other cases @code{and then}/@cite{or else} are
13516 required.
13517 @end table
13519 @geindex -gnatyc (gcc)
13522 @table @asis
13524 @item @code{-gnatyc}
13526 `Check comments, double space.'
13528 Comments must meet the following set of rules:
13531 @itemize *
13533 @item 
13534 The @code{--} that starts the column must either start in column one,
13535 or else at least one blank must precede this sequence.
13537 @item 
13538 Comments that follow other tokens on a line must have at least one blank
13539 following the @code{--} at the start of the comment.
13541 @item 
13542 Full line comments must have at least two blanks following the
13543 @code{--} that starts the comment, with the following exceptions.
13545 @item 
13546 A line consisting only of the @code{--} characters, possibly preceded
13547 by blanks is permitted.
13549 @item 
13550 A comment starting with @code{--x} where @code{x} is a special character
13551 is permitted.
13552 This allows proper processing of the output from specialized tools
13553 such as @code{gnatprep} (where @code{--!} is used) and in earlier versions of the SPARK
13554 annotation
13555 language (where @code{--#} is used). For the purposes of this rule, a
13556 special character is defined as being in one of the ASCII ranges
13557 @code{16#21#...16#2F#} or @code{16#3A#...16#3F#}.
13558 Note that this usage is not permitted
13559 in GNAT implementation units (i.e., when @code{-gnatg} is used).
13561 @item 
13562 A line consisting entirely of minus signs, possibly preceded by blanks, is
13563 permitted. This allows the construction of box comments where lines of minus
13564 signs are used to form the top and bottom of the box.
13566 @item 
13567 A comment that starts and ends with @code{--} is permitted as long as at
13568 least one blank follows the initial @code{--}. Together with the preceding
13569 rule, this allows the construction of box comments, as shown in the following
13570 example:
13572 @example
13573 ---------------------------
13574 -- This is a box comment --
13575 -- with two text lines.  --
13576 ---------------------------
13577 @end example
13578 @end itemize
13579 @end table
13581 @geindex -gnatyC (gcc)
13584 @table @asis
13586 @item @code{-gnatyC}
13588 `Check comments, single space.'
13590 This is identical to @code{c} except that only one space
13591 is required following the @code{--} of a comment instead of two.
13592 @end table
13594 @geindex -gnatyd (gcc)
13597 @table @asis
13599 @item @code{-gnatyd}
13601 `Check no DOS line terminators present.'
13603 All lines must be terminated by a single ASCII.LF
13604 character (in particular the DOS line terminator sequence CR/LF is not
13605 allowed).
13606 @end table
13608 @geindex -gnatyD (gcc)
13611 @table @asis
13613 @item @code{-gnatyD}
13615 `Check declared identifiers in mixed case.'
13617 Declared identifiers must be in mixed case, as in
13618 This_Is_An_Identifier. Use -gnatyr in addition to ensure
13619 that references match declarations.
13620 @end table
13622 @geindex -gnatye (gcc)
13625 @table @asis
13627 @item @code{-gnatye}
13629 `Check end/exit labels.'
13631 Optional labels on @code{end} statements ending subprograms and on
13632 @code{exit} statements exiting named loops, are required to be present.
13633 @end table
13635 @geindex -gnatyf (gcc)
13638 @table @asis
13640 @item @code{-gnatyf}
13642 `No form feeds or vertical tabs.'
13644 Neither form feeds nor vertical tab characters are permitted
13645 in the source text.
13646 @end table
13648 @geindex -gnatyg (gcc)
13651 @table @asis
13653 @item @code{-gnatyg}
13655 `GNAT style mode.'
13657 The set of style check switches is set to match that used by the GNAT sources.
13658 This may be useful when developing code that is eventually intended to be
13659 incorporated into GNAT. Currently this is equivalent to
13660 @code{-gnatyydISuxz}) but additional style switches may be added to this
13661 set in the future without advance notice.
13662 @end table
13664 @geindex -gnatyh (gcc)
13667 @table @asis
13669 @item @code{-gnatyh}
13671 `No horizontal tabs.'
13673 Horizontal tab characters are not permitted in the source text.
13674 Together with the b (no blanks at end of line) check, this
13675 enforces a canonical form for the use of blanks to separate
13676 source tokens.
13677 @end table
13679 @geindex -gnatyi (gcc)
13682 @table @asis
13684 @item @code{-gnatyi}
13686 `Check if-then layout.'
13688 The keyword @code{then} must appear either on the same
13689 line as corresponding @code{if}, or on a line on its own, lined
13690 up under the @code{if}.
13691 @end table
13693 @geindex -gnatyI (gcc)
13696 @table @asis
13698 @item @code{-gnatyI}
13700 `check mode IN keywords.'
13702 Mode @code{in} (the default mode) is not
13703 allowed to be given explicitly. @code{in out} is fine,
13704 but not @code{in} on its own.
13705 @end table
13707 @geindex -gnatyk (gcc)
13710 @table @asis
13712 @item @code{-gnatyk}
13714 `Check keyword casing.'
13716 All keywords must be in lower case (with the exception of keywords
13717 such as @code{digits} used as attribute names to which this check
13718 does not apply). A single error is reported for each line breaking
13719 this rule even if multiple casing issues exist on a same line.
13720 @end table
13722 @geindex -gnatyl (gcc)
13725 @table @asis
13727 @item @code{-gnatyl}
13729 `Check layout.'
13731 Layout of statement and declaration constructs must follow the
13732 recommendations in the Ada Reference Manual, as indicated by the
13733 form of the syntax rules. For example an @code{else} keyword must
13734 be lined up with the corresponding @code{if} keyword.
13736 There are two respects in which the style rule enforced by this check
13737 option are more liberal than those in the Ada Reference Manual. First
13738 in the case of record declarations, it is permissible to put the
13739 @code{record} keyword on the same line as the @code{type} keyword, and
13740 then the @code{end} in @code{end record} must line up under @code{type}.
13741 This is also permitted when the type declaration is split on two lines.
13742 For example, any of the following three layouts is acceptable:
13744 @example
13745 type q is record
13746    a : integer;
13747    b : integer;
13748 end record;
13750 type q is
13751    record
13752       a : integer;
13753       b : integer;
13754    end record;
13756 type q is
13757    record
13758       a : integer;
13759       b : integer;
13760 end record;
13761 @end example
13763 Second, in the case of a block statement, a permitted alternative
13764 is to put the block label on the same line as the @code{declare} or
13765 @code{begin} keyword, and then line the @code{end} keyword up under
13766 the block label. For example both the following are permitted:
13768 @example
13769 Block : declare
13770    A : Integer := 3;
13771 begin
13772    Proc (A, A);
13773 end Block;
13775 Block :
13776    declare
13777       A : Integer := 3;
13778    begin
13779       Proc (A, A);
13780    end Block;
13781 @end example
13783 The same alternative format is allowed for loops. For example, both of
13784 the following are permitted:
13786 @example
13787 Clear : while J < 10 loop
13788    A (J) := 0;
13789 end loop Clear;
13791 Clear :
13792    while J < 10 loop
13793       A (J) := 0;
13794    end loop Clear;
13795 @end example
13796 @end table
13798 @geindex -gnatyLnnn (gcc)
13801 @table @asis
13803 @item @code{-gnatyL}
13805 `Set maximum nesting level.'
13807 The maximum level of nesting of constructs (including subprograms, loops,
13808 blocks, packages, and conditionals) may not exceed the given value
13809 `nnn'. A value of zero disconnects this style check.
13810 @end table
13812 @geindex -gnatym (gcc)
13815 @table @asis
13817 @item @code{-gnatym}
13819 `Check maximum line length.'
13821 The length of source lines must not exceed 79 characters, including
13822 any trailing blanks. The value of 79 allows convenient display on an
13823 80 character wide device or window, allowing for possible special
13824 treatment of 80 character lines. Note that this count is of
13825 characters in the source text. This means that a tab character counts
13826 as one character in this count and a wide character sequence counts as
13827 a single character (however many bytes are needed in the encoding).
13828 @end table
13830 @geindex -gnatyMnnn (gcc)
13833 @table @asis
13835 @item @code{-gnatyM}
13837 `Set maximum line length.'
13839 The length of lines must not exceed the
13840 given value `nnn'. The maximum value that can be specified is 32767.
13841 If neither style option for setting the line length is used, then the
13842 default is 255. This also controls the maximum length of lexical elements,
13843 where the only restriction is that they must fit on a single line.
13844 @end table
13846 @geindex -gnatyn (gcc)
13849 @table @asis
13851 @item @code{-gnatyn}
13853 `Check casing of entities in Standard.'
13855 Any identifier from Standard must be cased
13856 to match the presentation in the Ada Reference Manual (for example,
13857 @code{Integer} and @code{ASCII.NUL}).
13858 @end table
13860 @geindex -gnatyN (gcc)
13863 @table @asis
13865 @item @code{-gnatyN}
13867 `Turn off all style checks.'
13869 All style check options are turned off.
13870 @end table
13872 @geindex -gnatyo (gcc)
13875 @table @asis
13877 @item @code{-gnatyo}
13879 `Check order of subprogram bodies.'
13881 All subprogram bodies in a given scope
13882 (e.g., a package body) must be in alphabetical order. The ordering
13883 rule uses normal Ada rules for comparing strings, ignoring casing
13884 of letters, except that if there is a trailing numeric suffix, then
13885 the value of this suffix is used in the ordering (e.g., Junk2 comes
13886 before Junk10).
13887 @end table
13889 @geindex -gnatyO (gcc)
13892 @table @asis
13894 @item @code{-gnatyO}
13896 `Check that overriding subprograms are explicitly marked as such.'
13898 This applies to all subprograms of a derived type that override a primitive
13899 operation of the type, for both tagged and untagged types. In particular,
13900 the declaration of a primitive operation of a type extension that overrides
13901 an inherited operation must carry an overriding indicator. Another case is
13902 the declaration of a function that overrides a predefined operator (such
13903 as an equality operator).
13904 @end table
13906 @geindex -gnatyp (gcc)
13909 @table @asis
13911 @item @code{-gnatyp}
13913 `Check pragma casing.'
13915 Pragma names must be written in mixed case, that is, the
13916 initial letter and any letter following an underscore must be uppercase.
13917 All other letters must be lowercase. An exception is that SPARK_Mode is
13918 allowed as an alternative for Spark_Mode.
13919 @end table
13921 @geindex -gnatyr (gcc)
13924 @table @asis
13926 @item @code{-gnatyr}
13928 `Check references.'
13930 All identifier references must be cased in the same way as the
13931 corresponding declaration. No specific casing style is imposed on
13932 identifiers. The only requirement is for consistency of references
13933 with declarations.
13934 @end table
13936 @geindex -gnatys (gcc)
13939 @table @asis
13941 @item @code{-gnatys}
13943 `Check separate specs.'
13945 Separate declarations (‘specs’) are required for subprograms (a
13946 body is not allowed to serve as its own declaration). The only
13947 exception is that parameterless library level procedures are
13948 not required to have a separate declaration. This exception covers
13949 the most frequent form of main program procedures.
13950 @end table
13952 @geindex -gnatyS (gcc)
13955 @table @asis
13957 @item @code{-gnatyS}
13959 `Check no statements after then/else.'
13961 No statements are allowed
13962 on the same line as a @code{then} or @code{else} keyword following the
13963 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
13964 affected, and a special exception allows a pragma to appear after @code{else}.
13965 @end table
13967 @geindex -gnatyt (gcc)
13970 @table @asis
13972 @item @code{-gnatyt}
13974 `Check token spacing.'
13976 The following token spacing rules are enforced:
13979 @itemize *
13981 @item 
13982 The keywords @code{abs} and @code{not} must be followed by a space.
13984 @item 
13985 The token @code{=>} must be surrounded by spaces.
13987 @item 
13988 The token @code{<>} must be preceded by a space or a left parenthesis.
13990 @item 
13991 Binary operators other than @code{**} must be surrounded by spaces.
13992 There is no restriction on the layout of the @code{**} binary operator.
13994 @item 
13995 Colon must be surrounded by spaces.
13997 @item 
13998 Colon-equal (assignment, initialization) must be surrounded by spaces.
14000 @item 
14001 Comma must be the first non-blank character on the line, or be
14002 immediately preceded by a non-blank character, and must be followed
14003 by a space.
14005 @item 
14006 If the token preceding a left parenthesis ends with a letter or digit, then
14007 a space must separate the two tokens.
14009 @item 
14010 If the token following a right parenthesis starts with a letter or digit, then
14011 a space must separate the two tokens.
14013 @item 
14014 A right parenthesis must either be the first non-blank character on
14015 a line, or it must be preceded by a non-blank character.
14017 @item 
14018 A semicolon must not be preceded by a space, and must not be followed by
14019 a non-blank character.
14021 @item 
14022 A unary plus or minus may not be followed by a space.
14024 @item 
14025 A vertical bar must be surrounded by spaces.
14026 @end itemize
14028 Exactly one blank (and no other white space) must appear between
14029 a @code{not} token and a following @code{in} token.
14030 @end table
14032 @geindex -gnatyu (gcc)
14035 @table @asis
14037 @item @code{-gnatyu}
14039 `Check unnecessary blank lines.'
14041 Unnecessary blank lines are not allowed. A blank line is considered
14042 unnecessary if it appears at the end of the file, or if more than
14043 one blank line occurs in sequence.
14044 @end table
14046 @geindex -gnatyx (gcc)
14049 @table @asis
14051 @item @code{-gnatyx}
14053 `Check extra parentheses.'
14055 Unnecessary extra levels of parentheses (C-style) are not allowed
14056 around conditions (or selection expressions) in @code{if}, @code{while},
14057 @code{case}, and @code{exit} statements, as well as part of ranges.
14058 @end table
14060 @geindex -gnatyy (gcc)
14063 @table @asis
14065 @item @code{-gnatyy}
14067 `Set all standard style check options.'
14069 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
14070 options enabled with the exception of @code{-gnatyB}, @code{-gnatyd},
14071 @code{-gnatyI}, @code{-gnatyLnnn}, @code{-gnatyo}, @code{-gnatyO},
14072 @code{-gnatyS}, @code{-gnatyu}, and @code{-gnatyx}.
14073 @end table
14075 @geindex -gnatyz (gcc)
14078 @table @asis
14080 @item @code{-gnatyz}
14082 `Check extra parentheses (operator precedence).'
14084 Extra levels of parentheses that are not required by operator precedence
14085 rules are flagged. See also @code{-gnatyx}.
14086 @end table
14088 @geindex -gnaty- (gcc)
14091 @table @asis
14093 @item @code{-gnaty-}
14095 `Remove style check options.'
14097 This causes any subsequent options in the string to act as canceling the
14098 corresponding style check option. To cancel maximum nesting level control,
14099 use the @code{L} parameter without any integer value after that, because any
14100 digit following `-' in the parameter string of the @code{-gnaty}
14101 option will be treated as canceling the indentation check. The same is true
14102 for the @code{M} parameter. @code{y} and @code{N} parameters are not
14103 allowed after `-'.
14104 @end table
14106 @geindex -gnaty+ (gcc)
14109 @table @asis
14111 @item @code{-gnaty+}
14113 `Enable style check options.'
14115 This causes any subsequent options in the string to enable the corresponding
14116 style check option. That is, it cancels the effect of a previous -,
14117 if any.
14118 @end table
14120 @c end of switch description (leave this comment to ease automatic parsing for
14122 @c GNAT Studio)
14124 In the above rules, appearing in column one is always permitted, that is,
14125 counts as meeting either a requirement for a required preceding space,
14126 or as meeting a requirement for no preceding space.
14128 Appearing at the end of a line is also always permitted, that is, counts
14129 as meeting either a requirement for a following space, or as meeting
14130 a requirement for no following space.
14132 If any of these style rules is violated, a message is generated giving
14133 details on the violation. The initial characters of such messages are
14134 always ‘@cite{(style)}’. Note that these messages are treated as warning
14135 messages, so they normally do not prevent the generation of an object
14136 file. The @code{-gnatwe} switch can be used to treat warning messages,
14137 including style messages, as fatal errors.
14139 The switch @code{-gnaty} on its own (that is not
14140 followed by any letters or digits) is equivalent
14141 to the use of @code{-gnatyy} as described above, that is all
14142 built-in standard style check options are enabled.
14144 The switch @code{-gnatyN} clears any previously set style checks.
14146 @node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
14147 @anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{f7}@anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{ec}
14148 @subsection Run-Time Checks
14151 @geindex Division by zero
14153 @geindex Access before elaboration
14155 @geindex Checks
14156 @geindex division by zero
14158 @geindex Checks
14159 @geindex access before elaboration
14161 @geindex Checks
14162 @geindex stack overflow checking
14164 By default, the following checks are suppressed: stack overflow
14165 checks, and checks for access before elaboration on subprogram
14166 calls. All other checks, including overflow checks, range checks and
14167 array bounds checks, are turned on by default. The following @code{gcc}
14168 switches refine this default behavior.
14170 @geindex -gnatp (gcc)
14173 @table @asis
14175 @item @code{-gnatp}
14177 @geindex Suppressing checks
14179 @geindex Checks
14180 @geindex suppressing
14182 This switch causes the unit to be compiled
14183 as though @code{pragma Suppress (All_checks)}
14184 had been present in the source. Validity checks are also eliminated (in
14185 other words @code{-gnatp} also implies @code{-gnatVn}.
14186 Use this switch to improve the performance
14187 of the code at the expense of safety in the presence of invalid data or
14188 program bugs.
14190 Note that when checks are suppressed, the compiler is allowed, but not
14191 required, to omit the checking code. If the run-time cost of the
14192 checking code is zero or near-zero, the compiler will generate it even
14193 if checks are suppressed. In particular, if the compiler can prove
14194 that a certain check will necessarily fail, it will generate code to
14195 do an unconditional ‘raise’, even if checks are suppressed. The
14196 compiler warns in this case. Another case in which checks may not be
14197 eliminated is when they are embedded in certain run-time routines such
14198 as math library routines.
14200 Of course, run-time checks are omitted whenever the compiler can prove
14201 that they will not fail, whether or not checks are suppressed.
14203 Note that if you suppress a check that would have failed, program
14204 execution is erroneous, which means the behavior is totally
14205 unpredictable. The program might crash, or print wrong answers, or
14206 do anything else. It might even do exactly what you wanted it to do
14207 (and then it might start failing mysteriously next week or next
14208 year). The compiler will generate code based on the assumption that
14209 the condition being checked is true, which can result in erroneous
14210 execution if that assumption is wrong.
14212 The checks subject to suppression include all the checks defined by the Ada
14213 standard, the additional implementation defined checks @code{Alignment_Check},
14214 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, @code{Container_Checks}, @code{Tampering_Check},
14215 and @code{Validity_Check}, as well as any checks introduced using @code{pragma Check_Name}.
14216 Note that @code{Atomic_Synchronization} is not automatically suppressed by use of this option.
14218 If the code depends on certain checks being active, you can use
14219 pragma @code{Unsuppress} either as a configuration pragma or as
14220 a local pragma to make sure that a specified check is performed
14221 even if @code{gnatp} is specified.
14223 The @code{-gnatp} switch has no effect if a subsequent
14224 @code{-gnat-p} switch appears.
14225 @end table
14227 @geindex -gnat-p (gcc)
14229 @geindex Suppressing checks
14231 @geindex Checks
14232 @geindex suppressing
14234 @geindex Suppress
14237 @table @asis
14239 @item @code{-gnat-p}
14241 This switch cancels the effect of a previous @code{gnatp} switch.
14242 @end table
14244 @geindex -gnato?? (gcc)
14246 @geindex Overflow checks
14248 @geindex Overflow mode
14250 @geindex Check
14251 @geindex overflow
14254 @table @asis
14256 @item @code{-gnato??}
14258 This switch controls the mode used for computing intermediate
14259 arithmetic integer operations, and also enables overflow checking.
14260 For a full description of overflow mode and checking control, see
14261 the ‘Overflow Check Handling in GNAT’ appendix in this
14262 User’s Guide.
14264 Overflow checks are always enabled by this switch. The argument
14265 controls the mode, using the codes
14268 @table @asis
14270 @item `1 = STRICT'
14272 In STRICT mode, intermediate operations are always done using the
14273 base type, and overflow checking ensures that the result is within
14274 the base type range.
14276 @item `2 = MINIMIZED'
14278 In MINIMIZED mode, overflows in intermediate operations are avoided
14279 where possible by using a larger integer type for the computation
14280 (typically @code{Long_Long_Integer}). Overflow checking ensures that
14281 the result fits in this larger integer type.
14283 @item `3 = ELIMINATED'
14285 In ELIMINATED mode, overflows in intermediate operations are avoided
14286 by using multi-precision arithmetic. In this case, overflow checking
14287 has no effect on intermediate operations (since overflow is impossible).
14288 @end table
14290 If two digits are present after @code{-gnato} then the first digit
14291 sets the mode for expressions outside assertions, and the second digit
14292 sets the mode for expressions within assertions. Here assertions is used
14293 in the technical sense (which includes for example precondition and
14294 postcondition expressions).
14296 If one digit is present, the corresponding mode is applicable to both
14297 expressions within and outside assertion expressions.
14299 If no digits are present, the default is to enable overflow checks
14300 and set STRICT mode for both kinds of expressions. This is compatible
14301 with the use of @code{-gnato} in previous versions of GNAT.
14303 @geindex Machine_Overflows
14305 Note that the @code{-gnato??} switch does not affect the code generated
14306 for any floating-point operations; it applies only to integer semantics.
14307 For floating-point, GNAT has the @code{Machine_Overflows}
14308 attribute set to @code{False} and the normal mode of operation is to
14309 generate IEEE NaN and infinite values on overflow or invalid operations
14310 (such as dividing 0.0 by 0.0).
14312 The reason that we distinguish overflow checking from other kinds of
14313 range constraint checking is that a failure of an overflow check, unlike
14314 for example the failure of a range check, can result in an incorrect
14315 value, but cannot cause random memory destruction (like an out of range
14316 subscript), or a wild jump (from an out of range case value). Overflow
14317 checking is also quite expensive in time and space, since in general it
14318 requires the use of double length arithmetic.
14320 Note again that the default is @code{-gnato11} (equivalent to @code{-gnato1}),
14321 so overflow checking is performed in STRICT mode by default.
14322 @end table
14324 @geindex -gnatE (gcc)
14326 @geindex Elaboration checks
14328 @geindex Check
14329 @geindex elaboration
14332 @table @asis
14334 @item @code{-gnatE}
14336 Enables dynamic checks for access-before-elaboration
14337 on subprogram calls and generic instantiations.
14338 Note that @code{-gnatE} is not necessary for safety, because in the
14339 default mode, GNAT ensures statically that the checks would not fail.
14340 For full details of the effect and use of this switch,
14341 @ref{c9,,Compiling with gcc}.
14342 @end table
14344 @geindex -fstack-check (gcc)
14346 @geindex Stack Overflow Checking
14348 @geindex Checks
14349 @geindex stack overflow checking
14352 @table @asis
14354 @item @code{-fstack-check}
14356 Activates stack overflow checking. For full details of the effect and use of
14357 this switch see @ref{e7,,Stack Overflow Checking}.
14358 @end table
14360 @geindex Unsuppress
14362 The setting of these switches only controls the default setting of the
14363 checks. You may modify them using either @code{Suppress} (to remove
14364 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
14365 the program source.
14367 @node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
14368 @anchor{gnat_ugn/building_executable_programs_with_gnat id20}@anchor{f8}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-syntax-checking}@anchor{f9}
14369 @subsection Using @code{gcc} for Syntax Checking
14372 @geindex -gnats (gcc)
14375 @table @asis
14377 @item @code{-gnats}
14379 The @code{s} stands for ‘syntax’.
14381 Run GNAT in syntax checking only mode. For
14382 example, the command
14384 @example
14385 $ gcc -c -gnats x.adb
14386 @end example
14388 compiles file @code{x.adb} in syntax-check-only mode. You can check a
14389 series of files in a single command
14390 , and can use wildcards to specify such a group of files.
14391 Note that you must specify the @code{-c} (compile
14392 only) flag in addition to the @code{-gnats} flag.
14394 You may use other switches in conjunction with @code{-gnats}. In
14395 particular, @code{-gnatl} and @code{-gnatv} are useful to control the
14396 format of any generated error messages.
14398 When the source file is empty or contains only empty lines and/or comments,
14399 the output is a warning:
14401 @example
14402 $ gcc -c -gnats -x ada toto.txt
14403 toto.txt:1:01: warning: empty file, contains no compilation units
14405 @end example
14407 Otherwise, the output is simply the error messages, if any. No object file or
14408 ALI file is generated by a syntax-only compilation. Also, no units other
14409 than the one specified are accessed. For example, if a unit @code{X}
14410 `with's a unit @code{Y}, compiling unit @code{X} in syntax
14411 check only mode does not access the source file containing unit
14412 @code{Y}.
14414 @geindex Multiple units
14415 @geindex syntax checking
14417 Normally, GNAT allows only a single unit in a source file. However, this
14418 restriction does not apply in syntax-check-only mode, and it is possible
14419 to check a file containing multiple compilation units concatenated
14420 together. This is primarily used by the @code{gnatchop} utility
14421 (@ref{1d,,Renaming Files with gnatchop}).
14422 @end table
14424 @node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
14425 @anchor{gnat_ugn/building_executable_programs_with_gnat id21}@anchor{fa}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-semantic-checking}@anchor{fb}
14426 @subsection Using @code{gcc} for Semantic Checking
14429 @geindex -gnatc (gcc)
14432 @table @asis
14434 @item @code{-gnatc}
14436 The @code{c} stands for ‘check’.
14437 Causes the compiler to operate in semantic check mode,
14438 with full checking for all illegalities specified in the
14439 Ada Reference Manual, but without generation of any object code
14440 (no object file is generated).
14442 Because dependent files must be accessed, you must follow the GNAT
14443 semantic restrictions on file structuring to operate in this mode:
14446 @itemize *
14448 @item 
14449 The needed source files must be accessible
14450 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
14452 @item 
14453 Each file must contain only one compilation unit.
14455 @item 
14456 The file name and unit name must match (@ref{3b,,File Naming Rules}).
14457 @end itemize
14459 The output consists of error messages as appropriate. No object file is
14460 generated. An @code{ALI} file is generated for use in the context of
14461 cross-reference tools, but this file is marked as not being suitable
14462 for binding (since no object file is generated).
14463 The checking corresponds exactly to the notion of
14464 legality in the Ada Reference Manual.
14466 Any unit can be compiled in semantics-checking-only mode, including
14467 units that would not normally be compiled (subunits,
14468 and specifications where a separate body is present).
14469 @end table
14471 @node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
14472 @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{fc}
14473 @subsection Compiling Different Versions of Ada
14476 The switches described in this section allow you to explicitly specify
14477 the version of the Ada language that your programs are written in.
14478 The default mode is Ada 2012,
14479 but you can also specify Ada 95, Ada 2005 mode, or
14480 indicate Ada 83 compatibility mode.
14482 @geindex Compatibility with Ada 83
14484 @geindex -gnat83 (gcc)
14486 @geindex ACVC
14487 @geindex Ada 83 tests
14489 @geindex Ada 83 mode
14492 @table @asis
14494 @item @code{-gnat83} (Ada 83 Compatibility Mode)
14496 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
14497 specifies that the program is to be compiled in Ada 83 mode. With
14498 @code{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
14499 semantics where this can be done easily.
14500 It is not possible to guarantee this switch does a perfect
14501 job; some subtle tests, such as are
14502 found in earlier ACVC tests (and that have been removed from the ACATS suite
14503 for Ada 95), might not compile correctly.
14504 Nevertheless, this switch may be useful in some circumstances, for example
14505 where, due to contractual reasons, existing code needs to be maintained
14506 using only Ada 83 features.
14508 With few exceptions (most notably the need to use @code{<>} on
14509 unconstrained 
14510 @geindex Generic formal parameters
14511 generic formal parameters,
14512 the use of the new Ada 95 / Ada 2005
14513 reserved words, and the use of packages
14514 with optional bodies), it is not necessary to specify the
14515 @code{-gnat83} switch when compiling Ada 83 programs, because, with rare
14516 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
14517 a correct Ada 83 program is usually also a correct program
14518 in these later versions of the language standard. For further information
14519 please refer to the `Compatibility and Porting Guide' chapter in the
14520 @cite{GNAT Reference Manual}.
14521 @end table
14523 @geindex -gnat95 (gcc)
14525 @geindex Ada 95 mode
14528 @table @asis
14530 @item @code{-gnat95} (Ada 95 mode)
14532 This switch directs the compiler to implement the Ada 95 version of the
14533 language.
14534 Since Ada 95 is almost completely upwards
14535 compatible with Ada 83, Ada 83 programs may generally be compiled using
14536 this switch (see the description of the @code{-gnat83} switch for further
14537 information about Ada 83 mode).
14538 If an Ada 2005 program is compiled in Ada 95 mode,
14539 uses of the new Ada 2005 features will cause error
14540 messages or warnings.
14542 This switch also can be used to cancel the effect of a previous
14543 @code{-gnat83}, @code{-gnat05/2005}, or @code{-gnat12/2012}
14544 switch earlier in the command line.
14545 @end table
14547 @geindex -gnat05 (gcc)
14549 @geindex -gnat2005 (gcc)
14551 @geindex Ada 2005 mode
14554 @table @asis
14556 @item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
14558 This switch directs the compiler to implement the Ada 2005 version of the
14559 language, as documented in the official Ada standards document.
14560 Since Ada 2005 is almost completely upwards
14561 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
14562 may generally be compiled using this switch (see the description of the
14563 @code{-gnat83} and @code{-gnat95} switches for further
14564 information).
14565 @end table
14567 @geindex -gnat12 (gcc)
14569 @geindex -gnat2012 (gcc)
14571 @geindex Ada 2012 mode
14574 @table @asis
14576 @item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
14578 This switch directs the compiler to implement the Ada 2012 version of the
14579 language (also the default).
14580 Since Ada 2012 is almost completely upwards
14581 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
14582 Ada 83 and Ada 95 programs
14583 may generally be compiled using this switch (see the description of the
14584 @code{-gnat83}, @code{-gnat95}, and @code{-gnat05/2005} switches
14585 for further information).
14586 @end table
14588 @geindex -gnat2022 (gcc)
14590 @geindex Ada 2022 mode
14593 @table @asis
14595 @item @code{-gnat2022} (Ada 2022 mode)
14597 This switch directs the compiler to implement the Ada 2022 version of the
14598 language.
14599 @end table
14601 @geindex -gnatX0 (gcc)
14603 @geindex Ada language extensions
14605 @geindex GNAT extensions
14608 @table @asis
14610 @item @code{-gnatX0} (Enable GNAT Extensions)
14612 This switch directs the compiler to implement the latest version of the
14613 language (currently Ada 2022) and also to enable certain GNAT implementation
14614 extensions that are not part of any Ada standard. For a full list of these
14615 extensions, see the GNAT reference manual, @code{Pragma Extensions_Allowed}.
14616 @end table
14618 @geindex -gnatX (gcc)
14620 @geindex Ada language extensions
14622 @geindex GNAT extensions
14625 @table @asis
14627 @item @code{-gnatX} (Enable core GNAT Extensions)
14629 This switch is similar to -gnatX0 except that only some, not all, of the
14630 GNAT-defined language extensions are enabled. For a list of the
14631 extensions enabled by this switch, see the GNAT reference manual
14632 @code{Pragma Extensions_Allowed} and the description of that pragma’s
14633 “On” (as opposed to “All”) argument.
14634 @end table
14636 @node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14637 @anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{31}@anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{fd}
14638 @subsection Character Set Control
14641 @geindex -gnati (gcc)
14644 @table @asis
14646 @item @code{-gnati`c'}
14648 Normally GNAT recognizes the Latin-1 character set in source program
14649 identifiers, as described in the Ada Reference Manual.
14650 This switch causes
14651 GNAT to recognize alternate character sets in identifiers. @code{c} is a
14652 single character  indicating the character set, as follows:
14655 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14656 @item
14660 @tab
14662 ISO 8859-1 (Latin-1) identifiers
14664 @item
14668 @tab
14670 ISO 8859-2 (Latin-2) letters allowed in identifiers
14672 @item
14676 @tab
14678 ISO 8859-3 (Latin-3) letters allowed in identifiers
14680 @item
14684 @tab
14686 ISO 8859-4 (Latin-4) letters allowed in identifiers
14688 @item
14692 @tab
14694 ISO 8859-5 (Cyrillic) letters allowed in identifiers
14696 @item
14700 @tab
14702 ISO 8859-15 (Latin-9) letters allowed in identifiers
14704 @item
14708 @tab
14710 IBM PC letters (code page 437) allowed in identifiers
14712 @item
14716 @tab
14718 IBM PC letters (code page 850) allowed in identifiers
14720 @item
14724 @tab
14726 Full upper-half codes allowed in identifiers
14728 @item
14732 @tab
14734 No upper-half codes allowed in identifiers
14736 @item
14740 @tab
14742 Wide-character codes (that is, codes greater than 255)
14743 allowed in identifiers
14745 @end multitable
14748 See @ref{23,,Foreign Language Representation} for full details on the
14749 implementation of these character sets.
14750 @end table
14752 @geindex -gnatW (gcc)
14755 @table @asis
14757 @item @code{-gnatW`e'}
14759 Specify the method of encoding for wide characters.
14760 @code{e} is one of the following:
14763 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14764 @item
14768 @tab
14770 Hex encoding (brackets coding also recognized)
14772 @item
14776 @tab
14778 Upper half encoding (brackets encoding also recognized)
14780 @item
14784 @tab
14786 Shift/JIS encoding (brackets encoding also recognized)
14788 @item
14792 @tab
14794 EUC encoding (brackets encoding also recognized)
14796 @item
14800 @tab
14802 UTF-8 encoding (brackets encoding also recognized)
14804 @item
14808 @tab
14810 Brackets encoding only (default value)
14812 @end multitable
14815 For full details on these encoding
14816 methods see @ref{37,,Wide_Character Encodings}.
14817 Note that brackets coding is always accepted, even if one of the other
14818 options is specified, so for example @code{-gnatW8} specifies that both
14819 brackets and UTF-8 encodings will be recognized. The units that are
14820 with’ed directly or indirectly will be scanned using the specified
14821 representation scheme, and so if one of the non-brackets scheme is
14822 used, it must be used consistently throughout the program. However,
14823 since brackets encoding is always recognized, it may be conveniently
14824 used in standard libraries, allowing these libraries to be used with
14825 any of the available coding schemes.
14827 Note that brackets encoding only applies to program text. Within comments,
14828 brackets are considered to be normal graphic characters, and bracket sequences
14829 are never recognized as wide characters.
14831 If no @code{-gnatW?} parameter is present, then the default
14832 representation is normally Brackets encoding only. However, if the
14833 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14834 byte order mark or BOM for UTF-8), then these three characters are
14835 skipped and the default representation for the file is set to UTF-8.
14837 Note that the wide character representation that is specified (explicitly
14838 or by default) for the main program also acts as the default encoding used
14839 for Wide_Text_IO files if not specifically overridden by a WCEM form
14840 parameter.
14841 @end table
14843 When no @code{-gnatW?} is specified, then characters (other than wide
14844 characters represented using brackets notation) are treated as 8-bit
14845 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14846 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14847 characters in the range 16#00#..16#1F# are not accepted in program text
14848 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14849 in program text, but allowed and ignored in comments. Note in particular
14850 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14851 as an end of line in this default mode. If your source program contains
14852 instances of the NEL character used as a line terminator,
14853 you must use UTF-8 encoding for the whole
14854 source program. In default mode, all lines must be ended by a standard
14855 end of line sequence (CR, CR/LF, or LF).
14857 Note that the convention of simply accepting all upper half characters in
14858 comments means that programs that use standard ASCII for program text, but
14859 UTF-8 encoding for comments are accepted in default mode, providing that the
14860 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14861 This is a common mode for many programs with foreign language comments.
14863 @node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14864 @anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{fe}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{ff}
14865 @subsection File Naming Control
14868 @geindex -gnatk (gcc)
14871 @table @asis
14873 @item @code{-gnatk`n'}
14875 Activates file name ‘krunching’. @code{n}, a decimal integer in the range
14876 1-999, indicates the maximum allowable length of a file name (not
14877 including the @code{.ads} or @code{.adb} extension). The default is not
14878 to enable file name krunching.
14880 For the source file naming rules, @ref{3b,,File Naming Rules}.
14881 @end table
14883 @node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14884 @anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{100}@anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{101}
14885 @subsection Subprogram Inlining Control
14888 @geindex -gnatn (gcc)
14891 @table @asis
14893 @item @code{-gnatn[12]}
14895 The @code{n} here is intended to suggest the first syllable of the word ‘inline’.
14896 GNAT recognizes and processes @code{Inline} pragmas. However, for inlining to
14897 actually occur, optimization must be enabled and, by default, inlining of
14898 subprograms across units is not performed. If you want to additionally
14899 enable inlining of subprograms specified by pragma @code{Inline} across units,
14900 you must also specify this switch.
14902 In the absence of this switch, GNAT does not attempt inlining across units
14903 and does not access the bodies of subprograms for which @code{pragma Inline} is
14904 specified if they are not in the current unit.
14906 You can optionally specify the inlining level: 1 for moderate inlining across
14907 units, which is a good compromise between compilation times and performances
14908 at run time, or 2 for full inlining across units, which may bring about
14909 longer compilation times. If no inlining level is specified, the compiler will
14910 pick it based on the optimization level: 1 for @code{-O1}, @code{-O2} or
14911 @code{-Os} and 2 for @code{-O3}.
14913 If you specify this switch the compiler will access these bodies,
14914 creating an extra source dependency for the resulting object file, and
14915 where possible, the call will be inlined.
14916 For further details on when inlining is possible
14917 see @ref{102,,Inlining of Subprograms}.
14918 @end table
14920 @geindex -gnatN (gcc)
14923 @table @asis
14925 @item @code{-gnatN}
14927 This switch activates front-end inlining which also
14928 generates additional dependencies.
14930 When using a gcc-based back end, then the use of
14931 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
14932 Historically front end inlining was more extensive than the gcc back end
14933 inlining, but that is no longer the case.
14934 @end table
14936 @node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14937 @anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{103}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{104}
14938 @subsection Auxiliary Output Control
14941 @geindex -gnatu (gcc)
14944 @table @asis
14946 @item @code{-gnatu}
14948 Print a list of units required by this compilation on @code{stdout}.
14949 The listing includes all units on which the unit being compiled depends
14950 either directly or indirectly.
14951 @end table
14953 @geindex -pass-exit-codes (gcc)
14956 @table @asis
14958 @item @code{-pass-exit-codes}
14960 If this switch is not used, the exit code returned by @code{gcc} when
14961 compiling multiple files indicates whether all source files have
14962 been successfully used to generate object files or not.
14964 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
14965 exit status and allows an integrated development environment to better
14966 react to a compilation failure. Those exit status are:
14969 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14970 @item
14974 @tab
14976 There was an error in at least one source file.
14978 @item
14982 @tab
14984 At least one source file did not generate an object file.
14986 @item
14990 @tab
14992 The compiler died unexpectedly (internal error for example).
14994 @item
14998 @tab
15000 An object file has been generated for every source file.
15002 @end multitable
15004 @end table
15006 @node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
15007 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{105}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{106}
15008 @subsection Debugging Control
15011 @quotation
15013 @geindex Debugging options
15014 @end quotation
15016 @geindex -gnatd (gcc)
15019 @table @asis
15021 @item @code{-gnatd`x'}
15023 Activate internal debugging switches. @code{x} is a letter or digit, or
15024 string of letters or digits, which specifies the type of debugging
15025 outputs desired. Normally these are used only for internal development
15026 or system debugging purposes. You can find full documentation for these
15027 switches in the body of the @code{Debug} unit in the compiler source
15028 file @code{debug.adb}.
15029 @end table
15031 @geindex -gnatG (gcc)
15034 @table @asis
15036 @item @code{-gnatG[=`nn']}
15038 This switch causes the compiler to generate auxiliary output containing
15039 a pseudo-source listing of the generated expanded code. Like most Ada
15040 compilers, GNAT works by first transforming the high level Ada code into
15041 lower level constructs. For example, tasking operations are transformed
15042 into calls to the tasking run-time routines. A unique capability of GNAT
15043 is to list this expanded code in a form very close to normal Ada source.
15044 This is very useful in understanding the implications of various Ada
15045 usage on the efficiency of the generated code. There are many cases in
15046 Ada (e.g., the use of controlled types), where simple Ada statements can
15047 generate a lot of run-time code. By using @code{-gnatG} you can identify
15048 these cases, and consider whether it may be desirable to modify the coding
15049 approach to improve efficiency.
15051 The optional parameter @code{nn} if present after -gnatG specifies an
15052 alternative maximum line length that overrides the normal default of 72.
15053 This value is in the range 40-999999, values less than 40 being silently
15054 reset to 40. The equal sign is optional.
15056 The format of the output is very similar to standard Ada source, and is
15057 easily understood by an Ada programmer. The following special syntactic
15058 additions correspond to low level features used in the generated code that
15059 do not have any exact analogies in pure Ada source form. The following
15060 is a partial list of these special constructions. See the spec
15061 of package @code{Sprint} in file @code{sprint.ads} for a full list.
15063 @geindex -gnatL (gcc)
15065 If the switch @code{-gnatL} is used in conjunction with
15066 @code{-gnatG}, then the original source lines are interspersed
15067 in the expanded source (as comment lines with the original line number).
15070 @table @asis
15072 @item @code{new @var{xxx} [storage_pool = @var{yyy}]}
15074 Shows the storage pool being used for an allocator.
15076 @item @code{at end @var{procedure-name};}
15078 Shows the finalization (cleanup) procedure for a scope.
15080 @item @code{(if @var{expr} then @var{expr} else @var{expr})}
15082 Conditional expression equivalent to the @code{x?y:z} construction in C.
15084 @item @code{@var{target}^(@var{source})}
15086 A conversion with floating-point truncation instead of rounding.
15088 @item @code{@var{target}?(@var{source})}
15090 A conversion that bypasses normal Ada semantic checking. In particular
15091 enumeration types and fixed-point types are treated simply as integers.
15093 @item @code{@var{target}?^(@var{source})}
15095 Combines the above two cases.
15096 @end table
15098 @code{@var{x} #/ @var{y}}
15100 @code{@var{x} #mod @var{y}}
15102 @code{@var{x} # @var{y}}
15105 @table @asis
15107 @item @code{@var{x} #rem @var{y}}
15109 A division or multiplication of fixed-point values which are treated as
15110 integers without any kind of scaling.
15112 @item @code{free @var{expr} [storage_pool = @var{xxx}]}
15114 Shows the storage pool associated with a @code{free} statement.
15116 @item @code{[subtype or type declaration]}
15118 Used to list an equivalent declaration for an internally generated
15119 type that is referenced elsewhere in the listing.
15121 @item @code{freeze @var{type-name} [@var{actions}]}
15123 Shows the point at which @code{type-name} is frozen, with possible
15124 associated actions to be performed at the freeze point.
15126 @item @code{reference @var{itype}}
15128 Reference (and hence definition) to internal type @code{itype}.
15130 @item @code{@var{function-name}! (@var{arg}, @var{arg}, @var{arg})}
15132 Intrinsic function call.
15134 @item @code{@var{label-name} : label}
15136 Declaration of label @code{labelname}.
15138 @item @code{#$ @var{subprogram-name}}
15140 An implicit call to a run-time support routine
15141 (to meet the requirement of H.3.1(9) in a
15142 convenient manner).
15144 @item @code{@var{expr} && @var{expr} && @var{expr} ... && @var{expr}}
15146 A multiple concatenation (same effect as @code{expr} & @code{expr} &
15147 @code{expr}, but handled more efficiently).
15149 @item @code{[constraint_error]}
15151 Raise the @code{Constraint_Error} exception.
15153 @item @code{@var{expression}'reference}
15155 A pointer to the result of evaluating @{expression@}.
15157 @item @code{@var{target-type}!(@var{source-expression})}
15159 An unchecked conversion of @code{source-expression} to @code{target-type}.
15161 @item @code{[@var{numerator}/@var{denominator}]}
15163 Used to represent internal real literals (that) have no exact
15164 representation in base 2-16 (for example, the result of compile time
15165 evaluation of the expression 1.0/27.0).
15166 @end table
15167 @end table
15169 @geindex -gnatD (gcc)
15172 @table @asis
15174 @item @code{-gnatD[=nn]}
15176 When used in conjunction with @code{-gnatG}, this switch causes
15177 the expanded source, as described above for
15178 @code{-gnatG} to be written to files with names
15179 @code{xxx.dg}, where @code{xxx} is the normal file name,
15180 instead of to the standard output file. For
15181 example, if the source file name is @code{hello.adb}, then a file
15182 @code{hello.adb.dg} will be written.  The debugging
15183 information generated by the @code{gcc} @code{-g} switch
15184 will refer to the generated @code{xxx.dg} file. This allows
15185 you to do source level debugging using the generated code which is
15186 sometimes useful for complex code, for example to find out exactly
15187 which part of a complex construction raised an exception. This switch
15188 also suppresses generation of cross-reference information (see
15189 @code{-gnatx}) since otherwise the cross-reference information
15190 would refer to the @code{.dg} file, which would cause
15191 confusion since this is not the original source file.
15193 Note that @code{-gnatD} actually implies @code{-gnatG}
15194 automatically, so it is not necessary to give both options.
15195 In other words @code{-gnatD} is equivalent to @code{-gnatDG}).
15197 @geindex -gnatL (gcc)
15199 If the switch @code{-gnatL} is used in conjunction with
15200 @code{-gnatDG}, then the original source lines are interspersed
15201 in the expanded source (as comment lines with the original line number).
15203 The optional parameter @code{nn} if present after -gnatD specifies an
15204 alternative maximum line length that overrides the normal default of 72.
15205 This value is in the range 40-999999, values less than 40 being silently
15206 reset to 40. The equal sign is optional.
15207 @end table
15209 @geindex -gnatr (gcc)
15211 @geindex pragma Restrictions
15214 @table @asis
15216 @item @code{-gnatr}
15218 This switch causes pragma Restrictions to be treated as Restriction_Warnings
15219 so that violation of restrictions causes warnings rather than illegalities.
15220 This is useful during the development process when new restrictions are added
15221 or investigated. The switch also causes pragma Profile to be treated as
15222 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
15223 restriction warnings rather than restrictions.
15224 @end table
15226 @geindex -gnatR (gcc)
15229 @table @asis
15231 @item @code{-gnatR[0|1|2|3|4][e][j][m][s]}
15233 This switch controls output from the compiler of a listing showing
15234 representation information for declared types, objects and subprograms.
15235 For @code{-gnatR0}, no information is output (equivalent to omitting
15236 the @code{-gnatR} switch). For @code{-gnatR1} (which is the default,
15237 so @code{-gnatR} with no parameter has the same effect), size and
15238 alignment information is listed for declared array and record types.
15240 For @code{-gnatR2}, size and alignment information is listed for all
15241 declared types and objects. The @code{Linker_Section} is also listed for any
15242 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
15243 latter case occurs for objects of a type for which a @code{Linker_Section}
15244 is set).
15246 For @code{-gnatR3}, symbolic expressions for values that are computed
15247 at run time for records are included. These symbolic expressions have
15248 a mostly obvious format with #n being used to represent the value of the
15249 n’th discriminant. See source files @code{repinfo.ads/adb} in the
15250 GNAT sources for full details on the format of @code{-gnatR3} output.
15252 For @code{-gnatR4}, information for relevant compiler-generated types
15253 is also listed, i.e. when they are structurally part of other declared
15254 types and objects.
15256 If the switch is followed by an @code{e} (e.g. @code{-gnatR2e}), then
15257 extended representation information for record sub-components of records
15258 is included.
15260 If the switch is followed by an @code{m} (e.g. @code{-gnatRm}), then
15261 subprogram conventions and parameter passing mechanisms for all the
15262 subprograms are included.
15264 If the switch is followed by a @code{j} (e.g., @code{-gnatRj}), then
15265 the output is in the JSON data interchange format specified by the
15266 ECMA-404 standard. The semantic description of this JSON output is
15267 available in the specification of the Repinfo unit present in the
15268 compiler sources.
15270 If the switch is followed by an @code{s} (e.g., @code{-gnatR3s}), then
15271 the output is to a file with the name @code{file.rep} where @code{file} is
15272 the name of the corresponding source file, except if @code{j} is also
15273 specified, in which case the file name is @code{file.json}.
15275 Note that it is possible for record components to have zero size. In
15276 this case, the component clause uses an obvious extension of permitted
15277 Ada syntax, for example @code{at 0 range 0 .. -1}.
15278 @end table
15280 @geindex -gnatS (gcc)
15283 @table @asis
15285 @item @code{-gnatS}
15287 The use of the switch @code{-gnatS} for an
15288 Ada compilation will cause the compiler to output a
15289 representation of package Standard in a form very
15290 close to standard Ada. It is not quite possible to
15291 do this entirely in standard Ada (since new
15292 numeric base types cannot be created in standard
15293 Ada), but the output is easily
15294 readable to any Ada programmer, and is useful to
15295 determine the characteristics of target dependent
15296 types in package Standard.
15297 @end table
15299 @geindex -gnatx (gcc)
15302 @table @asis
15304 @item @code{-gnatx}
15306 Normally the compiler generates full cross-referencing information in
15307 the @code{ALI} file. This information is used by a number of tools.
15308 The @code{-gnatx} switch suppresses this information. This saves some space
15309 and may slightly speed up compilation, but means that tools depending
15310 on this information cannot be used.
15311 @end table
15313 @geindex -fgnat-encodings (gcc)
15316 @table @asis
15318 @item @code{-fgnat-encodings=[all|gdb|minimal]}
15320 This switch controls the balance between GNAT encodings and standard DWARF
15321 emitted in the debug information.
15323 Historically, old debug formats like stabs were not powerful enough to
15324 express some Ada types (for instance, variant records or fixed-point types).
15325 To work around this, GNAT introduced proprietary encodings that embed the
15326 missing information (“GNAT encodings”).
15328 Recent versions of the DWARF debug information format are now able to
15329 correctly describe most of these Ada constructs (“standard DWARF”). As
15330 third-party tools started to use this format, GNAT has been enhanced to
15331 generate it. However, most tools (including GDB) are still relying on GNAT
15332 encodings.
15334 To support all tools, GNAT needs to be versatile about the balance between
15335 generation of GNAT encodings and standard DWARF. This is what
15336 @code{-fgnat-encodings} is about.
15339 @itemize *
15341 @item 
15342 @code{=all}: Emit all GNAT encodings, and then emit as much standard DWARF as
15343 possible so it does not conflict with GNAT encodings.
15345 @item 
15346 @code{=gdb}: Emit as much standard DWARF as possible as long as the current
15347 GDB handles it. Emit GNAT encodings for the rest.
15349 @item 
15350 @code{=minimal}: Emit as much standard DWARF as possible and emit GNAT
15351 encodings for the rest.
15352 @end itemize
15353 @end table
15355 @node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
15356 @anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{107}@anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{108}
15357 @subsection Exception Handling Control
15360 GNAT uses two methods for handling exceptions at run time. The
15361 @code{setjmp/longjmp} method saves the context when entering
15362 a frame with an exception handler. Then when an exception is
15363 raised, the context can be restored immediately, without the
15364 need for tracing stack frames. This method provides very fast
15365 exception propagation, but introduces significant overhead for
15366 the use of exception handlers, even if no exception is raised.
15368 The other approach is called ‘zero cost’ exception handling.
15369 With this method, the compiler builds static tables to describe
15370 the exception ranges. No dynamic code is required when entering
15371 a frame containing an exception handler. When an exception is
15372 raised, the tables are used to control a back trace of the
15373 subprogram invocation stack to locate the required exception
15374 handler. This method has considerably poorer performance for
15375 the propagation of exceptions, but there is no overhead for
15376 exception handlers if no exception is raised. Note that in this
15377 mode and in the context of mixed Ada and C/C++ programming,
15378 to propagate an exception through a C/C++ code, the C/C++ code
15379 must be compiled with the @code{-funwind-tables} GCC’s
15380 option.
15382 The following switches may be used to control which of the
15383 two exception handling methods is used.
15385 @geindex --RTS=sjlj (gnatmake)
15388 @table @asis
15390 @item @code{--RTS=sjlj}
15392 This switch causes the setjmp/longjmp run-time (when available) to be used
15393 for exception handling. If the default
15394 mechanism for the target is zero cost exceptions, then
15395 this switch can be used to modify this default, and must be
15396 used for all units in the partition.
15397 This option is rarely used. One case in which it may be
15398 advantageous is if you have an application where exception
15399 raising is common and the overall performance of the
15400 application is improved by favoring exception propagation.
15401 @end table
15403 @geindex --RTS=zcx (gnatmake)
15405 @geindex Zero Cost Exceptions
15408 @table @asis
15410 @item @code{--RTS=zcx}
15412 This switch causes the zero cost approach to be used
15413 for exception handling. If this is the default mechanism for the
15414 target (see below), then this switch is unneeded. If the default
15415 mechanism for the target is setjmp/longjmp exceptions, then
15416 this switch can be used to modify this default, and must be
15417 used for all units in the partition.
15418 This option can only be used if the zero cost approach
15419 is available for the target in use, otherwise it will generate an error.
15420 @end table
15422 The same option @code{--RTS} must be used both for @code{gcc}
15423 and @code{gnatbind}. Passing this option to @code{gnatmake}
15424 (@ref{d0,,Switches for gnatmake}) will ensure the required consistency
15425 through the compilation and binding steps.
15427 @node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
15428 @anchor{gnat_ugn/building_executable_programs_with_gnat id29}@anchor{109}@anchor{gnat_ugn/building_executable_programs_with_gnat units-to-sources-mapping-files}@anchor{ea}
15429 @subsection Units to Sources Mapping Files
15432 @geindex -gnatem (gcc)
15435 @table @asis
15437 @item @code{-gnatem=`path'}
15439 A mapping file is a way to communicate to the compiler two mappings:
15440 from unit names to file names (without any directory information) and from
15441 file names to path names (with full directory information). These mappings
15442 are used by the compiler to short-circuit the path search.
15444 The use of mapping files is not required for correct operation of the
15445 compiler, but mapping files can improve efficiency, particularly when
15446 sources are read over a slow network connection. In normal operation,
15447 you need not be concerned with the format or use of mapping files,
15448 and the @code{-gnatem} switch is not a switch that you would use
15449 explicitly. It is intended primarily for use by automatic tools such as
15450 @code{gnatmake} running under the project file facility. The
15451 description here of the format of mapping files is provided
15452 for completeness and for possible use by other tools.
15454 A mapping file is a sequence of sets of three lines. In each set, the
15455 first line is the unit name, in lower case, with @code{%s} appended
15456 for specs and @code{%b} appended for bodies; the second line is the
15457 file name; and the third line is the path name.
15459 Example:
15461 @example
15462 main%b
15463 main.2.ada
15464 /gnat/project1/sources/main.2.ada
15465 @end example
15467 When the switch @code{-gnatem} is specified, the compiler will
15468 create in memory the two mappings from the specified file. If there is
15469 any problem (nonexistent file, truncated file or duplicate entries),
15470 no mapping will be created.
15472 Several @code{-gnatem} switches may be specified; however, only the
15473 last one on the command line will be taken into account.
15475 When using a project file, @code{gnatmake} creates a temporary
15476 mapping file and communicates it to the compiler using this switch.
15477 @end table
15479 @node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
15480 @anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{10a}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{10b}
15481 @subsection Code Generation Control
15484 The GCC technology provides a wide range of target dependent
15485 @code{-m} switches for controlling
15486 details of code generation with respect to different versions of
15487 architectures. This includes variations in instruction sets (e.g.,
15488 different members of the power pc family), and different requirements
15489 for optimal arrangement of instructions (e.g., different members of
15490 the x86 family). The list of available @code{-m} switches may be
15491 found in the GCC documentation.
15493 Use of these @code{-m} switches may in some cases result in improved
15494 code performance.
15496 The GNAT technology is tested and qualified without any
15497 @code{-m} switches,
15498 so generally the most reliable approach is to avoid the use of these
15499 switches. However, we generally expect most of these switches to work
15500 successfully with GNAT, and many customers have reported successful
15501 use of these options.
15503 Our general advice is to avoid the use of @code{-m} switches unless
15504 special needs lead to requirements in this area. In particular,
15505 there is no point in using @code{-m} switches to improve performance
15506 unless you actually see a performance improvement.
15508 @node Linker Switches,Binding with gnatbind,Compiler Switches,Building Executable Programs with GNAT
15509 @anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{10c}@anchor{gnat_ugn/building_executable_programs_with_gnat linker-switches}@anchor{10d}
15510 @section Linker Switches
15513 Linker switches can be specified after @code{-largs} builder switch.
15515 @geindex -fuse-ld=name
15518 @table @asis
15520 @item @code{-fuse-ld=`name'}
15522 Linker to be used. The default is @code{bfd} for @code{ld.bfd}; @code{gold}
15523 (for @code{ld.gold}) and @code{mold} (for @code{ld.mold}) are more
15524 recent and faster alternatives, but only available on GNU/Linux
15525 platforms.
15526 @end table
15528 @node Binding with gnatbind,Linking with gnatlink,Linker Switches,Building Executable Programs with GNAT
15529 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{ca}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{10e}
15530 @section Binding with @code{gnatbind}
15533 @geindex gnatbind
15535 This chapter describes the GNAT binder, @code{gnatbind}, which is used
15536 to bind compiled GNAT objects.
15538 The @code{gnatbind} program performs four separate functions:
15541 @itemize *
15543 @item 
15544 Checks that a program is consistent, in accordance with the rules in
15545 Chapter 10 of the Ada Reference Manual. In particular, error
15546 messages are generated if a program uses inconsistent versions of a
15547 given unit.
15549 @item 
15550 Checks that an acceptable order of elaboration exists for the program
15551 and issues an error message if it cannot find an order of elaboration
15552 that satisfies the rules in Chapter 10 of the Ada Language Manual.
15554 @item 
15555 Generates a main program incorporating the given elaboration order.
15556 This program is a small Ada package (body and spec) that
15557 must be subsequently compiled
15558 using the GNAT compiler. The necessary compilation step is usually
15559 performed automatically by @code{gnatlink}. The two most important
15560 functions of this program
15561 are to call the elaboration routines of units in an appropriate order
15562 and to call the main program.
15564 @item 
15565 Determines the set of object files required by the given main program.
15566 This information is output in the forms of comments in the generated program,
15567 to be read by the @code{gnatlink} utility used to link the Ada application.
15568 @end itemize
15570 @menu
15571 * Running gnatbind:: 
15572 * Switches for gnatbind:: 
15573 * Command-Line Access:: 
15574 * Search Paths for gnatbind:: 
15575 * Examples of gnatbind Usage:: 
15577 @end menu
15579 @node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
15580 @anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{10f}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{110}
15581 @subsection Running @code{gnatbind}
15584 The form of the @code{gnatbind} command is
15586 @example
15587 $ gnatbind [ switches ] mainprog[.ali] [ switches ]
15588 @end example
15590 where @code{mainprog.adb} is the Ada file containing the main program
15591 unit body. @code{gnatbind} constructs an Ada
15592 package in two files whose names are
15593 @code{b~mainprog.ads}, and @code{b~mainprog.adb}.
15594 For example, if given the
15595 parameter @code{hello.ali}, for a main program contained in file
15596 @code{hello.adb}, the binder output files would be @code{b~hello.ads}
15597 and @code{b~hello.adb}.
15599 When doing consistency checking, the binder takes into consideration
15600 any source files it can locate. For example, if the binder determines
15601 that the given main program requires the package @code{Pack}, whose
15602 @code{.ALI}
15603 file is @code{pack.ali} and whose corresponding source spec file is
15604 @code{pack.ads}, it attempts to locate the source file @code{pack.ads}
15605 (using the same search path conventions as previously described for the
15606 @code{gcc} command). If it can locate this source file, it checks that
15607 the time stamps
15608 or source checksums of the source and its references to in @code{ALI} files
15609 match. In other words, any @code{ALI} files that mentions this spec must have
15610 resulted from compiling this version of the source file (or in the case
15611 where the source checksums match, a version close enough that the
15612 difference does not matter).
15614 @geindex Source files
15615 @geindex use by binder
15617 The effect of this consistency checking, which includes source files, is
15618 that the binder ensures that the program is consistent with the latest
15619 version of the source files that can be located at bind time. Editing a
15620 source file without compiling files that depend on the source file cause
15621 error messages to be generated by the binder.
15623 For example, suppose you have a main program @code{hello.adb} and a
15624 package @code{P}, from file @code{p.ads} and you perform the following
15625 steps:
15628 @itemize *
15630 @item 
15631 Enter @code{gcc -c hello.adb} to compile the main program.
15633 @item 
15634 Enter @code{gcc -c p.ads} to compile package @code{P}.
15636 @item 
15637 Edit file @code{p.ads}.
15639 @item 
15640 Enter @code{gnatbind hello}.
15641 @end itemize
15643 At this point, the file @code{p.ali} contains an out-of-date time stamp
15644 because the file @code{p.ads} has been edited. The attempt at binding
15645 fails, and the binder generates the following error messages:
15647 @example
15648 error: "hello.adb" must be recompiled ("p.ads" has been modified)
15649 error: "p.ads" has been modified and must be recompiled
15650 @end example
15652 Now both files must be recompiled as indicated, and then the bind can
15653 succeed, generating a main program. You need not normally be concerned
15654 with the contents of this file, but for reference purposes a sample
15655 binder output file is given in @ref{e,,Example of Binder Output File}.
15657 In most normal usage, the default mode of @code{gnatbind} which is to
15658 generate the main package in Ada, as described in the previous section.
15659 In particular, this means that any Ada programmer can read and understand
15660 the generated main program. It can also be debugged just like any other
15661 Ada code provided the @code{-g} switch is used for
15662 @code{gnatbind} and @code{gnatlink}.
15664 @node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
15665 @anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{111}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{112}
15666 @subsection Switches for @code{gnatbind}
15669 The following switches are available with @code{gnatbind}; details will
15670 be presented in subsequent sections.
15672 @geindex --version (gnatbind)
15675 @table @asis
15677 @item @code{--version}
15679 Display Copyright and version, then exit disregarding all other options.
15680 @end table
15682 @geindex --help (gnatbind)
15685 @table @asis
15687 @item @code{--help}
15689 If @code{--version} was not used, display usage, then exit disregarding
15690 all other options.
15691 @end table
15693 @geindex -a (gnatbind)
15696 @table @asis
15698 @item @code{-a}
15700 Indicates that, if supported by the platform, the adainit procedure should
15701 be treated as an initialisation routine by the linker (a constructor). This
15702 is intended to be used by the Project Manager to automatically initialize
15703 shared Stand-Alone Libraries.
15704 @end table
15706 @geindex -aO (gnatbind)
15709 @table @asis
15711 @item @code{-aO}
15713 Specify directory to be searched for ALI files.
15714 @end table
15716 @geindex -aI (gnatbind)
15719 @table @asis
15721 @item @code{-aI}
15723 Specify directory to be searched for source file.
15724 @end table
15726 @geindex -A (gnatbind)
15729 @table @asis
15731 @item @code{-A[=`filename']}
15733 Output ALI list (to standard output or to the named file).
15734 @end table
15736 @geindex -b (gnatbind)
15739 @table @asis
15741 @item @code{-b}
15743 Generate brief messages to @code{stderr} even if verbose mode set.
15744 @end table
15746 @geindex -c (gnatbind)
15749 @table @asis
15751 @item @code{-c}
15753 Check only, no generation of binder output file.
15754 @end table
15756 @geindex -dnn[k|m] (gnatbind)
15759 @table @asis
15761 @item @code{-d`nn'[k|m]}
15763 This switch can be used to change the default task stack size value
15764 to a specified size @code{nn}, which is expressed in bytes by default, or
15765 in kilobytes when suffixed with @code{k} or in megabytes when suffixed
15766 with @code{m}.
15767 In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15768 in effect, to completing all task specs with
15770 @example
15771 pragma Storage_Size (nn);
15772 @end example
15774 When they do not already have such a pragma.
15775 @end table
15777 @geindex -D (gnatbind)
15780 @table @asis
15782 @item @code{-D`nn'[k|m]}
15784 Set the default secondary stack size to @code{nn}. The suffix indicates whether
15785 the size is in bytes (no suffix), kilobytes (@code{k} suffix) or megabytes
15786 (@code{m} suffix).
15788 The secondary stack holds objects of unconstrained types that are returned by
15789 functions, for example unconstrained Strings. The size of the secondary stack
15790 can be dynamic or fixed depending on the target.
15792 For most targets, the secondary stack grows on demand and is implemented as
15793 a chain of blocks in the heap. In this case, the default secondary stack size
15794 determines the initial size of the secondary stack for each task and the
15795 smallest amount the secondary stack can grow by.
15797 For Light, Light-Tasking, and Embedded run-times the size of the secondary
15798 stack is fixed. This switch can be used to change the default size of these
15799 stacks. The default secondary stack size can be overridden on a per-task
15800 basis if individual tasks have different secondary stack requirements. This
15801 is achieved through the Secondary_Stack_Size aspect, which takes the size of
15802 the secondary stack in bytes.
15803 @end table
15805 @geindex -e (gnatbind)
15808 @table @asis
15810 @item @code{-e}
15812 Output complete list of elaboration-order dependencies.
15813 @end table
15815 @geindex -Ea (gnatbind)
15818 @table @asis
15820 @item @code{-Ea}
15822 Store tracebacks in exception occurrences when the target supports it.
15823 The “a” is for “address”; tracebacks will contain hexadecimal addresses,
15824 unless symbolic tracebacks are enabled.
15826 See also the packages @code{GNAT.Traceback} and
15827 @code{GNAT.Traceback.Symbolic} for more information.
15828 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
15829 @code{gcc} option.
15830 @end table
15832 @geindex -Es (gnatbind)
15835 @table @asis
15837 @item @code{-Es}
15839 Store tracebacks in exception occurrences when the target supports it.
15840 The “s” is for “symbolic”; symbolic tracebacks are enabled.
15841 @end table
15843 @geindex -E (gnatbind)
15846 @table @asis
15848 @item @code{-E}
15850 Currently the same as @code{-Ea}.
15851 @end table
15853 @geindex -f (gnatbind)
15856 @table @asis
15858 @item @code{-f`elab-order'}
15860 Force elaboration order. For further details see @ref{113,,Elaboration Control}
15861 and @ref{f,,Elaboration Order Handling in GNAT}.
15862 @end table
15864 @geindex -F (gnatbind)
15867 @table @asis
15869 @item @code{-F}
15871 Force the checks of elaboration flags. @code{gnatbind} does not normally
15872 generate checks of elaboration flags for the main executable, except when
15873 a Stand-Alone Library is used. However, there are cases when this cannot be
15874 detected by gnatbind. An example is importing an interface of a Stand-Alone
15875 Library through a pragma Import and only specifying through a linker switch
15876 this Stand-Alone Library. This switch is used to guarantee that elaboration
15877 flag checks are generated.
15878 @end table
15880 @geindex -h (gnatbind)
15883 @table @asis
15885 @item @code{-h}
15887 Output usage (help) information.
15888 @end table
15890 @geindex -H (gnatbind)
15893 @table @asis
15895 @item @code{-H}
15897 Legacy elaboration order model enabled. For further details see
15898 @ref{f,,Elaboration Order Handling in GNAT}.
15899 @end table
15901 @geindex -H32 (gnatbind)
15904 @table @asis
15906 @item @code{-H32}
15908 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
15909 For further details see @ref{114,,Dynamic Allocation Control}.
15910 @end table
15912 @geindex -H64 (gnatbind)
15914 @geindex __gnat_malloc
15917 @table @asis
15919 @item @code{-H64}
15921 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
15922 For further details see @ref{114,,Dynamic Allocation Control}.
15924 @geindex -I (gnatbind)
15926 @item @code{-I}
15928 Specify directory to be searched for source and ALI files.
15930 @geindex -I- (gnatbind)
15932 @item @code{-I-}
15934 Do not look for sources in the current directory where @code{gnatbind} was
15935 invoked, and do not look for ALI files in the directory containing the
15936 ALI file named in the @code{gnatbind} command line.
15938 @geindex -k (gnatbind)
15940 @item @code{-k}
15942 Disable checking of elaboration flags. When using @code{-n}
15943 either explicitly or implicitly, @code{-F} is also implied,
15944 unless @code{-k} is used. This switch should be used with care
15945 and you should ensure manually that elaboration routines are not called
15946 twice unintentionally.
15948 @geindex -K (gnatbind)
15950 @item @code{-K}
15952 Give list of linker options specified for link.
15954 @geindex -l (gnatbind)
15956 @item @code{-l}
15958 Output chosen elaboration order.
15960 @geindex -L (gnatbind)
15962 @item @code{-L`xxx'}
15964 Bind the units for library building. In this case the @code{adainit} and
15965 @code{adafinal} procedures (@ref{7e,,Binding with Non-Ada Main Programs})
15966 are renamed to @code{@var{xxx}init} and
15967 @code{@var{xxx}final}.
15968 Implies -n.
15969 (@ref{2a,,GNAT and Libraries}, for more details.)
15971 @geindex -M (gnatbind)
15973 @item @code{-M`xyz'}
15975 Rename generated main program from main to xyz. This option is
15976 supported on cross environments only.
15978 @geindex -m (gnatbind)
15980 @item @code{-m`n'}
15982 Limit number of detected errors or warnings to @code{n}, where @code{n} is
15983 in the range 1..999999. The default value if no switch is
15984 given is 9999. If the number of warnings reaches this limit, then a
15985 message is output and further warnings are suppressed, the bind
15986 continues in this case. If the number of errors reaches this
15987 limit, then a message is output and the bind is abandoned.
15988 A value of zero means that no limit is enforced. The equal
15989 sign is optional.
15991 @geindex -minimal (gnatbind)
15993 @item @code{-minimal}
15995 Generate a binder file suitable for space-constrained applications. When
15996 active, binder-generated objects not required for program operation are no
15997 longer generated. `Warning:' this option comes with the following
15998 limitations:
16001 @itemize *
16003 @item 
16004 Starting the program’s execution in the debugger will cause it to
16005 stop at the start of the @code{main} function instead of the main subprogram.
16006 This can be worked around by manually inserting a breakpoint on that
16007 subprogram and resuming the program’s execution until reaching that breakpoint.
16009 @item 
16010 Programs using GNAT.Compiler_Version will not link.
16011 @end itemize
16013 @geindex -n (gnatbind)
16015 @item @code{-n}
16017 No main program.
16019 @geindex -nostdinc (gnatbind)
16021 @item @code{-nostdinc}
16023 Do not look for sources in the system default directory.
16025 @geindex -nostdlib (gnatbind)
16027 @item @code{-nostdlib}
16029 Do not look for library files in the system default directory.
16031 @geindex --RTS (gnatbind)
16033 @item @code{--RTS=`rts-path'}
16035 Specifies the default location of the run-time library. Same meaning as the
16036 equivalent @code{gnatmake} flag (@ref{d0,,Switches for gnatmake}).
16038 @geindex -o (gnatbind)
16040 @item @code{-o `file'}
16042 Name the output file @code{file} (default is @code{b~`xxx}.adb`).
16043 Note that if this option is used, then linking must be done manually,
16044 gnatlink cannot be used.
16046 @geindex -O (gnatbind)
16048 @item @code{-O[=`filename']}
16050 Output object list (to standard output or to the named file).
16052 @geindex -p (gnatbind)
16054 @item @code{-p}
16056 Pessimistic (worst-case) elaboration order.
16058 @geindex -P (gnatbind)
16060 @item @code{-P}
16062 Generate binder file suitable for CodePeer.
16063 @end table
16065 @geindex -Q (gnatbind)
16068 @table @asis
16070 @item @code{-Q`nnn'}
16072 Generate @code{nnn} additional default-sized secondary stacks.
16074 Tasks declared at the library level that use default-size secondary stacks
16075 have their secondary stacks allocated from a pool of stacks generated by
16076 gnatbind. This allows the default secondary stack size to be quickly changed
16077 by rebinding the application.
16079 While the binder sizes this pool to match the number of such tasks defined in
16080 the application, the pool size may need to be increased with the @code{-Q}
16081 switch to accommodate foreign threads registered with the Light run-time. For
16082 more information, please see the `The Primary and Secondary Stack' chapter in
16083 the `GNAT User’s Guide Supplement for Cross Platforms'.
16085 @geindex -R (gnatbind)
16087 @item @code{-R}
16089 Output closure source list, which includes all non-run-time units that are
16090 included in the bind.
16092 @geindex -Ra (gnatbind)
16094 @item @code{-Ra}
16096 Like @code{-R} but the list includes run-time units.
16098 @geindex -s (gnatbind)
16100 @item @code{-s}
16102 Require all source files to be present.
16104 @geindex -S (gnatbind)
16106 @item @code{-S`xxx'}
16108 Specifies the value to be used when detecting uninitialized scalar
16109 objects with pragma Initialize_Scalars.
16110 The @code{xxx} string specified with the switch is one of:
16113 @itemize *
16115 @item 
16116 @code{in} for an invalid value.
16118 If zero is invalid for the discrete type in question,
16119 then the scalar value is set to all zero bits.
16120 For signed discrete types, the largest possible negative value of
16121 the underlying scalar is set (i.e. a one bit followed by all zero bits).
16122 For unsigned discrete types, the underlying scalar value is set to all
16123 one bits. For floating-point types, a NaN value is set
16124 (see body of package System.Scalar_Values for exact values).
16126 @item 
16127 @code{lo} for low value.
16129 If zero is invalid for the discrete type in question,
16130 then the scalar value is set to all zero bits.
16131 For signed discrete types, the largest possible negative value of
16132 the underlying scalar is set (i.e. a one bit followed by all zero bits).
16133 For unsigned discrete types, the underlying scalar value is set to all
16134 zero bits. For floating-point, a small value is set
16135 (see body of package System.Scalar_Values for exact values).
16137 @item 
16138 @code{hi} for high value.
16140 If zero is invalid for the discrete type in question,
16141 then the scalar value is set to all one bits.
16142 For signed discrete types, the largest possible positive value of
16143 the underlying scalar is set (i.e. a zero bit followed by all one bits).
16144 For unsigned discrete types, the underlying scalar value is set to all
16145 one bits. For floating-point, a large value is set
16146 (see body of package System.Scalar_Values for exact values).
16148 @item 
16149 @code{xx} for hex value (two hex digits).
16151 The underlying scalar is set to a value consisting of repeated bytes, whose
16152 value corresponds to the given value. For example if @code{BF} is given,
16153 then a 32-bit scalar value will be set to the bit pattern @code{16#BFBFBFBF#}.
16154 @end itemize
16156 @geindex GNAT_INIT_SCALARS
16158 In addition, you can specify @code{-Sev} to indicate that the value is
16159 to be set at run time. In this case, the program will look for an environment
16160 variable of the form @code{GNAT_INIT_SCALARS=@var{yy}}, where @code{yy} is one
16161 of @code{in/lo/hi/@var{xx}} with the same meanings as above.
16162 If no environment variable is found, or if it does not have a valid value,
16163 then the default is @code{in} (invalid values).
16164 @end table
16166 @geindex -static (gnatbind)
16169 @table @asis
16171 @item @code{-static}
16173 Link against a static GNAT run-time.
16175 @geindex -shared (gnatbind)
16177 @item @code{-shared}
16179 Link against a shared GNAT run-time when available.
16181 @geindex -t (gnatbind)
16183 @item @code{-t}
16185 Tolerate time stamp and other consistency errors.
16187 @geindex -T (gnatbind)
16189 @item @code{-T`n'}
16191 Set the time slice value to @code{n} milliseconds. If the system supports
16192 the specification of a specific time slice value, then the indicated value
16193 is used. If the system does not support specific time slice values, but
16194 does support some general notion of round-robin scheduling, then any
16195 nonzero value will activate round-robin scheduling.
16197 A value of zero is treated specially. It turns off time
16198 slicing, and in addition, indicates to the tasking run-time that the
16199 semantics should match as closely as possible the Annex D
16200 requirements of the Ada RM, and in particular sets the default
16201 scheduling policy to @code{FIFO_Within_Priorities}.
16203 @geindex -u (gnatbind)
16205 @item @code{-u`n'}
16207 Enable dynamic stack usage, with @code{n} results stored and displayed
16208 at program termination. A result is generated when a task
16209 terminates. Results that can’t be stored are displayed on the fly, at
16210 task termination. This option is currently not supported on Itanium
16211 platforms. (See @ref{115,,Dynamic Stack Usage Analysis} for details.)
16213 @geindex -v (gnatbind)
16215 @item @code{-v}
16217 Verbose mode. Write error messages, header, summary output to
16218 @code{stdout}.
16220 @geindex -V (gnatbind)
16222 @item @code{-V`key'=`value'}
16224 Store the given association of @code{key} to @code{value} in the bind environment.
16225 Values stored this way can be retrieved at run time using
16226 @code{GNAT.Bind_Environment}.
16228 @geindex -w (gnatbind)
16230 @item @code{-w`x'}
16232 Warning mode; @code{x} = s/e for suppress/treat as error.
16234 @geindex -Wx (gnatbind)
16236 @item @code{-Wx`e'}
16238 Override default wide character encoding for standard Text_IO files.
16240 @geindex -x (gnatbind)
16242 @item @code{-x}
16244 Exclude source files (check object consistency only).
16246 @geindex -xdr (gnatbind)
16248 @item @code{-xdr}
16250 Use the target-independent XDR protocol for stream oriented attributes
16251 instead of the default implementation which is based on direct binary
16252 representations and is therefore target-and endianness-dependent.
16253 However it does not support 128-bit integer types and the exception
16254 @code{Ada.IO_Exceptions.Device_Error} is raised if any attempt is made
16255 at streaming 128-bit integer types with it.
16257 @geindex -Xnnn (gnatbind)
16259 @item @code{-X`nnn'}
16261 Set default exit status value, normally 0 for POSIX compliance.
16263 @geindex -y (gnatbind)
16265 @item @code{-y}
16267 Enable leap seconds support in @code{Ada.Calendar} and its children.
16269 @geindex -z (gnatbind)
16271 @item @code{-z}
16273 No main subprogram.
16274 @end table
16276 You may obtain this listing of switches by running @code{gnatbind} with
16277 no arguments.
16279 @menu
16280 * Consistency-Checking Modes:: 
16281 * Binder Error Message Control:: 
16282 * Elaboration Control:: 
16283 * Output Control:: 
16284 * Dynamic Allocation Control:: 
16285 * Binding with Non-Ada Main Programs:: 
16286 * Binding Programs with No Main Subprogram:: 
16288 @end menu
16290 @node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
16291 @anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{116}@anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{117}
16292 @subsubsection Consistency-Checking Modes
16295 As described earlier, by default @code{gnatbind} checks
16296 that object files are consistent with one another and are consistent
16297 with any source files it can locate. The following switches control binder
16298 access to sources.
16300 @quotation
16302 @geindex -s (gnatbind)
16303 @end quotation
16306 @table @asis
16308 @item @code{-s}
16310 Require source files to be present. In this mode, the binder must be
16311 able to locate all source files that are referenced, in order to check
16312 their consistency. In normal mode, if a source file cannot be located it
16313 is simply ignored. If you specify this switch, a missing source
16314 file is an error.
16316 @geindex -Wx (gnatbind)
16318 @item @code{-Wx`e'}
16320 Override default wide character encoding for standard Text_IO files.
16321 Normally the default wide character encoding method used for standard
16322 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
16323 the main source input (see description of switch
16324 @code{-gnatWx} for the compiler). The
16325 use of this switch for the binder (which has the same set of
16326 possible arguments) overrides this default as specified.
16328 @geindex -x (gnatbind)
16330 @item @code{-x}
16332 Exclude source files. In this mode, the binder only checks that ALI
16333 files are consistent with one another. Source files are not accessed.
16334 The binder runs faster in this mode, and there is still a guarantee that
16335 the resulting program is self-consistent.
16336 If a source file has been edited since it was last compiled, and you
16337 specify this switch, the binder will not detect that the object
16338 file is out of date with respect to the source file. Note that this is the
16339 mode that is automatically used by @code{gnatmake} because in this
16340 case the checking against sources has already been performed by
16341 @code{gnatmake} in the course of compilation (i.e., before binding).
16342 @end table
16344 @node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
16345 @anchor{gnat_ugn/building_executable_programs_with_gnat binder-error-message-control}@anchor{118}@anchor{gnat_ugn/building_executable_programs_with_gnat id36}@anchor{119}
16346 @subsubsection Binder Error Message Control
16349 The following switches provide control over the generation of error
16350 messages from the binder:
16352 @quotation
16354 @geindex -v (gnatbind)
16355 @end quotation
16358 @table @asis
16360 @item @code{-v}
16362 Verbose mode. In the normal mode, brief error messages are generated to
16363 @code{stderr}. If this switch is present, a header is written
16364 to @code{stdout} and any error messages are directed to @code{stdout}.
16365 All that is written to @code{stderr} is a brief summary message.
16367 @geindex -b (gnatbind)
16369 @item @code{-b}
16371 Generate brief error messages to @code{stderr} even if verbose mode is
16372 specified. This is relevant only when used with the
16373 @code{-v} switch.
16375 @geindex -m (gnatbind)
16377 @item @code{-m`n'}
16379 Limits the number of error messages to @code{n}, a decimal integer in the
16380 range 1-999. The binder terminates immediately if this limit is reached.
16382 @geindex -M (gnatbind)
16384 @item @code{-M`xxx'}
16386 Renames the generated main program from @code{main} to @code{xxx}.
16387 This is useful in the case of some cross-building environments, where
16388 the actual main program is separate from the one generated
16389 by @code{gnatbind}.
16391 @geindex -ws (gnatbind)
16393 @geindex Warnings
16395 @item @code{-ws}
16397 Suppress all warning messages.
16399 @geindex -we (gnatbind)
16401 @item @code{-we}
16403 Treat any warning messages as fatal errors.
16405 @geindex -t (gnatbind)
16407 @geindex Time stamp checks
16408 @geindex in binder
16410 @geindex Binder consistency checks
16412 @geindex Consistency checks
16413 @geindex in binder
16415 @item @code{-t}
16417 The binder performs a number of consistency checks including:
16420 @itemize *
16422 @item 
16423 Check that time stamps of a given source unit are consistent
16425 @item 
16426 Check that checksums of a given source unit are consistent
16428 @item 
16429 Check that consistent versions of @code{GNAT} were used for compilation
16431 @item 
16432 Check consistency of configuration pragmas as required
16433 @end itemize
16435 Normally failure of such checks, in accordance with the consistency
16436 requirements of the Ada Reference Manual, causes error messages to be
16437 generated which abort the binder and prevent the output of a binder
16438 file and subsequent link to obtain an executable.
16440 The @code{-t} switch converts these error messages
16441 into warnings, so that
16442 binding and linking can continue to completion even in the presence of such
16443 errors. The result may be a failed link (due to missing symbols), or a
16444 non-functional executable which has undefined semantics.
16446 @cartouche
16447 @quotation Note 
16448 This means that @code{-t} should be used only in unusual situations,
16449 with extreme care.
16450 @end quotation
16451 @end cartouche
16452 @end table
16454 @node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
16455 @anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{113}@anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{11a}
16456 @subsubsection Elaboration Control
16459 The following switches provide additional control over the elaboration
16460 order. For further details see @ref{f,,Elaboration Order Handling in GNAT}.
16462 @geindex -f (gnatbind)
16465 @table @asis
16467 @item @code{-f`elab-order'}
16469 Force elaboration order.
16471 @code{elab-order} should be the name of a “forced elaboration order file”, that
16472 is, a text file containing library item names, one per line. A name of the
16473 form “some.unit%s” or “some.unit (spec)” denotes the spec of Some.Unit. A
16474 name of the form “some.unit%b” or “some.unit (body)” denotes the body of
16475 Some.Unit. Each pair of lines is taken to mean that there is an elaboration
16476 dependence of the second line on the first. For example, if the file
16477 contains:
16479 @example
16480 this (spec)
16481 this (body)
16482 that (spec)
16483 that (body)
16484 @end example
16486 then the spec of This will be elaborated before the body of This, and the
16487 body of This will be elaborated before the spec of That, and the spec of That
16488 will be elaborated before the body of That. The first and last of these three
16489 dependences are already required by Ada rules, so this file is really just
16490 forcing the body of This to be elaborated before the spec of That.
16492 The given order must be consistent with Ada rules, or else @code{gnatbind} will
16493 give elaboration cycle errors. For example, if you say x (body) should be
16494 elaborated before x (spec), there will be a cycle, because Ada rules require
16495 x (spec) to be elaborated before x (body); you can’t have the spec and body
16496 both elaborated before each other.
16498 If you later add “with That;” to the body of This, there will be a cycle, in
16499 which case you should erase either “this (body)” or “that (spec)” from the
16500 above forced elaboration order file.
16502 Blank lines and Ada-style comments are ignored. Unit names that do not exist
16503 in the program are ignored. Units in the GNAT predefined library are also
16504 ignored.
16505 @end table
16507 @geindex -p (gnatbind)
16510 @table @asis
16512 @item @code{-p}
16514 Pessimistic elaboration order
16516 This switch is only applicable to the pre-20.x legacy elaboration models.
16517 The post-20.x elaboration model uses a more informed approach of ordering
16518 the units.
16520 Normally the binder attempts to choose an elaboration order that is likely to
16521 minimize the likelihood of an elaboration order error resulting in raising a
16522 @code{Program_Error} exception. This switch reverses the action of the binder,
16523 and requests that it deliberately choose an order that is likely to maximize
16524 the likelihood of an elaboration error. This is useful in ensuring
16525 portability and avoiding dependence on accidental fortuitous elaboration
16526 ordering.
16528 Normally it only makes sense to use the @code{-p} switch if dynamic
16529 elaboration checking is used (@code{-gnatE} switch used for compilation).
16530 This is because in the default static elaboration mode, all necessary
16531 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
16532 These implicit pragmas are still respected by the binder in @code{-p}
16533 mode, so a safe elaboration order is assured.
16535 Note that @code{-p} is not intended for production use; it is more for
16536 debugging/experimental use.
16537 @end table
16539 @node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
16540 @anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{11b}@anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{11c}
16541 @subsubsection Output Control
16544 The following switches allow additional control over the output
16545 generated by the binder.
16547 @quotation
16549 @geindex -c (gnatbind)
16550 @end quotation
16553 @table @asis
16555 @item @code{-c}
16557 Check only. Do not generate the binder output file. In this mode the
16558 binder performs all error checks but does not generate an output file.
16560 @geindex -e (gnatbind)
16562 @item @code{-e}
16564 Output complete list of elaboration-order dependencies, showing the
16565 reason for each dependency. This output can be rather extensive but may
16566 be useful in diagnosing problems with elaboration order. The output is
16567 written to @code{stdout}.
16569 @geindex -h (gnatbind)
16571 @item @code{-h}
16573 Output usage information. The output is written to @code{stdout}.
16575 @geindex -K (gnatbind)
16577 @item @code{-K}
16579 Output linker options to @code{stdout}. Includes library search paths,
16580 contents of pragmas Ident and Linker_Options, and libraries added
16581 by @code{gnatbind}.
16583 @geindex -l (gnatbind)
16585 @item @code{-l}
16587 Output chosen elaboration order. The output is written to @code{stdout}.
16589 @geindex -O (gnatbind)
16591 @item @code{-O}
16593 Output full names of all the object files that must be linked to provide
16594 the Ada component of the program. The output is written to @code{stdout}.
16595 This list includes the files explicitly supplied and referenced by the user
16596 as well as implicitly referenced run-time unit files. The latter are
16597 omitted if the corresponding units reside in shared libraries. The
16598 directory names for the run-time units depend on the system configuration.
16600 @geindex -o (gnatbind)
16602 @item @code{-o `file'}
16604 Set name of output file to @code{file} instead of the normal
16605 @code{b~`mainprog}.adb` default. Note that @code{file} denote the Ada
16606 binder generated body filename.
16607 Note that if this option is used, then linking must be done manually.
16608 It is not possible to use gnatlink in this case, since it cannot locate
16609 the binder file.
16611 @geindex -r (gnatbind)
16613 @item @code{-r}
16615 Generate list of @code{pragma Restrictions} that could be applied to
16616 the current unit. This is useful for code audit purposes, and also may
16617 be used to improve code generation in some cases.
16618 @end table
16620 @node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
16621 @anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{114}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{11d}
16622 @subsubsection Dynamic Allocation Control
16625 The heap control switches – @code{-H32} and @code{-H64} –
16626 determine whether dynamic allocation uses 32-bit or 64-bit memory.
16627 They only affect compiler-generated allocations via @code{__gnat_malloc};
16628 explicit calls to @code{malloc} and related functions from the C
16629 run-time library are unaffected.
16632 @table @asis
16634 @item @code{-H32}
16636 Allocate memory on 32-bit heap
16638 @item @code{-H64}
16640 Allocate memory on 64-bit heap.  This is the default
16641 unless explicitly overridden by a @code{'Size} clause on the access type.
16642 @end table
16644 These switches are only effective on VMS platforms.
16646 @node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
16647 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-non-ada-main-programs}@anchor{7e}@anchor{gnat_ugn/building_executable_programs_with_gnat id40}@anchor{11e}
16648 @subsubsection Binding with Non-Ada Main Programs
16651 The description so far has assumed that the main
16652 program is in Ada, and that the task of the binder is to generate a
16653 corresponding function @code{main} that invokes this Ada main
16654 program. GNAT also supports the building of executable programs where
16655 the main program is not in Ada, but some of the called routines are
16656 written in Ada and compiled using GNAT (@ref{2c,,Mixed Language Programming}).
16657 The following switch is used in this situation:
16659 @quotation
16661 @geindex -n (gnatbind)
16662 @end quotation
16665 @table @asis
16667 @item @code{-n}
16669 No main program. The main program is not in Ada.
16670 @end table
16672 In this case, most of the functions of the binder are still required,
16673 but instead of generating a main program, the binder generates a file
16674 containing the following callable routines:
16676 @quotation
16678 @geindex adainit
16681 @table @asis
16683 @item @code{adainit}
16685 You must call this routine to initialize the Ada part of the program by
16686 calling the necessary elaboration routines. A call to @code{adainit} is
16687 required before the first call to an Ada subprogram.
16689 Note that it is assumed that the basic execution environment must be setup
16690 to be appropriate for Ada execution at the point where the first Ada
16691 subprogram is called. In particular, if the Ada code will do any
16692 floating-point operations, then the FPU must be setup in an appropriate
16693 manner. For the case of the x86, for example, full precision mode is
16694 required. The procedure GNAT.Float_Control.Reset may be used to ensure
16695 that the FPU is in the right state.
16696 @end table
16698 @geindex adafinal
16701 @table @asis
16703 @item @code{adafinal}
16705 You must call this routine to perform any library-level finalization
16706 required by the Ada subprograms. A call to @code{adafinal} is required
16707 after the last call to an Ada subprogram, and before the program
16708 terminates.
16709 @end table
16710 @end quotation
16712 @geindex -n (gnatbind)
16714 @geindex Binder
16715 @geindex multiple input files
16717 If the @code{-n} switch
16718 is given, more than one ALI file may appear on
16719 the command line for @code{gnatbind}. The normal @code{closure}
16720 calculation is performed for each of the specified units. Calculating
16721 the closure means finding out the set of units involved by tracing
16722 `with' references. The reason it is necessary to be able to
16723 specify more than one ALI file is that a given program may invoke two or
16724 more quite separate groups of Ada units.
16726 The binder takes the name of its output file from the last specified ALI
16727 file, unless overridden by the use of the @code{-o file}.
16729 @geindex -o (gnatbind)
16731 The output is an Ada unit in source form that can be compiled with GNAT.
16732 This compilation occurs automatically as part of the @code{gnatlink}
16733 processing.
16735 Currently the GNAT run-time requires a FPU using 80 bits mode
16736 precision. Under targets where this is not the default it is required to
16737 call GNAT.Float_Control.Reset before using floating point numbers (this
16738 include float computation, float input and output) in the Ada code. A
16739 side effect is that this could be the wrong mode for the foreign code
16740 where floating point computation could be broken after this call.
16742 @node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
16743 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-programs-with-no-main-subprogram}@anchor{11f}@anchor{gnat_ugn/building_executable_programs_with_gnat id41}@anchor{120}
16744 @subsubsection Binding Programs with No Main Subprogram
16747 It is possible to have an Ada program which does not have a main
16748 subprogram. This program will call the elaboration routines of all the
16749 packages, then the finalization routines.
16751 The following switch is used to bind programs organized in this manner:
16753 @quotation
16755 @geindex -z (gnatbind)
16756 @end quotation
16759 @table @asis
16761 @item @code{-z}
16763 Normally the binder checks that the unit name given on the command line
16764 corresponds to a suitable main subprogram. When this switch is used,
16765 a list of ALI files can be given, and the execution of the program
16766 consists of elaboration of these units in an appropriate order. Note
16767 that the default wide character encoding method for standard Text_IO
16768 files is always set to Brackets if this switch is set (you can use
16769 the binder switch
16770 @code{-Wx} to override this default).
16771 @end table
16773 @node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
16774 @anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{121}@anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{122}
16775 @subsection Command-Line Access
16778 The package @code{Ada.Command_Line} provides access to the command-line
16779 arguments and program name. In order for this interface to operate
16780 correctly, the two variables
16782 @example
16783 int gnat_argc;
16784 char **gnat_argv;
16785 @end example
16787 @geindex gnat_argv
16789 @geindex gnat_argc
16791 are declared in one of the GNAT library routines. These variables must
16792 be set from the actual @code{argc} and @code{argv} values passed to the
16793 main program. With no `n' present, @code{gnatbind}
16794 generates the C main program to automatically set these variables.
16795 If the `n' switch is used, there is no automatic way to
16796 set these variables. If they are not set, the procedures in
16797 @code{Ada.Command_Line} will not be available, and any attempt to use
16798 them will raise @code{Constraint_Error}. If command line access is
16799 required, your main program must set @code{gnat_argc} and
16800 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
16803 @node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
16804 @anchor{gnat_ugn/building_executable_programs_with_gnat id43}@anchor{123}@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-for-gnatbind}@anchor{76}
16805 @subsection Search Paths for @code{gnatbind}
16808 The binder takes the name of an ALI file as its argument and needs to
16809 locate source files as well as other ALI files to verify object consistency.
16811 For source files, it follows exactly the same search rules as @code{gcc}
16812 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
16813 directories searched are:
16816 @itemize *
16818 @item 
16819 The directory containing the ALI file named in the command line, unless
16820 the switch @code{-I-} is specified.
16822 @item 
16823 All directories specified by @code{-I}
16824 switches on the @code{gnatbind}
16825 command line, in the order given.
16827 @geindex ADA_PRJ_OBJECTS_FILE
16829 @item 
16830 Each of the directories listed in the text file whose name is given
16831 by the 
16832 @geindex ADA_PRJ_OBJECTS_FILE
16833 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16834 @code{ADA_PRJ_OBJECTS_FILE} environment variable.
16836 @geindex ADA_PRJ_OBJECTS_FILE
16837 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16838 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
16839 driver when project files are used. It should not normally be set
16840 by other means.
16842 @geindex ADA_OBJECTS_PATH
16844 @item 
16845 Each of the directories listed in the value of the
16846 @geindex ADA_OBJECTS_PATH
16847 @geindex environment variable; ADA_OBJECTS_PATH
16848 @code{ADA_OBJECTS_PATH} environment variable.
16849 Construct this value
16850 exactly as the 
16851 @geindex PATH
16852 @geindex environment variable; PATH
16853 @code{PATH} environment variable: a list of directory
16854 names separated by colons (semicolons when working with the NT version
16855 of GNAT).
16857 @item 
16858 The content of the @code{ada_object_path} file which is part of the GNAT
16859 installation tree and is used to store standard libraries such as the
16860 GNAT Run-Time Library (RTL) unless the switch @code{-nostdlib} is
16861 specified. See @ref{72,,Installing a library}
16862 @end itemize
16864 @geindex -I (gnatbind)
16866 @geindex -aI (gnatbind)
16868 @geindex -aO (gnatbind)
16870 In the binder the switch @code{-I}
16871 is used to specify both source and
16872 library file paths. Use @code{-aI}
16873 instead if you want to specify
16874 source paths only, and @code{-aO}
16875 if you want to specify library paths
16876 only. This means that for the binder
16877 @code{-I`dir'} is equivalent to
16878 @code{-aI`dir'}
16879 @code{-aO``dir'}.
16880 The binder generates the bind file (a C language source file) in the
16881 current working directory.
16883 @geindex Ada
16885 @geindex System
16887 @geindex Interfaces
16889 @geindex GNAT
16891 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
16892 children make up the GNAT Run-Time Library, together with the package
16893 GNAT and its children, which contain a set of useful additional
16894 library functions provided by GNAT. The sources for these units are
16895 needed by the compiler and are kept together in one directory. The ALI
16896 files and object files generated by compiling the RTL are needed by the
16897 binder and the linker and are kept together in one directory, typically
16898 different from the directory containing the sources. In a normal
16899 installation, you need not specify these directory names when compiling
16900 or binding. Either the environment variables or the built-in defaults
16901 cause these files to be found.
16903 Besides simplifying access to the RTL, a major use of search paths is
16904 in compiling sources from multiple directories. This can make
16905 development environments much more flexible.
16907 @node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16908 @anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatbind-usage}@anchor{124}@anchor{gnat_ugn/building_executable_programs_with_gnat id44}@anchor{125}
16909 @subsection Examples of @code{gnatbind} Usage
16912 Here are some examples of @code{gnatbind} invocations:
16914 @quotation
16916 @example
16917 gnatbind hello
16918 @end example
16920 The main program @code{Hello} (source program in @code{hello.adb}) is
16921 bound using the standard switch settings. The generated main program is
16922 @code{b~hello.adb}. This is the normal, default use of the binder.
16924 @example
16925 gnatbind hello -o mainprog.adb
16926 @end example
16928 The main program @code{Hello} (source program in @code{hello.adb}) is
16929 bound using the standard switch settings. The generated main program is
16930 @code{mainprog.adb} with the associated spec in
16931 @code{mainprog.ads}. Note that you must specify the body here not the
16932 spec. Note that if this option is used, then linking must be done manually,
16933 since gnatlink will not be able to find the generated file.
16934 @end quotation
16936 @node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16937 @anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{126}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{cb}
16938 @section Linking with @code{gnatlink}
16941 @geindex gnatlink
16943 This chapter discusses @code{gnatlink}, a tool that links
16944 an Ada program and builds an executable file. This utility
16945 invokes the system linker (via the @code{gcc} command)
16946 with a correct list of object files and library references.
16947 @code{gnatlink} automatically determines the list of files and
16948 references for the Ada part of a program. It uses the binder file
16949 generated by the @code{gnatbind} to determine this list.
16951 @menu
16952 * Running gnatlink:: 
16953 * Switches for gnatlink:: 
16955 @end menu
16957 @node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16958 @anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{127}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{128}
16959 @subsection Running @code{gnatlink}
16962 The form of the @code{gnatlink} command is
16964 @example
16965 $ gnatlink [ switches ] mainprog [.ali]
16966            [ non-Ada objects ] [ linker options ]
16967 @end example
16969 The arguments of @code{gnatlink} (switches, main @code{ALI} file,
16970 non-Ada objects
16971 or linker options) may be in any order, provided that no non-Ada object may
16972 be mistaken for a main @code{ALI} file.
16973 Any file name @code{F} without the @code{.ali}
16974 extension will be taken as the main @code{ALI} file if a file exists
16975 whose name is the concatenation of @code{F} and @code{.ali}.
16977 @code{mainprog.ali} references the ALI file of the main program.
16978 The @code{.ali} extension of this file can be omitted. From this
16979 reference, @code{gnatlink} locates the corresponding binder file
16980 @code{b~mainprog.adb} and, using the information in this file along
16981 with the list of non-Ada objects and linker options, constructs a
16982 linker command file to create the executable.
16984 The arguments other than the @code{gnatlink} switches and the main
16985 @code{ALI} file are passed to the linker uninterpreted.
16986 They typically include the names of
16987 object files for units written in other languages than Ada and any library
16988 references required to resolve references in any of these foreign language
16989 units, or in @code{Import} pragmas in any Ada units.
16991 @code{linker options} is an optional list of linker specific
16992 switches.
16993 The default linker called by gnatlink is @code{gcc} which in
16994 turn calls the appropriate system linker.
16996 One useful option for the linker is @code{-s}: it reduces the size of the
16997 executable by removing all symbol table and relocation information from the
16998 executable.
17000 Standard options for the linker such as @code{-lmy_lib} or
17001 @code{-Ldir} can be added as is.
17002 For options that are not recognized by
17003 @code{gcc} as linker options, use the @code{gcc} switches
17004 @code{-Xlinker} or @code{-Wl,}.
17006 Refer to the GCC documentation for
17007 details.
17009 Here is an example showing how to generate a linker map:
17011 @example
17012 $ gnatlink my_prog -Wl,-Map,MAPFILE
17013 @end example
17015 Using @code{linker options} it is possible to set the program stack and
17016 heap size.
17017 See @ref{129,,Setting Stack Size from gnatlink} and
17018 @ref{12a,,Setting Heap Size from gnatlink}.
17020 @code{gnatlink} determines the list of objects required by the Ada
17021 program and prepends them to the list of objects passed to the linker.
17022 @code{gnatlink} also gathers any arguments set by the use of
17023 @code{pragma Linker_Options} and adds them to the list of arguments
17024 presented to the linker.
17026 @node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
17027 @anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{12b}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{12c}
17028 @subsection Switches for @code{gnatlink}
17031 The following switches are available with the @code{gnatlink} utility:
17033 @geindex --version (gnatlink)
17036 @table @asis
17038 @item @code{--version}
17040 Display Copyright and version, then exit disregarding all other options.
17041 @end table
17043 @geindex --help (gnatlink)
17046 @table @asis
17048 @item @code{--help}
17050 If @code{--version} was not used, display usage, then exit disregarding
17051 all other options.
17052 @end table
17054 @geindex Command line length
17056 @geindex -f (gnatlink)
17059 @table @asis
17061 @item @code{-f}
17063 On some targets, the command line length is limited, and @code{gnatlink}
17064 will generate a separate file for the linker if the list of object files
17065 is too long.
17066 The @code{-f} switch forces this file
17067 to be generated even if
17068 the limit is not exceeded. This is useful in some cases to deal with
17069 special situations where the command line length is exceeded.
17070 @end table
17072 @geindex Debugging information
17073 @geindex including
17075 @geindex -g (gnatlink)
17078 @table @asis
17080 @item @code{-g}
17082 The option to include debugging information causes the Ada bind file (in
17083 other words, @code{b~mainprog.adb}) to be compiled with @code{-g}.
17084 In addition, the binder does not delete the @code{b~mainprog.adb},
17085 @code{b~mainprog.o} and @code{b~mainprog.ali} files.
17086 Without @code{-g}, the binder removes these files by default.
17087 @end table
17089 @geindex -n (gnatlink)
17092 @table @asis
17094 @item @code{-n}
17096 Do not compile the file generated by the binder. This may be used when
17097 a link is rerun with different options, but there is no need to recompile
17098 the binder file.
17099 @end table
17101 @geindex -v (gnatlink)
17104 @table @asis
17106 @item @code{-v}
17108 Verbose mode. Causes additional information to be output, including a full
17109 list of the included object files.
17110 This switch option is most useful when you want
17111 to see what set of object files are being used in the link step.
17112 @end table
17114 @geindex -v -v (gnatlink)
17117 @table @asis
17119 @item @code{-v -v}
17121 Very verbose mode. Requests that the compiler operate in verbose mode when
17122 it compiles the binder file, and that the system linker run in verbose mode.
17123 @end table
17125 @geindex -o (gnatlink)
17128 @table @asis
17130 @item @code{-o `exec-name'}
17132 @code{exec-name} specifies an alternate name for the generated
17133 executable program. If this switch is omitted, the executable has the same
17134 name as the main unit. For example, @code{gnatlink try.ali} creates
17135 an executable called @code{try}.
17136 @end table
17138 @geindex -B (gnatlink)
17141 @table @asis
17143 @item @code{-B`dir'}
17145 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
17146 from @code{dir} instead of the default location. Only use this switch
17147 when multiple versions of the GNAT compiler are available.
17148 See the @code{Directory Options} section in @cite{The_GNU_Compiler_Collection}
17149 for further details. You would normally use the @code{-b} or
17150 @code{-V} switch instead.
17151 @end table
17153 @geindex -M (gnatlink)
17156 @table @asis
17158 @item @code{-M}
17160 When linking an executable, create a map file. The name of the map file
17161 has the same name as the executable with extension “.map”.
17162 @end table
17164 @geindex -M= (gnatlink)
17167 @table @asis
17169 @item @code{-M=`mapfile'}
17171 When linking an executable, create a map file. The name of the map file is
17172 @code{mapfile}.
17173 @end table
17175 @geindex --GCC=compiler_name (gnatlink)
17178 @table @asis
17180 @item @code{--GCC=`compiler_name'}
17182 Program used for compiling the binder file. The default is
17183 @code{gcc}. You need to use quotes around @code{compiler_name} if
17184 @code{compiler_name} contains spaces or other separator characters.
17185 As an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to
17186 use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
17187 inserted after your command name. Thus in the above example the compiler
17188 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
17189 A limitation of this syntax is that the name and path name of the executable
17190 itself must not include any embedded spaces. If the compiler executable is
17191 different from the default one (gcc or <prefix>-gcc), then the back-end
17192 switches in the ALI file are not used to compile the binder generated source.
17193 For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
17194 switches will be used for @code{--GCC="gcc -gnatv"}. If several
17195 @code{--GCC=compiler_name} are used, only the last @code{compiler_name}
17196 is taken into account. However, all the additional switches are also taken
17197 into account. Thus,
17198 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
17199 @code{--GCC="bar -x -y -z -t"}.
17200 @end table
17202 @geindex --LINK= (gnatlink)
17205 @table @asis
17207 @item @code{--LINK=`name'}
17209 @code{name} is the name of the linker to be invoked. This is especially
17210 useful in mixed language programs since languages such as C++ require
17211 their own linker to be used. When this switch is omitted, the default
17212 name for the linker is @code{gcc}. When this switch is used, the
17213 specified linker is called instead of @code{gcc} with exactly the same
17214 parameters that would have been passed to @code{gcc} so if the desired
17215 linker requires different parameters it is necessary to use a wrapper
17216 script that massages the parameters before invoking the real linker. It
17217 may be useful to control the exact invocation by using the verbose
17218 switch.
17219 @end table
17221 @node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
17222 @anchor{gnat_ugn/building_executable_programs_with_gnat id48}@anchor{12d}@anchor{gnat_ugn/building_executable_programs_with_gnat using-the-gnu-make-utility}@anchor{70}
17223 @section Using the GNU @code{make} Utility
17226 @geindex make (GNU)
17227 @geindex GNU make
17229 This chapter offers some examples of makefiles that solve specific
17230 problems. It does not explain how to write a makefile, nor does it try to replace the
17231 @code{gnatmake} utility (@ref{c8,,Building with gnatmake}).
17233 All the examples in this section are specific to the GNU version of
17234 make. Although @code{make} is a standard utility, and the basic language
17235 is the same, these examples use some advanced features found only in
17236 @code{GNU make}.
17238 @menu
17239 * Using gnatmake in a Makefile:: 
17240 * Automatically Creating a List of Directories:: 
17241 * Generating the Command Line Switches:: 
17242 * Overcoming Command Line Length Limits:: 
17244 @end menu
17246 @node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
17247 @anchor{gnat_ugn/building_executable_programs_with_gnat id49}@anchor{12e}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gnatmake-in-a-makefile}@anchor{12f}
17248 @subsection Using gnatmake in a Makefile
17251 @c index makefile (GNU make)
17253 Complex project organizations can be handled in a very powerful way by
17254 using GNU make combined with gnatmake. For instance, here is a Makefile
17255 which allows you to build each subsystem of a big project into a separate
17256 shared library. Such a makefile allows you to significantly reduce the link
17257 time of very big applications while maintaining full coherence at
17258 each step of the build process.
17260 The list of dependencies are handled automatically by
17261 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
17262 the appropriate directories.
17264 Note that you should also read the example on how to automatically
17265 create the list of directories
17266 (@ref{130,,Automatically Creating a List of Directories})
17267 which might help you in case your project has a lot of subdirectories.
17269 @example
17270 ## This Makefile is intended to be used with the following directory
17271 ## configuration:
17272 ##  - The sources are split into a series of csc (computer software components)
17273 ##    Each of these csc is put in its own directory.
17274 ##    Their name are referenced by the directory names.
17275 ##    They will be compiled into shared library (although this would also work
17276 ##    with static libraries)
17277 ##  - The main program (and possibly other packages that do not belong to any
17278 ##    csc) is put in the top level directory (where the Makefile is).
17279 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17280 ##                    \\_ second_csc (sources) __ lib (will contain the library)
17281 ##                    \\_ ...
17282 ## Although this Makefile is build for shared library, it is easy to modify
17283 ## to build partial link objects instead (modify the lines with -shared and
17284 ## gnatlink below)
17286 ## With this makefile, you can change any file in the system or add any new
17287 ## file, and everything will be recompiled correctly (only the relevant shared
17288 ## objects will be recompiled, and the main program will be re-linked).
17290 # The list of computer software component for your project. This might be
17291 # generated automatically.
17292 CSC_LIST=aa bb cc
17294 # Name of the main program (no extension)
17295 MAIN=main
17297 # If we need to build objects with -fPIC, uncomment the following line
17298 #NEED_FPIC=-fPIC
17300 # The following variable should give the directory containing libgnat.so
17301 # You can get this directory through 'gnatls -v'. This is usually the last
17302 # directory in the Object_Path.
17303 GLIB=...
17305 # The directories for the libraries
17306 # (This macro expands the list of CSC to the list of shared libraries, you
17307 # could simply use the expanded form:
17308 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17309 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17311 $@{MAIN@}: objects $@{LIB_DIR@}
17312     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17313     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17315 objects::
17316     # recompile the sources
17317     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17319 # Note: In a future version of GNAT, the following commands will be simplified
17320 # by a new tool, gnatmlib
17321 $@{LIB_DIR@}:
17322     mkdir -p $@{dir $@@ @}
17323     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17324     cd $@{dir $@@ @} && cp -f ../*.ali .
17326 # The dependencies for the modules
17327 # Note that we have to force the expansion of *.o, since in some cases
17328 # make won't be able to do it itself.
17329 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17330 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17331 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17333 # Make sure all of the shared libraries are in the path before starting the
17334 # program
17335 run::
17336     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17338 clean::
17339     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17340     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17341     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17342     $@{RM@} *.o *.ali $@{MAIN@}
17343 @end example
17345 @node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
17346 @anchor{gnat_ugn/building_executable_programs_with_gnat automatically-creating-a-list-of-directories}@anchor{130}@anchor{gnat_ugn/building_executable_programs_with_gnat id50}@anchor{131}
17347 @subsection Automatically Creating a List of Directories
17350 In most makefiles, you will have to specify a list of directories, and
17351 store it in a variable. For small projects, it is often easier to
17352 specify each of them by hand, since you then have full control over what
17353 is the proper order for these directories, which ones should be
17354 included.
17356 However, in larger projects, which might involve hundreds of
17357 subdirectories, it might be more convenient to generate this list
17358 automatically.
17360 The example below presents two methods. The first one, although less
17361 general, gives you more control over the list. It involves wildcard
17362 characters, that are automatically expanded by @code{make}. Its
17363 shortcoming is that you need to explicitly specify some of the
17364 organization of your project, such as for instance the directory tree
17365 depth, whether some directories are found in a separate tree, etc.
17367 The second method is the most general one. It requires an external
17368 program, called @code{find}, which is standard on all Unix systems. All
17369 the directories found under a given root directory will be added to the
17370 list.
17372 @example
17373 # The examples below are based on the following directory hierarchy:
17374 # All the directories can contain any number of files
17375 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17376 #                       ->  ab
17377 #                       ->  ac
17378 #                ->  b  ->  ba  ->  baa
17379 #                       ->  bb
17380 #                       ->  bc
17381 # This Makefile creates a variable called DIRS, that can be reused any time
17382 # you need this list (see the other examples in this section)
17384 # The root of your project's directory hierarchy
17385 ROOT_DIRECTORY=.
17387 ####
17388 # First method: specify explicitly the list of directories
17389 # This allows you to specify any subset of all the directories you need.
17390 ####
17392 DIRS := a/aa/ a/ab/ b/ba/
17394 ####
17395 # Second method: use wildcards
17396 # Note that the argument(s) to wildcard below should end with a '/'.
17397 # Since wildcards also return file names, we have to filter them out
17398 # to avoid duplicate directory names.
17399 # We thus use make's `@w{`}dir`@w{`} and `@w{`}sort`@w{`} functions.
17400 # It sets DIRs to the following value (note that the directories aaa and baa
17401 # are not given, unless you change the arguments to wildcard).
17402 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17403 ####
17405 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17406                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17408 ####
17409 # Third method: use an external program
17410 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17411 # This is the most complete command: it sets DIRs to the following value:
17412 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17413 ####
17415 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17416 @end example
17418 @node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
17419 @anchor{gnat_ugn/building_executable_programs_with_gnat generating-the-command-line-switches}@anchor{132}@anchor{gnat_ugn/building_executable_programs_with_gnat id51}@anchor{133}
17420 @subsection Generating the Command Line Switches
17423 Once you have created the list of directories as explained in the
17424 previous section (@ref{130,,Automatically Creating a List of Directories}),
17425 you can easily generate the command line arguments to pass to gnatmake.
17427 For the sake of completeness, this example assumes that the source path
17428 is not the same as the object path, and that you have two separate lists
17429 of directories.
17431 @example
17432 # see "Automatically creating a list of directories" to create
17433 # these variables
17434 SOURCE_DIRS=
17435 OBJECT_DIRS=
17437 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17438 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17440 all:
17441         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17442 @end example
17444 @node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
17445 @anchor{gnat_ugn/building_executable_programs_with_gnat id52}@anchor{134}@anchor{gnat_ugn/building_executable_programs_with_gnat overcoming-command-line-length-limits}@anchor{135}
17446 @subsection Overcoming Command Line Length Limits
17449 One problem that might be encountered on big projects is that many
17450 operating systems limit the length of the command line. It is thus hard to give
17451 gnatmake the list of source and object directories.
17453 This example shows how you can set up environment variables, which will
17454 make @code{gnatmake} behave exactly as if the directories had been
17455 specified on the command line, but have a much higher length limit (or
17456 even none on most systems).
17458 It assumes that you have created a list of directories in your Makefile,
17459 using one of the methods presented in
17460 @ref{130,,Automatically Creating a List of Directories}.
17461 For the sake of completeness, we assume that the object
17462 path (where the ALI files are found) is different from the sources patch.
17464 Note a small trick in the Makefile below: for efficiency reasons, we
17465 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17466 expanded immediately by @code{make}. This way we overcome the standard
17467 make behavior which is to expand the variables only when they are
17468 actually used.
17470 On Windows, if you are using the standard Windows command shell, you must
17471 replace colons with semicolons in the assignments to these variables.
17473 @example
17474 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17475 # This is the same thing as putting the -I arguments on the command line.
17476 # (the equivalent of using -aI on the command line would be to define
17477 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17478 # You can of course have different values for these variables.
17480 # Note also that we need to keep the previous values of these variables, since
17481 # they might have been set before running 'make' to specify where the GNAT
17482 # library is installed.
17484 # see "Automatically creating a list of directories" to create these
17485 # variables
17486 SOURCE_DIRS=
17487 OBJECT_DIRS=
17489 empty:=
17490 space:=$@{empty@} $@{empty@}
17491 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17492 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17493 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17494 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17495 export ADA_INCLUDE_PATH
17496 export ADA_OBJECTS_PATH
17498 all:
17499         gnatmake main_unit
17500 @end example
17502 @node GNAT Utility Programs,GNAT and Program Execution,Building Executable Programs with GNAT,Top
17503 @anchor{gnat_ugn/gnat_utility_programs doc}@anchor{136}@anchor{gnat_ugn/gnat_utility_programs gnat-utility-programs}@anchor{b}@anchor{gnat_ugn/gnat_utility_programs id1}@anchor{137}
17504 @chapter GNAT Utility Programs
17507 This chapter describes a number of utility programs:
17511 @itemize *
17513 @item 
17514 @ref{138,,The File Cleanup Utility gnatclean}
17516 @item 
17517 @ref{139,,The GNAT Library Browser gnatls}
17518 @end itemize
17520 Other GNAT utilities are described elsewhere in this manual:
17523 @itemize *
17525 @item 
17526 @ref{42,,Handling Arbitrary File Naming Conventions with gnatname}
17528 @item 
17529 @ref{4c,,File Name Krunching with gnatkr}
17531 @item 
17532 @ref{1d,,Renaming Files with gnatchop}
17534 @item 
17535 @ref{90,,Preprocessing with gnatprep}
17536 @end itemize
17538 @menu
17539 * The File Cleanup Utility gnatclean:: 
17540 * The GNAT Library Browser gnatls:: 
17542 @end menu
17544 @node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
17545 @anchor{gnat_ugn/gnat_utility_programs id2}@anchor{13a}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{138}
17546 @section The File Cleanup Utility @code{gnatclean}
17549 @geindex File cleanup tool
17551 @geindex gnatclean
17553 @code{gnatclean} is a tool that allows the deletion of files produced by the
17554 compiler, binder and linker, including ALI files, object files, tree files,
17555 expanded source files, library files, interface copy source files, binder
17556 generated files and executable files.
17558 @menu
17559 * Running gnatclean:: 
17560 * Switches for gnatclean:: 
17562 @end menu
17564 @node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
17565 @anchor{gnat_ugn/gnat_utility_programs id3}@anchor{13b}@anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{13c}
17566 @subsection Running @code{gnatclean}
17569 The @code{gnatclean} command has the form:
17571 @quotation
17573 @example
17574 $ gnatclean switches names
17575 @end example
17576 @end quotation
17578 where @code{names} is a list of source file names. Suffixes @code{.ads} and
17579 @code{adb} may be omitted. If a project file is specified using switch
17580 @code{-P}, then @code{names} may be completely omitted.
17582 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17583 if switch @code{-c} is not specified, by the binder and
17584 the linker. In informative-only mode, specified by switch
17585 @code{-n}, the list of files that would have been deleted in
17586 normal mode is listed, but no file is actually deleted.
17588 @node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
17589 @anchor{gnat_ugn/gnat_utility_programs id4}@anchor{13d}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{13e}
17590 @subsection Switches for @code{gnatclean}
17593 @code{gnatclean} recognizes the following switches:
17595 @geindex --version (gnatclean)
17598 @table @asis
17600 @item @code{--version}
17602 Display copyright and version, then exit disregarding all other options.
17603 @end table
17605 @geindex --help (gnatclean)
17608 @table @asis
17610 @item @code{--help}
17612 If @code{--version} was not used, display usage, then exit disregarding
17613 all other options.
17615 @item @code{--subdirs=`subdir'}
17617 Actual object directory of each project file is the subdirectory subdir of the
17618 object directory specified or defaulted in the project file.
17620 @item @code{--unchecked-shared-lib-imports}
17622 By default, shared library projects are not allowed to import static library
17623 projects. When this switch is used on the command line, this restriction is
17624 relaxed.
17625 @end table
17627 @geindex -c (gnatclean)
17630 @table @asis
17632 @item @code{-c}
17634 Only attempt to delete the files produced by the compiler, not those produced
17635 by the binder or the linker. The files that are not to be deleted are library
17636 files, interface copy files, binder generated files and executable files.
17637 @end table
17639 @geindex -D (gnatclean)
17642 @table @asis
17644 @item @code{-D `dir'}
17646 Indicate that ALI and object files should normally be found in directory @code{dir}.
17647 @end table
17649 @geindex -F (gnatclean)
17652 @table @asis
17654 @item @code{-F}
17656 When using project files, if some errors or warnings are detected during
17657 parsing and verbose mode is not in effect (no use of switch
17658 -v), then error lines start with the full path name of the project
17659 file, rather than its simple file name.
17660 @end table
17662 @geindex -h (gnatclean)
17665 @table @asis
17667 @item @code{-h}
17669 Output a message explaining the usage of @code{gnatclean}.
17670 @end table
17672 @geindex -n (gnatclean)
17675 @table @asis
17677 @item @code{-n}
17679 Informative-only mode. Do not delete any files. Output the list of the files
17680 that would have been deleted if this switch was not specified.
17681 @end table
17683 @geindex -P (gnatclean)
17686 @table @asis
17688 @item @code{-P`project'}
17690 Use project file @code{project}. Only one such switch can be used.
17691 When cleaning a project file, the files produced by the compilation of the
17692 immediate sources or inherited sources of the project files are to be
17693 deleted. This is not depending on the presence or not of executable names
17694 on the command line.
17695 @end table
17697 @geindex -q (gnatclean)
17700 @table @asis
17702 @item @code{-q}
17704 Quiet output. If there are no errors, do not output anything, except in
17705 verbose mode (switch -v) or in informative-only mode
17706 (switch -n).
17707 @end table
17709 @geindex -r (gnatclean)
17712 @table @asis
17714 @item @code{-r}
17716 When a project file is specified (using switch -P),
17717 clean all imported and extended project files, recursively. If this switch
17718 is not specified, only the files related to the main project file are to be
17719 deleted. This switch has no effect if no project file is specified.
17720 @end table
17722 @geindex -v (gnatclean)
17725 @table @asis
17727 @item @code{-v}
17729 Verbose mode.
17730 @end table
17732 @geindex -vP (gnatclean)
17735 @table @asis
17737 @item @code{-vP`x'}
17739 Indicates the verbosity of the parsing of GNAT project files.
17740 @ref{d1,,Switches Related to Project Files}.
17741 @end table
17743 @geindex -X (gnatclean)
17746 @table @asis
17748 @item @code{-X`name'=`value'}
17750 Indicates that external variable @code{name} has the value @code{value}.
17751 The Project Manager will use this value for occurrences of
17752 @code{external(name)} when parsing the project file.
17753 See @ref{d1,,Switches Related to Project Files}.
17754 @end table
17756 @geindex -aO (gnatclean)
17759 @table @asis
17761 @item @code{-aO`dir'}
17763 When searching for ALI and object files, look in directory @code{dir}.
17764 @end table
17766 @geindex -I (gnatclean)
17769 @table @asis
17771 @item @code{-I`dir'}
17773 Equivalent to @code{-aO`dir'}.
17774 @end table
17776 @geindex -I- (gnatclean)
17778 @geindex Source files
17779 @geindex suppressing search
17782 @table @asis
17784 @item @code{-I-}
17786 Do not look for ALI or object files in the directory
17787 where @code{gnatclean} was invoked.
17788 @end table
17790 @node The GNAT Library Browser gnatls,,The File Cleanup Utility gnatclean,GNAT Utility Programs
17791 @anchor{gnat_ugn/gnat_utility_programs id5}@anchor{13f}@anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{139}
17792 @section The GNAT Library Browser @code{gnatls}
17795 @geindex Library browser
17797 @geindex gnatls
17799 @code{gnatls} is a tool that outputs information about compiled
17800 units. It gives the relationship between objects, unit names and source
17801 files. It can also be used to check the source dependencies of a unit
17802 as well as various characteristics.
17804 @menu
17805 * Running gnatls:: 
17806 * Switches for gnatls:: 
17807 * Example of gnatls Usage:: 
17809 @end menu
17811 @node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
17812 @anchor{gnat_ugn/gnat_utility_programs id6}@anchor{140}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{141}
17813 @subsection Running @code{gnatls}
17816 The @code{gnatls} command has the form
17818 @quotation
17820 @example
17821 $ gnatls switches object_or_ali_file
17822 @end example
17823 @end quotation
17825 The main argument is the list of object or @code{ali} files
17826 (see @ref{28,,The Ada Library Information Files})
17827 for which information is requested.
17829 In normal mode, without additional option, @code{gnatls} produces a
17830 four-column listing. Each line represents information for a specific
17831 object. The first column gives the full path of the object, the second
17832 column gives the name of the principal unit in this object, the third
17833 column gives the status of the source and the fourth column gives the
17834 full path of the source representing this unit.
17835 Here is a simple example of use:
17837 @quotation
17839 @example
17840 $ gnatls *.o
17841 ./demo1.o            demo1            DIF demo1.adb
17842 ./demo2.o            demo2             OK demo2.adb
17843 ./hello.o            h1                OK hello.adb
17844 ./instr-child.o      instr.child      MOK instr-child.adb
17845 ./instr.o            instr             OK instr.adb
17846 ./tef.o              tef              DIF tef.adb
17847 ./text_io_example.o  text_io_example   OK text_io_example.adb
17848 ./tgef.o             tgef             DIF tgef.adb
17849 @end example
17850 @end quotation
17852 The first line can be interpreted as follows: the main unit which is
17853 contained in
17854 object file @code{demo1.o} is demo1, whose main source is in
17855 @code{demo1.adb}. Furthermore, the version of the source used for the
17856 compilation of demo1 has been modified (DIF). Each source file has a status
17857 qualifier which can be:
17860 @table @asis
17862 @item `OK (unchanged)'
17864 The version of the source file used for the compilation of the
17865 specified unit corresponds exactly to the actual source file.
17867 @item `MOK (slightly modified)'
17869 The version of the source file used for the compilation of the
17870 specified unit differs from the actual source file but not enough to
17871 require recompilation. If you use gnatmake with the option
17872 @code{-m} (minimal recompilation), a file marked
17873 MOK will not be recompiled.
17875 @item `DIF (modified)'
17877 No version of the source found on the path corresponds to the source
17878 used to build this object.
17880 @item `??? (file not found)'
17882 No source file was found for this unit.
17884 @item `HID (hidden,  unchanged version not first on PATH)'
17886 The version of the source that corresponds exactly to the source used
17887 for compilation has been found on the path but it is hidden by another
17888 version of the same source that has been modified.
17889 @end table
17891 @node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
17892 @anchor{gnat_ugn/gnat_utility_programs id7}@anchor{142}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{143}
17893 @subsection Switches for @code{gnatls}
17896 @code{gnatls} recognizes the following switches:
17898 @geindex --version (gnatls)
17901 @table @asis
17903 @item @code{--version}
17905 Display copyright and version, then exit disregarding all other options.
17906 @end table
17908 @geindex --help (gnatls)
17911 @table @asis
17913 @item @code{--help}
17915 If @code{--version} was not used, display usage, then exit disregarding
17916 all other options.
17917 @end table
17919 @geindex -a (gnatls)
17922 @table @asis
17924 @item @code{-a}
17926 Consider all units, including those of the predefined Ada library.
17927 Especially useful with @code{-d}.
17928 @end table
17930 @geindex -d (gnatls)
17933 @table @asis
17935 @item @code{-d}
17937 List sources from which specified units depend on.
17938 @end table
17940 @geindex -h (gnatls)
17943 @table @asis
17945 @item @code{-h}
17947 Output the list of options.
17948 @end table
17950 @geindex -o (gnatls)
17953 @table @asis
17955 @item @code{-o}
17957 Only output information about object files.
17958 @end table
17960 @geindex -s (gnatls)
17963 @table @asis
17965 @item @code{-s}
17967 Only output information about source files.
17968 @end table
17970 @geindex -u (gnatls)
17973 @table @asis
17975 @item @code{-u}
17977 Only output information about compilation units.
17978 @end table
17980 @geindex -files (gnatls)
17983 @table @asis
17985 @item @code{-files=`file'}
17987 Take as arguments the files listed in text file @code{file}.
17988 Text file @code{file} may contain empty lines that are ignored.
17989 Each nonempty line should contain the name of an existing file.
17990 Several such switches may be specified simultaneously.
17991 @end table
17993 @geindex -aO (gnatls)
17995 @geindex -aI (gnatls)
17997 @geindex -I (gnatls)
17999 @geindex -I- (gnatls)
18002 @table @asis
18004 @item @code{-aO`dir'}, @code{-aI`dir'}, @code{-I`dir'}, @code{-I-}, @code{-nostdinc}
18006 Source path manipulation. Same meaning as the equivalent @code{gnatmake}
18007 flags (@ref{d0,,Switches for gnatmake}).
18008 @end table
18010 @geindex -aP (gnatls)
18013 @table @asis
18015 @item @code{-aP`dir'}
18017 Add @code{dir} at the beginning of the project search dir.
18018 @end table
18020 @geindex --RTS (gnatls)
18023 @table @asis
18025 @item @code{--RTS=`rts-path'}
18027 Specifies the default location of the runtime library. Same meaning as the
18028 equivalent @code{gnatmake} flag (@ref{d0,,Switches for gnatmake}).
18029 @end table
18031 @geindex -v (gnatls)
18034 @table @asis
18036 @item @code{-v}
18038 Verbose mode. Output the complete source, object and project paths. Do not use
18039 the default column layout but instead use long format giving as much as
18040 information possible on each requested units, including special
18041 characteristics such as:
18044 @itemize *
18046 @item 
18047 `Preelaborable': The unit is preelaborable in the Ada sense.
18049 @item 
18050 `No_Elab_Code':  No elaboration code has been produced by the compiler for this unit.
18052 @item 
18053 `Pure': The unit is pure in the Ada sense.
18055 @item 
18056 `Elaborate_Body': The unit contains a pragma Elaborate_Body.
18058 @item 
18059 `Remote_Types': The unit contains a pragma Remote_Types.
18061 @item 
18062 `Shared_Passive': The unit contains a pragma Shared_Passive.
18064 @item 
18065 `Predefined': This unit is part of the predefined environment and cannot be modified
18066 by the user.
18068 @item 
18069 `Remote_Call_Interface': The unit contains a pragma Remote_Call_Interface.
18070 @end itemize
18071 @end table
18073 @node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
18074 @anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{144}@anchor{gnat_ugn/gnat_utility_programs id8}@anchor{145}
18075 @subsection Example of @code{gnatls} Usage
18078 Example of using the verbose switch. Note how the source and
18079 object paths are affected by the -I switch.
18081 @quotation
18083 @example
18084 $ gnatls -v -I.. demo1.o
18086 GNATLS 5.03w (20041123-34)
18087 Copyright 1997-2004 Free Software Foundation, Inc.
18089 Source Search Path:
18090    <Current_Directory>
18091    ../
18092    /home/comar/local/adainclude/
18094 Object Search Path:
18095    <Current_Directory>
18096    ../
18097    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18099 Project Search Path:
18100    <Current_Directory>
18101    /home/comar/local/lib/gnat/
18103 ./demo1.o
18104    Unit =>
18105      Name   => demo1
18106      Kind   => subprogram body
18107      Flags  => No_Elab_Code
18108      Source => demo1.adb    modified
18109 @end example
18110 @end quotation
18112 The following is an example of use of the dependency list.
18113 Note the use of the -s switch
18114 which gives a straight list of source files. This can be useful for
18115 building specialized scripts.
18117 @quotation
18119 @example
18120 $ gnatls -d demo2.o
18121 ./demo2.o   demo2        OK demo2.adb
18122                          OK gen_list.ads
18123                          OK gen_list.adb
18124                          OK instr.ads
18125                          OK instr-child.ads
18127 $ gnatls -d -s -a demo1.o
18128 demo1.adb
18129 /home/comar/local/adainclude/ada.ads
18130 /home/comar/local/adainclude/a-finali.ads
18131 /home/comar/local/adainclude/a-filico.ads
18132 /home/comar/local/adainclude/a-stream.ads
18133 /home/comar/local/adainclude/a-tags.ads
18134 gen_list.ads
18135 gen_list.adb
18136 /home/comar/local/adainclude/gnat.ads
18137 /home/comar/local/adainclude/g-io.ads
18138 instr.ads
18139 /home/comar/local/adainclude/system.ads
18140 /home/comar/local/adainclude/s-exctab.ads
18141 /home/comar/local/adainclude/s-finimp.ads
18142 /home/comar/local/adainclude/s-finroo.ads
18143 /home/comar/local/adainclude/s-secsta.ads
18144 /home/comar/local/adainclude/s-stalib.ads
18145 /home/comar/local/adainclude/s-stoele.ads
18146 /home/comar/local/adainclude/s-stratt.ads
18147 /home/comar/local/adainclude/s-tasoli.ads
18148 /home/comar/local/adainclude/s-unstyp.ads
18149 /home/comar/local/adainclude/unchconv.ads
18150 @end example
18151 @end quotation
18157 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
18159 @node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
18160 @anchor{gnat_ugn/gnat_and_program_execution doc}@anchor{146}@anchor{gnat_ugn/gnat_and_program_execution gnat-and-program-execution}@anchor{c}@anchor{gnat_ugn/gnat_and_program_execution id1}@anchor{147}
18161 @chapter GNAT and Program Execution
18164 This chapter covers several topics:
18167 @itemize *
18169 @item 
18170 @ref{148,,Running and Debugging Ada Programs}
18172 @item 
18173 @ref{149,,Profiling}
18175 @item 
18176 @ref{14a,,Improving Performance}
18178 @item 
18179 @ref{14b,,Overflow Check Handling in GNAT}
18181 @item 
18182 @ref{14c,,Performing Dimensionality Analysis in GNAT}
18184 @item 
18185 @ref{14d,,Stack Related Facilities}
18187 @item 
18188 @ref{14e,,Memory Management Issues}
18189 @end itemize
18191 @menu
18192 * Running and Debugging Ada Programs:: 
18193 * Profiling:: 
18194 * Improving Performance:: 
18195 * Overflow Check Handling in GNAT:: 
18196 * Performing Dimensionality Analysis in GNAT:: 
18197 * Stack Related Facilities:: 
18198 * Memory Management Issues:: 
18200 @end menu
18202 @node Running and Debugging Ada Programs,Profiling,,GNAT and Program Execution
18203 @anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{148}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{14f}
18204 @section Running and Debugging Ada Programs
18207 @geindex Debugging
18209 This section discusses how to debug Ada programs.
18211 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18214 @itemize *
18216 @item 
18217 The illegality may be a violation of the static semantics of Ada. In
18218 that case GNAT diagnoses the constructs in the program that are illegal.
18219 It is then a straightforward matter for the user to modify those parts of
18220 the program.
18222 @item 
18223 The illegality may be a violation of the dynamic semantics of Ada. In
18224 that case the program compiles and executes, but may generate incorrect
18225 results, or may terminate abnormally with some exception.
18227 @item 
18228 When presented with a program that contains convoluted errors, GNAT
18229 itself may terminate abnormally without providing full diagnostics on
18230 the incorrect user program.
18231 @end itemize
18233 @geindex Debugger
18235 @geindex gdb
18237 @menu
18238 * The GNAT Debugger GDB:: 
18239 * Running GDB:: 
18240 * Introduction to GDB Commands:: 
18241 * Using Ada Expressions:: 
18242 * Calling User-Defined Subprograms:: 
18243 * Using the next Command in a Function:: 
18244 * Stopping When Ada Exceptions Are Raised:: 
18245 * Ada Tasks:: 
18246 * Debugging Generic Units:: 
18247 * Remote Debugging with gdbserver:: 
18248 * GNAT Abnormal Termination or Failure to Terminate:: 
18249 * Naming Conventions for GNAT Source Files:: 
18250 * Getting Internal Debugging Information:: 
18251 * Stack Traceback:: 
18252 * Pretty-Printers for the GNAT runtime:: 
18254 @end menu
18256 @node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
18257 @anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{150}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{151}
18258 @subsection The GNAT Debugger GDB
18261 @code{GDB} is a general purpose, platform-independent debugger that
18262 can be used to debug mixed-language programs compiled with @code{gcc},
18263 and in particular is capable of debugging Ada programs compiled with
18264 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18265 complex Ada data structures.
18267 See @cite{Debugging with GDB},
18268 for full details on the usage of @code{GDB}, including a section on
18269 its usage on programs. This manual should be consulted for full
18270 details. The section that follows is a brief introduction to the
18271 philosophy and use of @code{GDB}.
18273 When GNAT programs are compiled, the compiler optionally writes debugging
18274 information into the generated object file, including information on
18275 line numbers, and on declared types and variables. This information is
18276 separate from the generated code. It makes the object files considerably
18277 larger, but it does not add to the size of the actual executable that
18278 will be loaded into memory, and has no impact on run-time performance. The
18279 generation of debug information is triggered by the use of the
18280 @code{-g} switch in the @code{gcc} or @code{gnatmake} command
18281 used to carry out the compilations. It is important to emphasize that
18282 the use of these options does not change the generated code.
18284 The debugging information is written in standard system formats that
18285 are used by many tools, including debuggers and profilers. The format
18286 of the information is typically designed to describe C types and
18287 semantics, but GNAT implements a translation scheme which allows full
18288 details about Ada types and variables to be encoded into these
18289 standard C formats. Details of this encoding scheme may be found in
18290 the file exp_dbug.ads in the GNAT source distribution. However, the
18291 details of this encoding are, in general, of no interest to a user,
18292 since @code{GDB} automatically performs the necessary decoding.
18294 When a program is bound and linked, the debugging information is
18295 collected from the object files, and stored in the executable image of
18296 the program. Again, this process significantly increases the size of
18297 the generated executable file, but it does not increase the size of
18298 the executable program itself. Furthermore, if this program is run in
18299 the normal manner, it runs exactly as if the debug information were
18300 not present, and takes no more actual memory.
18302 However, if the program is run under control of @code{GDB}, the
18303 debugger is activated.  The image of the program is loaded, at which
18304 point it is ready to run.  If a run command is given, then the program
18305 will run exactly as it would have if @code{GDB} were not present. This
18306 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18307 entirely non-intrusive until a breakpoint is encountered.  If no
18308 breakpoint is ever hit, the program will run exactly as it would if no
18309 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18310 the debugging information and can respond to user commands to inspect
18311 variables, and more generally to report on the state of execution.
18313 @node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
18314 @anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{152}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{153}
18315 @subsection Running GDB
18318 This section describes how to initiate the debugger.
18320 The debugger can be launched from a @code{GNAT Studio} menu or
18321 directly from the command line. The description below covers the latter use.
18322 All the commands shown can be used in the @code{GNAT Studio} debug console window,
18323 but there are usually more GUI-based ways to achieve the same effect.
18325 The command to run @code{GDB} is
18327 @quotation
18329 @example
18330 $ gdb program
18331 @end example
18332 @end quotation
18334 where @code{program} is the name of the executable file. This
18335 activates the debugger and results in a prompt for debugger commands.
18336 The simplest command is simply @code{run}, which causes the program to run
18337 exactly as if the debugger were not present. The following section
18338 describes some of the additional commands that can be given to @code{GDB}.
18340 @node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
18341 @anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{154}@anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{155}
18342 @subsection Introduction to GDB Commands
18345 @code{GDB} contains a large repertoire of commands.
18346 See @cite{Debugging with GDB} for extensive documentation on the use
18347 of these commands, together with examples of their use. Furthermore,
18348 the command `help' invoked from within GDB activates a simple help
18349 facility which summarizes the available commands and their options.
18350 In this section we summarize a few of the most commonly
18351 used commands to give an idea of what @code{GDB} is about. You should create
18352 a simple program with debugging information and experiment with the use of
18353 these @code{GDB} commands on the program as you read through the
18354 following section.
18357 @itemize *
18359 @item 
18361 @table @asis
18363 @item @code{set args @var{arguments}}
18365 The `arguments' list above is a list of arguments to be passed to
18366 the program on a subsequent run command, just as though the arguments
18367 had been entered on a normal invocation of the program. The @code{set args}
18368 command is not needed if the program does not require arguments.
18369 @end table
18371 @item 
18373 @table @asis
18375 @item @code{run}
18377 The @code{run} command causes execution of the program to start from
18378 the beginning. If the program is already running, that is to say if
18379 you are currently positioned at a breakpoint, then a prompt will ask
18380 for confirmation that you want to abandon the current execution and
18381 restart.
18382 @end table
18384 @item 
18386 @table @asis
18388 @item @code{breakpoint @var{location}}
18390 The breakpoint command sets a breakpoint, that is to say a point at which
18391 execution will halt and @code{GDB} will await further
18392 commands. `location' is
18393 either a line number within a file, given in the format @code{file:linenumber},
18394 or it is the name of a subprogram. If you request that a breakpoint be set on
18395 a subprogram that is overloaded, a prompt will ask you to specify on which of
18396 those subprograms you want to breakpoint. You can also
18397 specify that all of them should be breakpointed. If the program is run
18398 and execution encounters the breakpoint, then the program
18399 stops and @code{GDB} signals that the breakpoint was encountered by
18400 printing the line of code before which the program is halted.
18401 @end table
18403 @item 
18405 @table @asis
18407 @item @code{catch exception @var{name}}
18409 This command causes the program execution to stop whenever exception
18410 @code{name} is raised.  If @code{name} is omitted, then the execution is
18411 suspended when any exception is raised.
18412 @end table
18414 @item 
18416 @table @asis
18418 @item @code{print @var{expression}}
18420 This will print the value of the given expression. Most simple
18421 Ada expression formats are properly handled by @code{GDB}, so the expression
18422 can contain function calls, variables, operators, and attribute references.
18423 @end table
18425 @item 
18427 @table @asis
18429 @item @code{continue}
18431 Continues execution following a breakpoint, until the next breakpoint or the
18432 termination of the program.
18433 @end table
18435 @item 
18437 @table @asis
18439 @item @code{step}
18441 Executes a single line after a breakpoint. If the next statement
18442 is a subprogram call, execution continues into (the first statement of)
18443 the called subprogram.
18444 @end table
18446 @item 
18448 @table @asis
18450 @item @code{next}
18452 Executes a single line. If this line is a subprogram call, executes and
18453 returns from the call.
18454 @end table
18456 @item 
18458 @table @asis
18460 @item @code{list}
18462 Lists a few lines around the current source location. In practice, it
18463 is usually more convenient to have a separate edit window open with the
18464 relevant source file displayed. Successive applications of this command
18465 print subsequent lines. The command can be given an argument which is a
18466 line number, in which case it displays a few lines around the specified one.
18467 @end table
18469 @item 
18471 @table @asis
18473 @item @code{backtrace}
18475 Displays a backtrace of the call chain. This command is typically
18476 used after a breakpoint has occurred, to examine the sequence of calls that
18477 leads to the current breakpoint. The display includes one line for each
18478 activation record (frame) corresponding to an active subprogram.
18479 @end table
18481 @item 
18483 @table @asis
18485 @item @code{up}
18487 At a breakpoint, @code{GDB} can display the values of variables local
18488 to the current frame. The command @code{up} can be used to
18489 examine the contents of other active frames, by moving the focus up
18490 the stack, that is to say from callee to caller, one frame at a time.
18491 @end table
18493 @item 
18495 @table @asis
18497 @item @code{down}
18499 Moves the focus of @code{GDB} down from the frame currently being
18500 examined to the frame of its callee (the reverse of the previous command),
18501 @end table
18503 @item 
18505 @table @asis
18507 @item @code{frame @var{n}}
18509 Inspect the frame with the given number. The value 0 denotes the frame
18510 of the current breakpoint, that is to say the top of the call stack.
18511 @end table
18513 @item 
18515 @table @asis
18517 @item @code{kill}
18519 Kills the child process in which the program is running under GDB.
18520 This may be useful for several purposes:
18523 @itemize *
18525 @item 
18526 It allows you to recompile and relink your program, since on many systems
18527 you cannot regenerate an executable file while it is running in a process.
18529 @item 
18530 You can run your program outside the debugger, on systems that do not
18531 permit executing a program outside GDB while breakpoints are set
18532 within GDB.
18534 @item 
18535 It allows you to debug a core dump rather than a running process.
18536 @end itemize
18537 @end table
18538 @end itemize
18540 The above list is a very short introduction to the commands that
18541 @code{GDB} provides. Important additional capabilities, including conditional
18542 breakpoints, the ability to execute command sequences on a breakpoint,
18543 the ability to debug at the machine instruction level and many other
18544 features are described in detail in @cite{Debugging with GDB}.
18545 Note that most commands can be abbreviated
18546 (for example, c for continue, bt for backtrace).
18548 @node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
18549 @anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{156}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{157}
18550 @subsection Using Ada Expressions
18553 @geindex Ada expressions (in gdb)
18555 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18556 extensions. The philosophy behind the design of this subset is
18558 @quotation
18561 @itemize *
18563 @item 
18564 That @code{GDB} should provide basic literals and access to operations for
18565 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18566 leaving more sophisticated computations to subprograms written into the
18567 program (which therefore may be called from @code{GDB}).
18569 @item 
18570 That type safety and strict adherence to Ada language restrictions
18571 are not particularly relevant in a debugging context.
18573 @item 
18574 That brevity is important to the @code{GDB} user.
18575 @end itemize
18576 @end quotation
18578 Thus, for brevity, the debugger acts as if there were
18579 implicit @code{with} and @code{use} clauses in effect for all user-written
18580 packages, thus making it unnecessary to fully qualify most names with
18581 their packages, regardless of context. Where this causes ambiguity,
18582 @code{GDB} asks the user’s intent.
18584 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
18586 @node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
18587 @anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{158}@anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{159}
18588 @subsection Calling User-Defined Subprograms
18591 An important capability of @code{GDB} is the ability to call user-defined
18592 subprograms while debugging. This is achieved simply by entering
18593 a subprogram call statement in the form:
18595 @quotation
18597 @example
18598 call subprogram-name (parameters)
18599 @end example
18600 @end quotation
18602 The keyword @code{call} can be omitted in the normal case where the
18603 @code{subprogram-name} does not coincide with any of the predefined
18604 @code{GDB} commands.
18606 The effect is to invoke the given subprogram, passing it the
18607 list of parameters that is supplied. The parameters can be expressions and
18608 can include variables from the program being debugged. The
18609 subprogram must be defined
18610 at the library level within your program, and @code{GDB} will call the
18611 subprogram within the environment of your program execution (which
18612 means that the subprogram is free to access or even modify variables
18613 within your program).
18615 The most important use of this facility is in allowing the inclusion of
18616 debugging routines that are tailored to particular data structures
18617 in your program. Such debugging routines can be written to provide a suitably
18618 high-level description of an abstract type, rather than a low-level dump
18619 of its physical layout. After all, the standard
18620 @code{GDB print} command only knows the physical layout of your
18621 types, not their abstract meaning. Debugging routines can provide information
18622 at the desired semantic level and are thus enormously useful.
18624 For example, when debugging GNAT itself, it is crucial to have access to
18625 the contents of the tree nodes used to represent the program internally.
18626 But tree nodes are represented simply by an integer value (which in turn
18627 is an index into a table of nodes).
18628 Using the @code{print} command on a tree node would simply print this integer
18629 value, which is not very useful. But the PN routine (defined in file
18630 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18631 a useful high level representation of the tree node, which includes the
18632 syntactic category of the node, its position in the source, the integers
18633 that denote descendant nodes and parent node, as well as varied
18634 semantic information. To study this example in more detail, you might want to
18635 look at the body of the PN procedure in the stated file.
18637 Another useful application of this capability is to deal with situations of
18638 complex data which are not handled suitably by GDB. For example, if you specify
18639 Convention Fortran for a multi-dimensional array, GDB does not know that
18640 the ordering of array elements has been switched and will not properly
18641 address the array elements. In such a case, instead of trying to print the
18642 elements directly from GDB, you can write a callable procedure that prints
18643 the elements in the desired format.
18645 @node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
18646 @anchor{gnat_ugn/gnat_and_program_execution id8}@anchor{15a}@anchor{gnat_ugn/gnat_and_program_execution using-the-next-command-in-a-function}@anchor{15b}
18647 @subsection Using the `next' Command in a Function
18650 When you use the @code{next} command in a function, the current source
18651 location will advance to the next statement as usual. A special case
18652 arises in the case of a @code{return} statement.
18654 Part of the code for a return statement is the ‘epilogue’ of the function.
18655 This is the code that returns to the caller. There is only one copy of
18656 this epilogue code, and it is typically associated with the last return
18657 statement in the function if there is more than one return. In some
18658 implementations, this epilogue is associated with the first statement
18659 of the function.
18661 The result is that if you use the @code{next} command from a return
18662 statement that is not the last return statement of the function you
18663 may see a strange apparent jump to the last return statement or to
18664 the start of the function. You should simply ignore this odd jump.
18665 The value returned is always that from the first return statement
18666 that was stepped through.
18668 @node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
18669 @anchor{gnat_ugn/gnat_and_program_execution id9}@anchor{15c}@anchor{gnat_ugn/gnat_and_program_execution stopping-when-ada-exceptions-are-raised}@anchor{15d}
18670 @subsection Stopping When Ada Exceptions Are Raised
18673 @geindex Exceptions (in gdb)
18675 You can set catchpoints that stop the program execution when your program
18676 raises selected exceptions.
18679 @itemize *
18681 @item 
18683 @table @asis
18685 @item @code{catch exception}
18687 Set a catchpoint that stops execution whenever (any task in the) program
18688 raises any exception.
18689 @end table
18691 @item 
18693 @table @asis
18695 @item @code{catch exception @var{name}}
18697 Set a catchpoint that stops execution whenever (any task in the) program
18698 raises the exception `name'.
18699 @end table
18701 @item 
18703 @table @asis
18705 @item @code{catch exception unhandled}
18707 Set a catchpoint that stops executing whenever (any task in the) program
18708 raises an exception for which there is no handler.
18709 @end table
18711 @item 
18713 @table @asis
18715 @item @code{info exceptions}, @code{info exceptions @var{regexp}}
18717 The @code{info exceptions} command permits the user to examine all defined
18718 exceptions within Ada programs. With a regular expression, `regexp', as
18719 argument, prints out only those exceptions whose name matches `regexp'.
18720 @end table
18721 @end itemize
18723 @geindex Tasks (in gdb)
18725 @node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
18726 @anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{15e}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{15f}
18727 @subsection Ada Tasks
18730 @code{GDB} allows the following task-related commands:
18733 @itemize *
18735 @item 
18737 @table @asis
18739 @item @code{info tasks}
18741 This command shows a list of current Ada tasks, as in the following example:
18743 @example
18744 (gdb) info tasks
18745   ID       TID P-ID   Thread Pri State                 Name
18746    1   8088000   0   807e000  15 Child Activation Wait main_task
18747    2   80a4000   1   80ae000  15 Accept/Select Wait    b
18748    3   809a800   1   80a4800  15 Child Activation Wait a
18749 *  4   80ae800   3   80b8000  15 Running               c
18750 @end example
18752 In this listing, the asterisk before the first task indicates it to be the
18753 currently running task. The first column lists the task ID that is used
18754 to refer to tasks in the following commands.
18755 @end table
18756 @end itemize
18758 @geindex Breakpoints and tasks
18761 @itemize *
18763 @item 
18764 @code{break} `linespec' @code{task} `taskid', @code{break} `linespec' @code{task} `taskid' @code{if} …
18766 @quotation
18768 These commands are like the @code{break ... thread ...}.
18769 `linespec' specifies source lines.
18771 Use the qualifier @code{task @var{taskid}} with a breakpoint command
18772 to specify that you only want @code{GDB} to stop the program when a
18773 particular Ada task reaches this breakpoint. `taskid' is one of the
18774 numeric task identifiers assigned by @code{GDB}, shown in the first
18775 column of the @code{info tasks} display.
18777 If you do not specify @code{task @var{taskid}} when you set a
18778 breakpoint, the breakpoint applies to `all' tasks of your
18779 program.
18781 You can use the @code{task} qualifier on conditional breakpoints as
18782 well; in this case, place @code{task @var{taskid}} before the
18783 breakpoint condition (before the @code{if}).
18784 @end quotation
18785 @end itemize
18787 @geindex Task switching (in gdb)
18790 @itemize *
18792 @item 
18793 @code{task @var{taskno}}
18795 @quotation
18797 This command allows switching to the task referred by `taskno'. In
18798 particular, this allows browsing of the backtrace of the specified
18799 task. It is advisable to switch back to the original task before
18800 continuing execution otherwise the scheduling of the program may be
18801 perturbed.
18802 @end quotation
18803 @end itemize
18805 For more detailed information on the tasking support,
18806 see @cite{Debugging with GDB}.
18808 @geindex Debugging Generic Units
18810 @geindex Generics
18812 @node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
18813 @anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{160}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{161}
18814 @subsection Debugging Generic Units
18817 GNAT always uses code expansion for generic instantiation. This means that
18818 each time an instantiation occurs, a complete copy of the original code is
18819 made, with appropriate substitutions of formals by actuals.
18821 It is not possible to refer to the original generic entities in
18822 @code{GDB}, but it is always possible to debug a particular instance of
18823 a generic, by using the appropriate expanded names. For example, if we have
18825 @quotation
18827 @example
18828 procedure g is
18830    generic package k is
18831       procedure kp (v1 : in out integer);
18832    end k;
18834    package body k is
18835       procedure kp (v1 : in out integer) is
18836       begin
18837          v1 := v1 + 1;
18838       end kp;
18839    end k;
18841    package k1 is new k;
18842    package k2 is new k;
18844    var : integer := 1;
18846 begin
18847    k1.kp (var);
18848    k2.kp (var);
18849    k1.kp (var);
18850    k2.kp (var);
18851 end;
18852 @end example
18853 @end quotation
18855 Then to break on a call to procedure kp in the k2 instance, simply
18856 use the command:
18858 @quotation
18860 @example
18861 (gdb) break g.k2.kp
18862 @end example
18863 @end quotation
18865 When the breakpoint occurs, you can step through the code of the
18866 instance in the normal manner and examine the values of local variables, as for
18867 other units.
18869 @geindex Remote Debugging with gdbserver
18871 @node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
18872 @anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{162}@anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{163}
18873 @subsection Remote Debugging with gdbserver
18876 On platforms where gdbserver is supported, it is possible to use this tool
18877 to debug your application remotely.  This can be useful in situations
18878 where the program needs to be run on a target host that is different
18879 from the host used for development, particularly when the target has
18880 a limited amount of resources (either CPU and/or memory).
18882 To do so, start your program using gdbserver on the target machine.
18883 gdbserver then automatically suspends the execution of your program
18884 at its entry point, waiting for a debugger to connect to it.  The
18885 following commands starts an application and tells gdbserver to
18886 wait for a connection with the debugger on localhost port 4444.
18888 @quotation
18890 @example
18891 $ gdbserver localhost:4444 program
18892 Process program created; pid = 5685
18893 Listening on port 4444
18894 @end example
18895 @end quotation
18897 Once gdbserver has started listening, we can tell the debugger to establish
18898 a connection with this gdbserver, and then start the same debugging session
18899 as if the program was being debugged on the same host, directly under
18900 the control of GDB.
18902 @quotation
18904 @example
18905 $ gdb program
18906 (gdb) target remote targethost:4444
18907 Remote debugging using targethost:4444
18908 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
18909 (gdb) b foo.adb:3
18910 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
18911 (gdb) continue
18912 Continuing.
18914 Breakpoint 1, foo () at foo.adb:4
18915 4       end foo;
18916 @end example
18917 @end quotation
18919 It is also possible to use gdbserver to attach to an already running
18920 program, in which case the execution of that program is simply suspended
18921 until the connection between the debugger and gdbserver is established.
18923 For more information on how to use gdbserver, see the `Using the gdbserver Program'
18924 section in @cite{Debugging with GDB}.
18925 GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
18927 @geindex Abnormal Termination or Failure to Terminate
18929 @node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
18930 @anchor{gnat_ugn/gnat_and_program_execution gnat-abnormal-termination-or-failure-to-terminate}@anchor{164}@anchor{gnat_ugn/gnat_and_program_execution id13}@anchor{165}
18931 @subsection GNAT Abnormal Termination or Failure to Terminate
18934 When presented with programs that contain serious errors in syntax
18935 or semantics,
18936 GNAT may on rare occasions  experience problems in operation, such
18937 as aborting with a
18938 segmentation fault or illegal memory access, raising an internal
18939 exception, terminating abnormally, or failing to terminate at all.
18940 In such cases, you can activate
18941 various features of GNAT that can help you pinpoint the construct in your
18942 program that is the likely source of the problem.
18944 The following strategies are presented in increasing order of
18945 difficulty, corresponding to your experience in using GNAT and your
18946 familiarity with compiler internals.
18949 @itemize *
18951 @item 
18952 Run @code{gcc} with the @code{-gnatf}. This first
18953 switch causes all errors on a given line to be reported. In its absence,
18954 only the first error on a line is displayed.
18956 The @code{-gnatdO} switch causes errors to be displayed as soon as they
18957 are encountered, rather than after compilation is terminated. If GNAT
18958 terminates prematurely or goes into an infinite loop, the last error
18959 message displayed may help to pinpoint the culprit.
18961 @item 
18962 Run @code{gcc} with the @code{-v} (verbose) switch. In this
18963 mode, @code{gcc} produces ongoing information about the progress of the
18964 compilation and provides the name of each procedure as code is
18965 generated. This switch allows you to find which Ada procedure was being
18966 compiled when it encountered a code generation problem.
18967 @end itemize
18969 @geindex -gnatdc switch
18972 @itemize *
18974 @item 
18975 Run @code{gcc} with the @code{-gnatdc} switch. This is a GNAT specific
18976 switch that does for the front-end what @code{-v} does
18977 for the back end. The system prints the name of each unit,
18978 either a compilation unit or nested unit, as it is being analyzed.
18980 @item 
18981 Finally, you can start
18982 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
18983 front-end of GNAT, and can be run independently (normally it is just
18984 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
18985 would on a C program (but @ref{151,,The GNAT Debugger GDB} for caveats). The
18986 @code{where} command is the first line of attack; the variable
18987 @code{lineno} (seen by @code{print lineno}), used by the second phase of
18988 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
18989 which the execution stopped, and @code{input_file name} indicates the name of
18990 the source file.
18991 @end itemize
18993 @node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
18994 @anchor{gnat_ugn/gnat_and_program_execution id14}@anchor{166}@anchor{gnat_ugn/gnat_and_program_execution naming-conventions-for-gnat-source-files}@anchor{167}
18995 @subsection Naming Conventions for GNAT Source Files
18998 In order to examine the workings of the GNAT system, the following
18999 brief description of its organization may be helpful:
19002 @itemize *
19004 @item 
19005 Files with prefix @code{sc} contain the lexical scanner.
19007 @item 
19008 All files prefixed with @code{par} are components of the parser. The
19009 numbers correspond to chapters of the Ada Reference Manual. For example,
19010 parsing of select statements can be found in @code{par-ch9.adb}.
19012 @item 
19013 All files prefixed with @code{sem} perform semantic analysis. The
19014 numbers correspond to chapters of the Ada standard. For example, all
19015 issues involving context clauses can be found in @code{sem_ch10.adb}. In
19016 addition, some features of the language require sufficient special processing
19017 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19018 dynamic dispatching, etc.
19020 @item 
19021 All files prefixed with @code{exp} perform normalization and
19022 expansion of the intermediate representation (abstract syntax tree, or AST).
19023 these files use the same numbering scheme as the parser and semantics files.
19024 For example, the construction of record initialization procedures is done in
19025 @code{exp_ch3.adb}.
19027 @item 
19028 The files prefixed with @code{bind} implement the binder, which
19029 verifies the consistency of the compilation, determines an order of
19030 elaboration, and generates the bind file.
19032 @item 
19033 The files @code{atree.ads} and @code{atree.adb} detail the low-level
19034 data structures used by the front-end.
19036 @item 
19037 The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
19038 the abstract syntax tree as produced by the parser.
19040 @item 
19041 The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
19042 all entities, computed during semantic analysis.
19044 @item 
19045 Library management issues are dealt with in files with prefix
19046 @code{lib}.
19048 @geindex Annex A (in Ada Reference Manual)
19050 @item 
19051 Ada files with the prefix @code{a-} are children of @code{Ada}, as
19052 defined in Annex A.
19054 @geindex Annex B (in Ada reference Manual)
19056 @item 
19057 Files with prefix @code{i-} are children of @code{Interfaces}, as
19058 defined in Annex B.
19060 @geindex System (package in Ada Reference Manual)
19062 @item 
19063 Files with prefix @code{s-} are children of @code{System}. This includes
19064 both language-defined children and GNAT run-time routines.
19066 @geindex GNAT (package)
19068 @item 
19069 Files with prefix @code{g-} are children of @code{GNAT}. These are useful
19070 general-purpose packages, fully documented in their specs. All
19071 the other @code{.c} files are modifications of common @code{gcc} files.
19072 @end itemize
19074 @node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
19075 @anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{168}@anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{169}
19076 @subsection Getting Internal Debugging Information
19079 Most compilers have internal debugging switches and modes. GNAT
19080 does also, except GNAT internal debugging switches and modes are not
19081 secret. A summary and full description of all the compiler and binder
19082 debug flags are in the file @code{debug.adb}. You must obtain the
19083 sources of the compiler to see the full detailed effects of these flags.
19085 The switches that print the source of the program (reconstructed from
19086 the internal tree) are of general interest for user programs, as are the
19087 options to print
19088 the full internal tree, and the entity table (the symbol table
19089 information). The reconstructed source provides a readable version of the
19090 program after the front-end has completed analysis and  expansion,
19091 and is useful when studying the performance of specific constructs.
19092 For example, constraint checks are indicated, complex aggregates
19093 are replaced with loops and assignments, and tasking primitives
19094 are replaced with run-time calls.
19096 @geindex traceback
19098 @geindex stack traceback
19100 @geindex stack unwinding
19102 @node Stack Traceback,Pretty-Printers for the GNAT runtime,Getting Internal Debugging Information,Running and Debugging Ada Programs
19103 @anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{16a}@anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{16b}
19104 @subsection Stack Traceback
19107 Traceback is a mechanism to display the sequence of subprogram calls that
19108 leads to a specified execution point in a program. Often (but not always)
19109 the execution point is an instruction at which an exception has been raised.
19110 This mechanism is also known as `stack unwinding' because it obtains
19111 its information by scanning the run-time stack and recovering the activation
19112 records of all active subprograms. Stack unwinding is one of the most
19113 important tools for program debugging.
19115 The first entry stored in traceback corresponds to the deepest calling level,
19116 that is to say the subprogram currently executing the instruction
19117 from which we want to obtain the traceback.
19119 Note that there is no runtime performance penalty when stack traceback
19120 is enabled, and no exception is raised during program execution.
19122 @geindex traceback
19123 @geindex non-symbolic
19125 @menu
19126 * Non-Symbolic Traceback:: 
19127 * Symbolic Traceback:: 
19129 @end menu
19131 @node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
19132 @anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{16c}@anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{16d}
19133 @subsubsection Non-Symbolic Traceback
19136 Note: this feature is not supported on all platforms. See
19137 @code{GNAT.Traceback} spec in @code{g-traceb.ads}
19138 for a complete list of supported platforms.
19140 @subsubheading Tracebacks From an Unhandled Exception
19143 A runtime non-symbolic traceback is a list of addresses of call instructions.
19144 To enable this feature you must use the @code{-E} @code{gnatbind} option. With
19145 this option a stack traceback is stored as part of exception information.
19147 You can translate this information using the @code{addr2line} tool, provided that
19148 the program is compiled with debugging options (see @ref{dd,,Compiler Switches})
19149 and linked at a fixed position with @code{-no-pie}.
19151 Here is a simple example with @code{gnatmake}:
19153 @quotation
19155 @example
19156 procedure STB is
19158    procedure P1 is
19159    begin
19160       raise Constraint_Error;
19161    end P1;
19163    procedure P2 is
19164    begin
19165       P1;
19166    end P2;
19168 begin
19169    P2;
19170 end STB;
19171 @end example
19173 @example
19174 $ gnatmake stb -g -bargs -E -largs -no-pie
19175 $ stb
19177 Execution of stb terminated by unhandled exception
19178 raised CONSTRAINT_ERROR : stb.adb:5 explicit raise
19179 Load address: 0x400000
19180 Call stack traceback locations:
19181 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19182 @end example
19183 @end quotation
19185 As we see the traceback lists a sequence of addresses for the unhandled
19186 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19187 guess that this exception come from procedure P1. To translate these
19188 addresses into the source lines where the calls appear, the @code{addr2line}
19189 tool needs to be invoked like this:
19191 @quotation
19193 @example
19194 $ addr2line -e stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19195    0x4011f1 0x77e892a4
19197 d:/stb/stb.adb:5
19198 d:/stb/stb.adb:10
19199 d:/stb/stb.adb:14
19200 d:/stb/b~stb.adb:197
19201 crtexe.c:?
19202 crtexe.c:?
19203 ??:0
19204 @end example
19205 @end quotation
19207 The @code{addr2line} tool has several other useful options:
19209 @quotation
19212 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
19213 @item
19215 @code{-a --addresses}
19217 @tab
19219 to show the addresses alongside the line numbers
19221 @item
19223 @code{-f --functions}
19225 @tab
19227 to get the function name corresponding to a location
19229 @item
19231 @code{-p --pretty-print}
19233 @tab
19235 to print all the information on a single line
19237 @item
19239 @code{--demangle=gnat}
19241 @tab
19243 to use the GNAT decoding mode for the function names
19245 @end multitable
19248 @example
19249 $ addr2line -e stb -a -f -p --demangle=gnat 0x401373 0x40138b
19250    0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19252 0x00401373: stb.p1 at d:/stb/stb.adb:5
19253 0x0040138B: stb.p2 at d:/stb/stb.adb:10
19254 0x0040139C: stb at d:/stb/stb.adb:14
19255 0x00401335: main at d:/stb/b~stb.adb:197
19256 0x004011c4: ?? at crtexe.c:?
19257 0x004011f1: ?? at crtexe.c:?
19258 0x77e892a4: ?? ??:0
19259 @end example
19260 @end quotation
19262 From this traceback we can see that the exception was raised in @code{stb.adb}
19263 at line 5, which was reached from a procedure call in @code{stb.adb} at line
19264 10, and so on. The @code{b~std.adb} is the binder file, which contains the
19265 call to the main program. @ref{110,,Running gnatbind}. The remaining entries are
19266 assorted runtime routines and the output will vary from platform to platform.
19268 It is also possible to use @code{GDB} with these traceback addresses to debug
19269 the program. For example, we can break at a given code location, as reported
19270 in the stack traceback:
19272 @example
19273 $ gdb -nw stb
19275 (gdb) break *0x401373
19276 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19277 @end example
19279 It is important to note that the stack traceback addresses do not change when
19280 debug information is included. This is particularly useful because it makes it
19281 possible to release software without debug information (to minimize object
19282 size), get a field report that includes a stack traceback whenever an internal
19283 bug occurs, and then be able to retrieve the sequence of calls with the same
19284 program compiled with debug information.
19286 However the @code{addr2line} tool does not work with Position-Independent Code
19287 (PIC), the historical example being Linux dynamic libraries and Windows DLLs,
19288 which nowadays encompasse Position-Independent Executables (PIE) on recent
19289 Linux and Windows versions.
19291 In order to translate addresses the source lines with Position-Independent
19292 Executables on recent Linux and Windows versions, in other words without
19293 using the switch @code{-no-pie} during linking, you need to use the
19294 @code{gnatsymbolize} tool with @code{--load} instead of the @code{addr2line}
19295 tool. The main difference is that you need to copy the Load Address output
19296 in the traceback ahead of the sequence of addresses. And the default mode
19297 of @code{gnatsymbolize} is equivalent to that of @code{addr2line} with the above
19298 switches, so none of them is needed:
19300 @example
19301 $ gnatmake stb -g -bargs -E
19302 $ stb
19304 Execution of stb terminated by unhandled exception
19305 raised CONSTRAINT_ERROR : stb.adb:5 explicit raise
19306 Load address: 0x400000
19307 Call stack traceback locations:
19308 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19310 $ gnatsymbolize --load stb 0x400000 0x401373 0x40138b 0x40139c 0x401335 \
19311    0x4011c4 0x4011f1 0x77e892a4
19313 0x00401373 Stb.P1 at stb.adb:5
19314 0x0040138B Stb.P2 at stb.adb:10
19315 0x0040139C Stb at stb.adb:14
19316 0x00401335 Main at b~stb.adb:197
19317 0x004011c4 __tmainCRTStartup at ???
19318 0x004011f1 mainCRTStartup at ???
19319 0x77e892a4 ??? at ???
19320 @end example
19322 @subsubheading Tracebacks From Exception Occurrences
19325 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
19326 The stack traceback is attached to the exception information string, and can
19327 be retrieved in an exception handler within the Ada program, by means of the
19328 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19330 @quotation
19332 @example
19333 with Ada.Text_IO;
19334 with Ada.Exceptions;
19336 procedure STB is
19338    use Ada;
19339    use Ada.Exceptions;
19341    procedure P1 is
19342       K : Positive := 1;
19343    begin
19344       K := K - 1;
19345    exception
19346       when E : others =>
19347          Text_IO.Put_Line (Exception_Information (E));
19348    end P1;
19350    procedure P2 is
19351    begin
19352       P1;
19353    end P2;
19355 begin
19356    P2;
19357 end STB;
19358 @end example
19360 @example
19361 $ gnatmake stb -g -bargs -E -largs -no-pie
19362 $ stb
19364 raised CONSTRAINT_ERROR : stb.adb:12 range check failed
19365 Load address: 0x400000
19366 Call stack traceback locations:
19367 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19368 @end example
19369 @end quotation
19371 @subsubheading Tracebacks From Anywhere in a Program
19374 It is also possible to retrieve a stack traceback from anywhere in a program.
19375 For this you need to use the @code{GNAT.Traceback} API. This package includes a
19376 procedure called @code{Call_Chain} that computes a complete stack traceback, as
19377 well as useful display procedures described below. It is not necessary to use
19378 the @code{-E} @code{gnatbind} option in this case, because the stack traceback
19379 mechanism is invoked explicitly.
19381 In the following example we compute a traceback at a specific location in the
19382 program, and we display it using @code{GNAT.Debug_Utilities.Image} to convert
19383 addresses to strings:
19385 @quotation
19387 @example
19388 with Ada.Text_IO;
19389 with GNAT.Traceback;
19390 with GNAT.Debug_Utilities;
19391 with System;
19393 procedure STB is
19395    use Ada;
19396    use Ada.Text_IO;
19397    use GNAT;
19398    use GNAT.Traceback;
19399    use System;
19401    LA : constant Address := Executable_Load_Address;
19403    procedure P1 is
19404       TB  : Tracebacks_Array (1 .. 10);
19405       --  We are asking for a maximum of 10 stack frames.
19406       Len : Natural;
19407       --  Len will receive the actual number of stack frames returned.
19408    begin
19409       Call_Chain (TB, Len);
19411       Put ("In STB.P1 : ");
19413       for K in 1 .. Len loop
19414          Put (Debug_Utilities.Image_C (TB (K)));
19415          Put (' ');
19416       end loop;
19418       New_Line;
19419    end P1;
19421    procedure P2 is
19422    begin
19423       P1;
19424    end P2;
19426 begin
19427    if LA /= Null_Address then
19428       Put_Line ("Load address: " & Debug_Utilities.Image_C (LA));
19429    end if;
19431    P2;
19432 end STB;
19433 @end example
19435 @example
19436 $ gnatmake stb -g
19437 $ stb
19439 Load address: 0x400000
19440 In STB.P1 : 0x40F1E4 0x4014F2 0x40170B 0x40171C 0x401461 0x4011C4 \
19441   0x4011F1 0x77E892A4
19442 @end example
19443 @end quotation
19445 You can then get further information by invoking the @code{addr2line} tool or
19446 the @code{gnatsymbolize} tool as described earlier (note that the hexadecimal
19447 addresses need to be specified in C format, with a leading ‘0x’).
19449 @geindex traceback
19450 @geindex symbolic
19452 @node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
19453 @anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{16e}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{16f}
19454 @subsubsection Symbolic Traceback
19457 A symbolic traceback is a stack traceback in which procedure names are
19458 associated with each code location.
19460 Note that this feature is not supported on all platforms. See
19461 @code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
19462 list of currently supported platforms.
19464 Note that the symbolic traceback requires that the program be compiled
19465 with debug information. If it is not compiled with debug information
19466 only the non-symbolic information will be valid.
19468 @subsubheading Tracebacks From Exception Occurrences
19471 Here is an example:
19473 @quotation
19475 @example
19476 with Ada.Text_IO;
19477 with GNAT.Traceback.Symbolic;
19479 procedure STB is
19481    procedure P1 is
19482    begin
19483       raise Constraint_Error;
19484    end P1;
19486    procedure P2 is
19487    begin
19488       P1;
19489    end P2;
19491    procedure P3 is
19492    begin
19493       P2;
19494    end P3;
19496 begin
19497    P3;
19498 exception
19499    when E : others =>
19500       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19501 end STB;
19502 @end example
19504 @example
19505 $ gnatmake -g stb -bargs -E
19506 $ stb
19508 0040149F in stb.p1 at stb.adb:8
19509 004014B7 in stb.p2 at stb.adb:13
19510 004014CF in stb.p3 at stb.adb:18
19511 004015DD in ada.stb at stb.adb:22
19512 00401461 in main at b~stb.adb:168
19513 004011C4 in __mingw_CRTStartup at crt1.c:200
19514 004011F1 in mainCRTStartup at crt1.c:222
19515 77E892A4 in ?? at ??:0
19516 @end example
19517 @end quotation
19519 @subsubheading Tracebacks From Anywhere in a Program
19522 It is possible to get a symbolic stack traceback
19523 from anywhere in a program, just as for non-symbolic tracebacks.
19524 The first step is to obtain a non-symbolic
19525 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19526 information. Here is an example:
19528 @quotation
19530 @example
19531 with Ada.Text_IO;
19532 with GNAT.Traceback;
19533 with GNAT.Traceback.Symbolic;
19535 procedure STB is
19537    use Ada;
19538    use GNAT.Traceback;
19539    use GNAT.Traceback.Symbolic;
19541    procedure P1 is
19542       TB  : Tracebacks_Array (1 .. 10);
19543       --  We are asking for a maximum of 10 stack frames.
19544       Len : Natural;
19545       --  Len will receive the actual number of stack frames returned.
19546    begin
19547       Call_Chain (TB, Len);
19548       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19549    end P1;
19551    procedure P2 is
19552    begin
19553       P1;
19554    end P2;
19556 begin
19557    P2;
19558 end STB;
19559 @end example
19560 @end quotation
19562 @subsubheading Automatic Symbolic Tracebacks
19565 Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
19566 in @code{gprbuild -g ... -bargs -Es}).
19567 This will cause the Exception_Information to contain a symbolic traceback,
19568 which will also be printed if an unhandled exception terminates the
19569 program.
19571 @node Pretty-Printers for the GNAT runtime,,Stack Traceback,Running and Debugging Ada Programs
19572 @anchor{gnat_ugn/gnat_and_program_execution id19}@anchor{170}@anchor{gnat_ugn/gnat_and_program_execution pretty-printers-for-the-gnat-runtime}@anchor{171}
19573 @subsection Pretty-Printers for the GNAT runtime
19576 As discussed in @cite{Calling User-Defined Subprograms}, GDB’s
19577 @code{print} command only knows about the physical layout of program data
19578 structures and therefore normally displays only low-level dumps, which
19579 are often hard to understand.
19581 An example of this is when trying to display the contents of an Ada
19582 standard container, such as @code{Ada.Containers.Ordered_Maps.Map}:
19584 @quotation
19586 @example
19587 with Ada.Containers.Ordered_Maps;
19589 procedure PP is
19590    package Int_To_Nat is
19591       new Ada.Containers.Ordered_Maps (Integer, Natural);
19593    Map : Int_To_Nat.Map;
19594 begin
19595    Map.Insert (1, 10);
19596    Map.Insert (2, 20);
19597    Map.Insert (3, 30);
19599    Map.Clear; --  BREAK HERE
19600 end PP;
19601 @end example
19602 @end quotation
19604 When this program is built with debugging information and run under
19605 GDB up to the @code{Map.Clear} statement, trying to print @code{Map} will
19606 yield information that is only relevant to the developers of our standard
19607 containers:
19609 @quotation
19611 @example
19612 (gdb) print map
19613 $1 = (
19614   tree => (
19615     first => 0x64e010,
19616     last => 0x64e070,
19617     root => 0x64e040,
19618     length => 3,
19619     tc => (
19620       busy => 0,
19621       lock => 0
19622     )
19623   )
19625 @end example
19626 @end quotation
19628 Fortunately, GDB has a feature called pretty-printers@footnote{http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Introduction},
19629 which allows customizing how GDB displays data structures. The GDB
19630 shipped with GNAT embeds such pretty-printers for the most common
19631 containers in the standard library.  To enable them, either run the
19632 following command manually under GDB or add it to your @code{.gdbinit} file:
19634 @quotation
19636 @example
19637 python import gnatdbg; gnatdbg.setup()
19638 @end example
19639 @end quotation
19641 Once this is done, GDB’s @code{print} command will automatically use
19642 these pretty-printers when appropriate. Using the previous example:
19644 @quotation
19646 @example
19647 (gdb) print map
19648 $1 = pp.int_to_nat.map of length 3 = @{
19649   [1] = 10,
19650   [2] = 20,
19651   [3] = 30
19653 @end example
19654 @end quotation
19656 Pretty-printers are invoked each time GDB tries to display a value,
19657 including when displaying the arguments of a called subprogram (in
19658 GDB’s @code{backtrace} command) or when printing the value returned by a
19659 function (in GDB’s @code{finish} command).
19661 To display a value without involving pretty-printers, @code{print} can be
19662 invoked with its @code{/r} option:
19664 @quotation
19666 @example
19667 (gdb) print/r map
19668 $1 = (
19669   tree => (...
19670 @end example
19671 @end quotation
19673 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}
19674 for more information.
19676 @geindex Profiling
19678 @node Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
19679 @anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{172}@anchor{gnat_ugn/gnat_and_program_execution profiling}@anchor{149}
19680 @section Profiling
19683 This section describes how to use the @code{gprof} profiler tool on Ada programs.
19685 @geindex gprof
19687 @geindex Profiling
19689 @menu
19690 * Profiling an Ada Program with gprof:: 
19692 @end menu
19694 @node Profiling an Ada Program with gprof,,,Profiling
19695 @anchor{gnat_ugn/gnat_and_program_execution id21}@anchor{173}@anchor{gnat_ugn/gnat_and_program_execution profiling-an-ada-program-with-gprof}@anchor{174}
19696 @subsection Profiling an Ada Program with gprof
19699 This section is not meant to be an exhaustive documentation of @code{gprof}.
19700 Full documentation for it can be found in the @cite{GNU Profiler User’s Guide}
19701 documentation that is part of this GNAT distribution.
19703 Profiling a program helps determine the parts of a program that are executed
19704 most often, and are therefore the most time-consuming.
19706 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
19707 better handle Ada programs and multitasking.
19708 It is currently supported on the following platforms
19711 @itemize *
19713 @item 
19714 Linux x86/x86_64
19716 @item 
19717 Windows x86/x86_64 (without PIE support)
19718 @end itemize
19720 In order to profile a program using @code{gprof}, several steps are needed:
19723 @enumerate 
19725 @item 
19726 Instrument the code, which requires a full recompilation of the project with the
19727 proper switches.
19729 @item 
19730 Execute the program under the analysis conditions, i.e. with the desired
19731 input.
19733 @item 
19734 Analyze the results using the @code{gprof} tool.
19735 @end enumerate
19737 The following sections detail the different steps, and indicate how
19738 to interpret the results.
19740 @menu
19741 * Compilation for profiling:: 
19742 * Program execution:: 
19743 * Running gprof:: 
19744 * Interpretation of profiling results:: 
19746 @end menu
19748 @node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
19749 @anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{175}@anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{176}
19750 @subsubsection Compilation for profiling
19753 @geindex -pg (gcc)
19754 @geindex for profiling
19756 @geindex -pg (gnatlink)
19757 @geindex for profiling
19759 In order to profile a program the first step is to tell the compiler
19760 to generate the necessary profiling information. The compiler switch to be used
19761 is @code{-pg}, which must be added to other compilation switches. This
19762 switch needs to be specified both during compilation and link stages, and can
19763 be specified once when using gnatmake:
19765 @quotation
19767 @example
19768 $ gnatmake -f -pg -P my_project
19769 @end example
19770 @end quotation
19772 Note that only the objects that were compiled with the @code{-pg} switch will
19773 be profiled; if you need to profile your whole project, use the @code{-f}
19774 gnatmake switch to force full recompilation.
19776 Note that on Windows, gprof does not support PIE. The @code{-no-pie} switch
19777 should be added to the linker flags to disable this feature.
19779 @node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
19780 @anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{177}@anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{178}
19781 @subsubsection Program execution
19784 Once the program has been compiled for profiling, you can run it as usual.
19786 The only constraint imposed by profiling is that the program must terminate
19787 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
19788 properly analyzed.
19790 Once the program completes execution, a data file called @code{gmon.out} is
19791 generated in the directory where the program was launched from. If this file
19792 already exists, it will be overwritten.
19794 @node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
19795 @anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{179}@anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{17a}
19796 @subsubsection Running gprof
19799 The @code{gprof} tool is called as follow:
19801 @quotation
19803 @example
19804 $ gprof my_prog gmon.out
19805 @end example
19806 @end quotation
19808 or simply:
19810 @quotation
19812 @example
19813 $ gprof my_prog
19814 @end example
19815 @end quotation
19817 The complete form of the gprof command line is the following:
19819 @quotation
19821 @example
19822 $ gprof [switches] [executable [data-file]]
19823 @end example
19824 @end quotation
19826 @code{gprof} supports numerous switches. The order of these
19827 switch does not matter. The full list of options can be found in
19828 the GNU Profiler User’s Guide documentation that comes with this documentation.
19830 The following is the subset of those switches that is most relevant:
19832 @geindex --demangle (gprof)
19835 @table @asis
19837 @item @code{--demangle[=@var{style}]}, @code{--no-demangle}
19839 These options control whether symbol names should be demangled when
19840 printing output.  The default is to demangle C++ symbols.  The
19841 @code{--no-demangle} option may be used to turn off demangling. Different
19842 compilers have different mangling styles.  The optional demangling style
19843 argument can be used to choose an appropriate demangling style for your
19844 compiler, in particular Ada symbols generated by GNAT can be demangled using
19845 @code{--demangle=gnat}.
19846 @end table
19848 @geindex -e (gprof)
19851 @table @asis
19853 @item @code{-e @var{function_name}}
19855 The @code{-e @var{function}} option tells @code{gprof} not to print
19856 information about the function @code{function_name} (and its
19857 children…) in the call graph.  The function will still be listed
19858 as a child of any functions that call it, but its index number will be
19859 shown as @code{[not printed]}.  More than one @code{-e} option may be
19860 given; only one @code{function_name} may be indicated with each @code{-e}
19861 option.
19862 @end table
19864 @geindex -E (gprof)
19867 @table @asis
19869 @item @code{-E @var{function_name}}
19871 The @code{-E @var{function}} option works like the @code{-e} option, but
19872 execution time spent in the function (and children who were not called from
19873 anywhere else), will not be used to compute the percentages-of-time for
19874 the call graph.  More than one @code{-E} option may be given; only one
19875 @code{function_name} may be indicated with each @code{-E`} option.
19876 @end table
19878 @geindex -f (gprof)
19881 @table @asis
19883 @item @code{-f @var{function_name}}
19885 The @code{-f @var{function}} option causes @code{gprof} to limit the
19886 call graph to the function @code{function_name} and its children (and
19887 their children…).  More than one @code{-f} option may be given;
19888 only one @code{function_name} may be indicated with each @code{-f}
19889 option.
19890 @end table
19892 @geindex -F (gprof)
19895 @table @asis
19897 @item @code{-F @var{function_name}}
19899 The @code{-F @var{function}} option works like the @code{-f} option, but
19900 only time spent in the function and its children (and their
19901 children…) will be used to determine total-time and
19902 percentages-of-time for the call graph.  More than one @code{-F} option
19903 may be given; only one @code{function_name} may be indicated with each
19904 @code{-F} option.  The @code{-F} option overrides the @code{-E} option.
19905 @end table
19907 @node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
19908 @anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{17b}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{17c}
19909 @subsubsection Interpretation of profiling results
19912 The results of the profiling analysis are represented by two arrays: the
19913 ‘flat profile’ and the ‘call graph’. Full documentation of those outputs
19914 can be found in the GNU Profiler User’s Guide.
19916 The flat profile shows the time spent in each function of the program, and how
19917 many time it has been called. This allows you to locate easily the most
19918 time-consuming functions.
19920 The call graph shows, for each subprogram, the subprograms that call it,
19921 and the subprograms that it calls. It also provides an estimate of the time
19922 spent in each of those callers/called subprograms.
19924 @node Improving Performance,Overflow Check Handling in GNAT,Profiling,GNAT and Program Execution
19925 @anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{14a}@anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{17d}
19926 @section Improving Performance
19929 @geindex Improving performance
19931 This section presents several topics related to program performance.
19932 It first describes some of the tradeoffs that need to be considered
19933 and some of the techniques for making your program run faster.
19935 It then documents the unused subprogram/data elimination feature,
19936 which can reduce the size of program executables.
19938 @menu
19939 * Performance Considerations:: 
19940 * Text_IO Suggestions:: 
19941 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
19943 @end menu
19945 @node Performance Considerations,Text_IO Suggestions,,Improving Performance
19946 @anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{17e}@anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{17f}
19947 @subsection Performance Considerations
19950 The GNAT system provides a number of options that allow a trade-off
19951 between
19954 @itemize *
19956 @item 
19957 performance of the generated code
19959 @item 
19960 speed of compilation
19962 @item 
19963 minimization of dependences and recompilation
19965 @item 
19966 the degree of run-time checking.
19967 @end itemize
19969 The defaults (if no options are selected) aim at improving the speed
19970 of compilation and minimizing dependences, at the expense of performance
19971 of the generated code:
19974 @itemize *
19976 @item 
19977 no optimization
19979 @item 
19980 no inlining of subprogram calls
19982 @item 
19983 all run-time checks enabled except overflow and elaboration checks
19984 @end itemize
19986 These options are suitable for most program development purposes. This
19987 section describes how you can modify these choices, and also provides
19988 some guidelines on debugging optimized code.
19990 @menu
19991 * Controlling Run-Time Checks:: 
19992 * Use of Restrictions:: 
19993 * Optimization Levels:: 
19994 * Debugging Optimized Code:: 
19995 * Inlining of Subprograms:: 
19996 * Floating Point Operations:: 
19997 * Vectorization of loops:: 
19998 * Other Optimization Switches:: 
19999 * Optimization and Strict Aliasing:: 
20000 * Aliased Variables and Optimization:: 
20001 * Atomic Variables and Optimization:: 
20002 * Passive Task Optimization:: 
20004 @end menu
20006 @node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
20007 @anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{180}@anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{181}
20008 @subsubsection Controlling Run-Time Checks
20011 By default, GNAT generates all run-time checks, except stack overflow
20012 checks, and checks for access before elaboration on subprogram
20013 calls. The latter are not required in default mode, because all
20014 necessary checking is done at compile time.
20016 @geindex -gnatp (gcc)
20018 @geindex -gnato (gcc)
20020 The gnat switch, @code{-gnatp} allows this default to be modified. See
20021 @ref{ec,,Run-Time Checks}.
20023 Our experience is that the default is suitable for most development
20024 purposes.
20026 Elaboration checks are off by default, and also not needed by default, since
20027 GNAT uses a static elaboration analysis approach that avoids the need for
20028 run-time checking. This manual contains a full chapter discussing the issue
20029 of elaboration checks, and if the default is not satisfactory for your use,
20030 you should read this chapter.
20032 For validity checks, the minimal checks required by the Ada Reference
20033 Manual (for case statements and assignments to array elements) are on
20034 by default. These can be suppressed by use of the @code{-gnatVn} switch.
20035 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
20036 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
20037 it may be reasonable to routinely use @code{-gnatVn}. Validity checks
20038 are also suppressed entirely if @code{-gnatp} is used.
20040 @geindex Overflow checks
20042 @geindex Checks
20043 @geindex overflow
20045 @geindex Suppress
20047 @geindex Unsuppress
20049 @geindex pragma Suppress
20051 @geindex pragma Unsuppress
20053 Note that the setting of the switches controls the default setting of
20054 the checks. They may be modified using either @code{pragma Suppress} (to
20055 remove checks) or @code{pragma Unsuppress} (to add back suppressed
20056 checks) in the program source.
20058 @node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
20059 @anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{182}@anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{183}
20060 @subsubsection Use of Restrictions
20063 The use of pragma Restrictions allows you to control which features are
20064 permitted in your program. Apart from the obvious point that if you avoid
20065 relatively expensive features like finalization (enforceable by the use
20066 of pragma Restrictions (No_Finalization)), the use of this pragma does not
20067 affect the generated code in most cases.
20069 One notable exception to this rule is that the possibility of task abort
20070 results in some distributed overhead, particularly if finalization or
20071 exception handlers are used. The reason is that certain sections of code
20072 have to be marked as non-abortable.
20074 If you use neither the @code{abort} statement, nor asynchronous transfer
20075 of control (@code{select ... then abort}), then this distributed overhead
20076 is removed, which may have a general positive effect in improving
20077 overall performance.  Especially code involving frequent use of tasking
20078 constructs and controlled types will show much improved performance.
20079 The relevant restrictions pragmas are
20081 @quotation
20083 @example
20084 pragma Restrictions (No_Abort_Statements);
20085 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
20086 @end example
20087 @end quotation
20089 It is recommended that these restriction pragmas be used if possible. Note
20090 that this also means that you can write code without worrying about the
20091 possibility of an immediate abort at any point.
20093 @node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
20094 @anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{184}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{ef}
20095 @subsubsection Optimization Levels
20098 @geindex -O (gcc)
20100 Without any optimization option,
20101 the compiler’s goal is to reduce the cost of
20102 compilation and to make debugging produce the expected results.
20103 Statements are independent: if you stop the program with a breakpoint between
20104 statements, you can then assign a new value to any variable or change
20105 the program counter to any other statement in the subprogram and get exactly
20106 the results you would expect from the source code.
20108 Turning on optimization makes the compiler attempt to improve the
20109 performance and/or code size at the expense of compilation time and
20110 possibly the ability to debug the program.
20112 If you use multiple
20113 -O options, with or without level numbers,
20114 the last such option is the one that is effective.
20116 The default is optimization off. This results in the fastest compile
20117 times, but GNAT makes absolutely no attempt to optimize, and the
20118 generated programs are considerably larger and slower than when
20119 optimization is enabled. You can use the
20120 @code{-O} switch (the permitted forms are @code{-O0}, @code{-O1}
20121 @code{-O2}, @code{-O3}, and @code{-Os})
20122 to @code{gcc} to control the optimization level:
20125 @itemize *
20127 @item 
20129 @table @asis
20131 @item @code{-O0}
20133 No optimization (the default);
20134 generates unoptimized code but has
20135 the fastest compilation time.
20137 Note that many other compilers do substantial optimization even
20138 if ‘no optimization’ is specified. With gcc, it is very unusual
20139 to use @code{-O0} for production if execution time is of any concern,
20140 since @code{-O0} means (almost) no optimization. This difference
20141 between gcc and other compilers should be kept in mind when
20142 doing performance comparisons.
20143 @end table
20145 @item 
20147 @table @asis
20149 @item @code{-O1}
20151 Moderate optimization;
20152 optimizes reasonably well but does not
20153 degrade compilation time significantly.
20154 @end table
20156 @item 
20158 @table @asis
20160 @item @code{-O2}
20162 Full optimization;
20163 generates highly optimized code and has
20164 the slowest compilation time.
20165 @end table
20167 @item 
20169 @table @asis
20171 @item @code{-O3}
20173 Full optimization as in @code{-O2};
20174 also uses more aggressive automatic inlining of subprograms within a unit
20175 (@ref{102,,Inlining of Subprograms}) and attempts to vectorize loops.
20176 @end table
20178 @item 
20180 @table @asis
20182 @item @code{-Os}
20184 Optimize space usage (code and data) of resulting program.
20185 @end table
20186 @end itemize
20188 Higher optimization levels perform more global transformations on the
20189 program and apply more expensive analysis algorithms in order to generate
20190 faster and more compact code. The price in compilation time, and the
20191 resulting improvement in execution time,
20192 both depend on the particular application and the hardware environment.
20193 You should experiment to find the best level for your application.
20195 Since the precise set of optimizations done at each level will vary from
20196 release to release (and sometime from target to target), it is best to think
20197 of the optimization settings in general terms.
20198 See the `Options That Control Optimization' section in
20199 @cite{Using the GNU Compiler Collection (GCC)}
20200 for details about
20201 the @code{-O} settings and a number of @code{-f} options that
20202 individually enable or disable specific optimizations.
20204 Unlike some other compilation systems, @code{gcc} has
20205 been tested extensively at all optimization levels. There are some bugs
20206 which appear only with optimization turned on, but there have also been
20207 bugs which show up only in `unoptimized' code. Selecting a lower
20208 level of optimization does not improve the reliability of the code
20209 generator, which in practice is highly reliable at all optimization
20210 levels.
20212 Note regarding the use of @code{-O3}: The use of this optimization level
20213 ought not to be automatically preferred over that of level @code{-O2},
20214 since it often results in larger executables which may run more slowly.
20215 See further discussion of this point in @ref{102,,Inlining of Subprograms}.
20217 @node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
20218 @anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{185}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{186}
20219 @subsubsection Debugging Optimized Code
20222 @geindex Debugging optimized code
20224 @geindex Optimization and debugging
20226 Although it is possible to do a reasonable amount of debugging at
20227 nonzero optimization levels,
20228 the higher the level the more likely that
20229 source-level constructs will have been eliminated by optimization.
20230 For example, if a loop is strength-reduced, the loop
20231 control variable may be completely eliminated and thus cannot be
20232 displayed in the debugger.
20233 This can only happen at @code{-O2} or @code{-O3}.
20234 Explicit temporary variables that you code might be eliminated at
20235 level @code{-O1} or higher.
20237 @geindex -g (gcc)
20239 The use of the @code{-g} switch,
20240 which is needed for source-level debugging,
20241 affects the size of the program executable on disk,
20242 and indeed the debugging information can be quite large.
20243 However, it has no effect on the generated code (and thus does not
20244 degrade performance)
20246 Since the compiler generates debugging tables for a compilation unit before
20247 it performs optimizations, the optimizing transformations may invalidate some
20248 of the debugging data.  You therefore need to anticipate certain
20249 anomalous situations that may arise while debugging optimized code.
20250 These are the most common cases:
20253 @itemize *
20255 @item 
20256 `The ‘hopping Program Counter’:'  Repeated @code{step} or @code{next}
20257 commands show
20258 the PC bouncing back and forth in the code.  This may result from any of
20259 the following optimizations:
20262 @itemize -
20264 @item 
20265 `Common subexpression elimination:' using a single instance of code for a
20266 quantity that the source computes several times.  As a result you
20267 may not be able to stop on what looks like a statement.
20269 @item 
20270 `Invariant code motion:' moving an expression that does not change within a
20271 loop, to the beginning of the loop.
20273 @item 
20274 `Instruction scheduling:' moving instructions so as to
20275 overlap loads and stores (typically) with other code, or in
20276 general to move computations of values closer to their uses. Often
20277 this causes you to pass an assignment statement without the assignment
20278 happening and then later bounce back to the statement when the
20279 value is actually needed.  Placing a breakpoint on a line of code
20280 and then stepping over it may, therefore, not always cause all the
20281 expected side-effects.
20282 @end itemize
20284 @item 
20285 `The ‘big leap’:' More commonly known as `cross-jumping', in which
20286 two identical pieces of code are merged and the program counter suddenly
20287 jumps to a statement that is not supposed to be executed, simply because
20288 it (and the code following) translates to the same thing as the code
20289 that `was' supposed to be executed.  This effect is typically seen in
20290 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
20291 a @code{break} in a C @code{switch} statement.
20293 @item 
20294 `The ‘roving variable’:' The symptom is an unexpected value in a variable.
20295 There are various reasons for this effect:
20298 @itemize -
20300 @item 
20301 In a subprogram prologue, a parameter may not yet have been moved to its
20302 ‘home’.
20304 @item 
20305 A variable may be dead, and its register re-used.  This is
20306 probably the most common cause.
20308 @item 
20309 As mentioned above, the assignment of a value to a variable may
20310 have been moved.
20312 @item 
20313 A variable may be eliminated entirely by value propagation or
20314 other means.  In this case, GCC may incorrectly generate debugging
20315 information for the variable
20316 @end itemize
20318 In general, when an unexpected value appears for a local variable or parameter
20319 you should first ascertain if that value was actually computed by
20320 your program, as opposed to being incorrectly reported by the debugger.
20321 Record fields or
20322 array elements in an object designated by an access value
20323 are generally less of a problem, once you have ascertained that the access
20324 value is sensible.
20325 Typically, this means checking variables in the preceding code and in the
20326 calling subprogram to verify that the value observed is explainable from other
20327 values (one must apply the procedure recursively to those
20328 other values); or re-running the code and stopping a little earlier
20329 (perhaps before the call) and stepping to better see how the variable obtained
20330 the value in question; or continuing to step `from' the point of the
20331 strange value to see if code motion had simply moved the variable’s
20332 assignments later.
20333 @end itemize
20335 In light of such anomalies, a recommended technique is to use @code{-O0}
20336 early in the software development cycle, when extensive debugging capabilities
20337 are most needed, and then move to @code{-O1} and later @code{-O2} as
20338 the debugger becomes less critical.
20339 Whether to use the @code{-g} switch in the release version is
20340 a release management issue.
20341 Note that if you use @code{-g} you can then use the @code{strip} program
20342 on the resulting executable,
20343 which removes both debugging information and global symbols.
20345 @node Inlining of Subprograms,Floating Point Operations,Debugging Optimized Code,Performance Considerations
20346 @anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{187}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{102}
20347 @subsubsection Inlining of Subprograms
20350 A call to a subprogram in the current unit is inlined if all the
20351 following conditions are met:
20354 @itemize *
20356 @item 
20357 The optimization level is at least @code{-O1}.
20359 @item 
20360 The called subprogram is suitable for inlining: It must be small enough
20361 and not contain something that @code{gcc} cannot support in inlined
20362 subprograms.
20364 @geindex pragma Inline
20366 @geindex Inline
20368 @item 
20369 Any one of the following applies: @code{pragma Inline} is applied to the
20370 subprogram; the subprogram is local to the unit and called once from
20371 within it; the subprogram is small and optimization level @code{-O2} is
20372 specified; optimization level @code{-O3} is specified.
20373 @end itemize
20375 Calls to subprograms in `with'ed units are normally not inlined.
20376 To achieve actual inlining (that is, replacement of the call by the code
20377 in the body of the subprogram), the following conditions must all be true:
20380 @itemize *
20382 @item 
20383 The optimization level is at least @code{-O1}.
20385 @item 
20386 The called subprogram is suitable for inlining: It must be small enough
20387 and not contain something that @code{gcc} cannot support in inlined
20388 subprograms.
20390 @item 
20391 There is a @code{pragma Inline} for the subprogram.
20393 @item 
20394 The @code{-gnatn} switch is used on the command line.
20395 @end itemize
20397 Even if all these conditions are met, it may not be possible for
20398 the compiler to inline the call, due to the length of the body,
20399 or features in the body that make it impossible for the compiler
20400 to do the inlining.
20402 Note that specifying the @code{-gnatn} switch causes additional
20403 compilation dependencies. Consider the following:
20405 @quotation
20407 @example
20408 package R is
20409    procedure Q;
20410    pragma Inline (Q);
20411 end R;
20412 package body R is
20413    ...
20414 end R;
20416 with R;
20417 procedure Main is
20418 begin
20419    ...
20420    R.Q;
20421 end Main;
20422 @end example
20423 @end quotation
20425 With the default behavior (no @code{-gnatn} switch specified), the
20426 compilation of the @code{Main} procedure depends only on its own source,
20427 @code{main.adb}, and the spec of the package in file @code{r.ads}. This
20428 means that editing the body of @code{R} does not require recompiling
20429 @code{Main}.
20431 On the other hand, the call @code{R.Q} is not inlined under these
20432 circumstances. If the @code{-gnatn} switch is present when @code{Main}
20433 is compiled, the call will be inlined if the body of @code{Q} is small
20434 enough, but now @code{Main} depends on the body of @code{R} in
20435 @code{r.adb} as well as on the spec. This means that if this body is edited,
20436 the main program must be recompiled. Note that this extra dependency
20437 occurs whether or not the call is in fact inlined by @code{gcc}.
20439 The use of front end inlining with @code{-gnatN} generates similar
20440 additional dependencies.
20442 @geindex -fno-inline (gcc)
20444 Note: The @code{-fno-inline} switch overrides all other conditions and ensures that
20445 no inlining occurs, unless requested with pragma Inline_Always for @code{gcc}
20446 back-ends. The extra dependences resulting from @code{-gnatn} will still be active,
20447 even if this switch is used to suppress the resulting inlining actions.
20449 @geindex -fno-inline-functions (gcc)
20451 Note: The @code{-fno-inline-functions} switch can be used to prevent
20452 automatic inlining of subprograms if @code{-O3} is used.
20454 @geindex -fno-inline-small-functions (gcc)
20456 Note: The @code{-fno-inline-small-functions} switch can be used to prevent
20457 automatic inlining of small subprograms if @code{-O2} is used.
20459 @geindex -fno-inline-functions-called-once (gcc)
20461 Note: The @code{-fno-inline-functions-called-once} switch
20462 can be used to prevent inlining of subprograms local to the unit
20463 and called once from within it if @code{-O1} is used.
20465 Note regarding the use of @code{-O3}: @code{-gnatn} is made up of two
20466 sub-switches @code{-gnatn1} and @code{-gnatn2} that can be directly
20467 specified in lieu of it, @code{-gnatn} being translated into one of them
20468 based on the optimization level. With @code{-O2} or below, @code{-gnatn}
20469 is equivalent to @code{-gnatn1} which activates pragma @code{Inline} with
20470 moderate inlining across modules. With @code{-O3}, @code{-gnatn} is
20471 equivalent to @code{-gnatn2} which activates pragma @code{Inline} with
20472 full inlining across modules. If you have used pragma @code{Inline} in
20473 appropriate cases, then it is usually much better to use @code{-O2}
20474 and @code{-gnatn} and avoid the use of @code{-O3} which has the additional
20475 effect of inlining subprograms you did not think should be inlined. We have
20476 found that the use of @code{-O3} may slow down the compilation and increase
20477 the code size by performing excessive inlining, leading to increased
20478 instruction cache pressure from the increased code size and thus minor
20479 performance improvements. So the bottom line here is that you should not
20480 automatically assume that @code{-O3} is better than @code{-O2}, and
20481 indeed you should use @code{-O3} only if tests show that it actually
20482 improves performance for your program.
20484 @node Floating Point Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
20485 @anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{188}@anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{189}
20486 @subsubsection Floating Point Operations
20489 @geindex Floating-Point Operations
20491 On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
20492 64-bit standard IEEE floating-point representations, and operations will
20493 use standard IEEE arithmetic as provided by the processor. On most, but
20494 not all, architectures, the attribute Machine_Overflows is False for these
20495 types, meaning that the semantics of overflow is implementation-defined.
20496 In the case of GNAT, these semantics correspond to the normal IEEE
20497 treatment of infinities and NaN (not a number) values. For example,
20498 1.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
20499 avoiding explicit overflow checks, the performance is greatly improved
20500 on many targets. However, if required, floating-point overflow can be
20501 enabled by the use of the pragma Check_Float_Overflow.
20503 Another consideration that applies specifically to x86 32-bit
20504 architectures is which form of floating-point arithmetic is used.
20505 By default the operations use the old style x86 floating-point,
20506 which implements an 80-bit extended precision form (on these
20507 architectures the type Long_Long_Float corresponds to that form).
20508 In addition, generation of efficient code in this mode means that
20509 the extended precision form will be used for intermediate results.
20510 This may be helpful in improving the final precision of a complex
20511 expression. However it means that the results obtained on the x86
20512 will be different from those on other architectures, and for some
20513 algorithms, the extra intermediate precision can be detrimental.
20515 In addition to this old-style floating-point, all modern x86 chips
20516 implement an alternative floating-point operation model referred
20517 to as SSE2. In this model there is no extended form, and furthermore
20518 execution performance is significantly enhanced. To force GNAT to use
20519 this more modern form, use both of the switches:
20521 @quotation
20523 -msse2 -mfpmath=sse
20524 @end quotation
20526 A unit compiled with these switches will automatically use the more
20527 efficient SSE2 instruction set for Float and Long_Float operations.
20528 Note that the ABI has the same form for both floating-point models,
20529 so it is permissible to mix units compiled with and without these
20530 switches.
20532 @node Vectorization of loops,Other Optimization Switches,Floating Point Operations,Performance Considerations
20533 @anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{18a}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{18b}
20534 @subsubsection Vectorization of loops
20537 @geindex Optimization Switches
20539 You can take advantage of the auto-vectorizer present in the @code{gcc}
20540 back end to vectorize loops with GNAT.  The corresponding command line switch
20541 is @code{-ftree-vectorize} but, as it is enabled by default at @code{-O3}
20542 and other aggressive optimizations helpful for vectorization also are enabled
20543 by default at this level, using @code{-O3} directly is recommended.
20545 You also need to make sure that the target architecture features a supported
20546 SIMD instruction set.  For example, for the x86 architecture, you should at
20547 least specify @code{-msse2} to get significant vectorization (but you don’t
20548 need to specify it for x86-64 as it is part of the base 64-bit architecture).
20549 Similarly, for the PowerPC architecture, you should specify @code{-maltivec}.
20551 The preferred loop form for vectorization is the @code{for} iteration scheme.
20552 Loops with a @code{while} iteration scheme can also be vectorized if they are
20553 very simple, but the vectorizer will quickly give up otherwise.  With either
20554 iteration scheme, the flow of control must be straight, in particular no
20555 @code{exit} statement may appear in the loop body.  The loop may however
20556 contain a single nested loop, if it can be vectorized when considered alone:
20558 @quotation
20560 @example
20561 A : array (1..4, 1..4) of Long_Float;
20562 S : array (1..4) of Long_Float;
20564 procedure Sum is
20565 begin
20566    for I in A'Range(1) loop
20567       for J in A'Range(2) loop
20568          S (I) := S (I) + A (I, J);
20569       end loop;
20570    end loop;
20571 end Sum;
20572 @end example
20573 @end quotation
20575 The vectorizable operations depend on the targeted SIMD instruction set, but
20576 the adding and some of the multiplying operators are generally supported, as
20577 well as the logical operators for modular types. Note that compiling
20578 with @code{-gnatp} might well reveal cases where some checks do thwart
20579 vectorization.
20581 Type conversions may also prevent vectorization if they involve semantics that
20582 are not directly supported by the code generator or the SIMD instruction set.
20583 A typical example is direct conversion from floating-point to integer types.
20584 The solution in this case is to use the following idiom:
20586 @quotation
20588 @example
20589 Integer (S'Truncation (F))
20590 @end example
20591 @end quotation
20593 if @code{S} is the subtype of floating-point object @code{F}.
20595 In most cases, the vectorizable loops are loops that iterate over arrays.
20596 All kinds of array types are supported, i.e. constrained array types with
20597 static bounds:
20599 @quotation
20601 @example
20602 type Array_Type is array (1 .. 4) of Long_Float;
20603 @end example
20604 @end quotation
20606 constrained array types with dynamic bounds:
20608 @quotation
20610 @example
20611 type Array_Type is array (1 .. Q.N) of Long_Float;
20613 type Array_Type is array (Q.K .. 4) of Long_Float;
20615 type Array_Type is array (Q.K .. Q.N) of Long_Float;
20616 @end example
20617 @end quotation
20619 or unconstrained array types:
20621 @quotation
20623 @example
20624 type Array_Type is array (Positive range <>) of Long_Float;
20625 @end example
20626 @end quotation
20628 The quality of the generated code decreases when the dynamic aspect of the
20629 array type increases, the worst code being generated for unconstrained array
20630 types.  This is so because, the less information the compiler has about the
20631 bounds of the array, the more fallback code it needs to generate in order to
20632 fix things up at run time.
20634 It is possible to specify that a given loop should be subject to vectorization
20635 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
20637 @quotation
20639 @example
20640 pragma Loop_Optimize (Vector);
20641 @end example
20642 @end quotation
20644 placed immediately within the loop will convey the appropriate hint to the
20645 compiler for this loop.
20647 It is also possible to help the compiler generate better vectorized code
20648 for a given loop by asserting that there are no loop-carried dependencies
20649 in the loop.  Consider for example the procedure:
20651 @quotation
20653 @example
20654 type Arr is array (1 .. 4) of Long_Float;
20656 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
20657 begin
20658   for I in Arr'Range loop
20659     R(I) := X(I) + Y(I);
20660   end loop;
20661 end;
20662 @end example
20663 @end quotation
20665 By default, the compiler cannot unconditionally vectorize the loop because
20666 assigning to a component of the array designated by R in one iteration could
20667 change the value read from the components of the array designated by X or Y
20668 in a later iteration.  As a result, the compiler will generate two versions
20669 of the loop in the object code, one vectorized and the other not vectorized,
20670 as well as a test to select the appropriate version at run time.  This can
20671 be overcome by another hint:
20673 @quotation
20675 @example
20676 pragma Loop_Optimize (Ivdep);
20677 @end example
20678 @end quotation
20680 placed immediately within the loop will tell the compiler that it can safely
20681 omit the non-vectorized version of the loop as well as the run-time test.
20683 @node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
20684 @anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{18c}@anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{18d}
20685 @subsubsection Other Optimization Switches
20688 @geindex Optimization Switches
20690 Since GNAT uses the @code{gcc} back end, all the specialized
20691 @code{gcc} optimization switches are potentially usable. These switches
20692 have not been extensively tested with GNAT but can generally be expected
20693 to work. Examples of switches in this category are @code{-funroll-loops}
20694 and the various target-specific @code{-m} options (in particular, it has
20695 been observed that @code{-march=xxx} can significantly improve performance
20696 on appropriate machines). For full details of these switches, see
20697 the `Submodel Options' section in the `Hardware Models and Configurations'
20698 chapter of @cite{Using the GNU Compiler Collection (GCC)}.
20700 @node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
20701 @anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{18e}@anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{e6}
20702 @subsubsection Optimization and Strict Aliasing
20705 @geindex Aliasing
20707 @geindex Strict Aliasing
20709 @geindex No_Strict_Aliasing
20711 The strong typing capabilities of Ada allow an optimizer to generate
20712 efficient code in situations where other languages would be forced to
20713 make worst case assumptions preventing such optimizations. Consider
20714 the following example:
20716 @quotation
20718 @example
20719 procedure R is
20720    type Int1 is new Integer;
20721    type Int2 is new Integer;
20722    type Int1A is access Int1;
20723    type Int2A is access Int2;
20724    Int1V : Int1A;
20725    Int2V : Int2A;
20726    ...
20728 begin
20729    ...
20730    for J in Data'Range loop
20731       if Data (J) = Int1V.all then
20732          Int2V.all := Int2V.all + 1;
20733       end if;
20734    end loop;
20735    ...
20736 end R;
20737 @end example
20738 @end quotation
20740 In this example, since the variable @code{Int1V} can only access objects
20741 of type @code{Int1}, and @code{Int2V} can only access objects of type
20742 @code{Int2}, there is no possibility that the assignment to
20743 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
20744 the compiler optimizer can “know” that the value @code{Int1V.all} is constant
20745 for all iterations of the loop and avoid the extra memory reference
20746 required to dereference it each time through the loop.
20748 This kind of optimization, called strict aliasing analysis, is
20749 triggered by specifying an optimization level of @code{-O2} or
20750 higher or @code{-Os} and allows GNAT to generate more efficient code
20751 when access values are involved.
20753 However, although this optimization is always correct in terms of
20754 the formal semantics of the Ada Reference Manual, difficulties can
20755 arise if features like @code{Unchecked_Conversion} are used to break
20756 the typing system. Consider the following complete program example:
20758 @quotation
20760 @example
20761 package p1 is
20762    type int1 is new integer;
20763    type int2 is new integer;
20764    type a1 is access int1;
20765    type a2 is access int2;
20766 end p1;
20768 with p1; use p1;
20769 package p2 is
20770    function to_a2 (Input : a1) return a2;
20771 end p2;
20773 with Ada.Unchecked_Conversion;
20774 package body p2 is
20775    function to_a2 (Input : a1) return a2 is
20776       function to_a2u is
20777         new Ada.Unchecked_Conversion (a1, a2);
20778    begin
20779       return to_a2u (Input);
20780    end to_a2;
20781 end p2;
20783 with p2; use p2;
20784 with p1; use p1;
20785 with Text_IO; use Text_IO;
20786 procedure m is
20787    v1 : a1 := new int1;
20788    v2 : a2 := to_a2 (v1);
20789 begin
20790    v1.all := 1;
20791    v2.all := 0;
20792    put_line (int1'image (v1.all));
20793 end;
20794 @end example
20795 @end quotation
20797 This program prints out 0 in @code{-O0} or @code{-O1}
20798 mode, but it prints out 1 in @code{-O2} mode. That’s
20799 because in strict aliasing mode, the compiler can and
20800 does assume that the assignment to @code{v2.all} could not
20801 affect the value of @code{v1.all}, since different types
20802 are involved.
20804 This behavior is not a case of non-conformance with the standard, since
20805 the Ada RM specifies that an unchecked conversion where the resulting
20806 bit pattern is not a correct value of the target type can result in an
20807 abnormal value and attempting to reference an abnormal value makes the
20808 execution of a program erroneous.  That’s the case here since the result
20809 does not point to an object of type @code{int2}.  This means that the
20810 effect is entirely unpredictable.
20812 However, although that explanation may satisfy a language
20813 lawyer, in practice an applications programmer expects an
20814 unchecked conversion involving pointers to create true
20815 aliases and the behavior of printing 1 seems plain wrong.
20816 In this case, the strict aliasing optimization is unwelcome.
20818 Indeed the compiler recognizes this possibility, and the
20819 unchecked conversion generates a warning:
20821 @quotation
20823 @example
20824 p2.adb:5:07: warning: possible aliasing problem with type "a2"
20825 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
20826 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
20827 @end example
20828 @end quotation
20830 Unfortunately the problem is recognized when compiling the body of
20831 package @code{p2}, but the actual “bad” code is generated while
20832 compiling the body of @code{m} and this latter compilation does not see
20833 the suspicious @code{Unchecked_Conversion}.
20835 As implied by the warning message, there are approaches you can use to
20836 avoid the unwanted strict aliasing optimization in a case like this.
20838 One possibility is to simply avoid the use of @code{-O2}, but
20839 that is a bit drastic, since it throws away a number of useful
20840 optimizations that do not involve strict aliasing assumptions.
20842 A less drastic approach is to compile the program using the
20843 option @code{-fno-strict-aliasing}. Actually it is only the
20844 unit containing the dereferencing of the suspicious pointer
20845 that needs to be compiled. So in this case, if we compile
20846 unit @code{m} with this switch, then we get the expected
20847 value of zero printed. Analyzing which units might need
20848 the switch can be painful, so a more reasonable approach
20849 is to compile the entire program with options @code{-O2}
20850 and @code{-fno-strict-aliasing}. If the performance is
20851 satisfactory with this combination of options, then the
20852 advantage is that the entire issue of possible “wrong”
20853 optimization due to strict aliasing is avoided.
20855 To avoid the use of compiler switches, the configuration
20856 pragma @code{No_Strict_Aliasing} with no parameters may be
20857 used to specify that for all access types, the strict
20858 aliasing optimization should be suppressed.
20860 However, these approaches are still overkill, in that they causes
20861 all manipulations of all access values to be deoptimized. A more
20862 refined approach is to concentrate attention on the specific
20863 access type identified as problematic.
20865 First, if a careful analysis of uses of the pointer shows
20866 that there are no possible problematic references, then
20867 the warning can be suppressed by bracketing the
20868 instantiation of @code{Unchecked_Conversion} to turn
20869 the warning off:
20871 @quotation
20873 @example
20874 pragma Warnings (Off);
20875 function to_a2u is
20876   new Ada.Unchecked_Conversion (a1, a2);
20877 pragma Warnings (On);
20878 @end example
20879 @end quotation
20881 Of course that approach is not appropriate for this particular
20882 example, since indeed there is a problematic reference. In this
20883 case we can take one of two other approaches.
20885 The first possibility is to move the instantiation of unchecked
20886 conversion to the unit in which the type is declared. In
20887 this example, we would move the instantiation of
20888 @code{Unchecked_Conversion} from the body of package
20889 @code{p2} to the spec of package @code{p1}. Now the
20890 warning disappears. That’s because any use of the
20891 access type knows there is a suspicious unchecked
20892 conversion, and the strict aliasing optimization
20893 is automatically suppressed for the type.
20895 If it is not practical to move the unchecked conversion to the same unit
20896 in which the destination access type is declared (perhaps because the
20897 source type is not visible in that unit), you may use pragma
20898 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
20899 same declarative sequence as the declaration of the access type:
20901 @quotation
20903 @example
20904 type a2 is access int2;
20905 pragma No_Strict_Aliasing (a2);
20906 @end example
20907 @end quotation
20909 Here again, the compiler now knows that the strict aliasing optimization
20910 should be suppressed for any reference to type @code{a2} and the
20911 expected behavior is obtained.
20913 Finally, note that although the compiler can generate warnings for
20914 simple cases of unchecked conversions, there are tricker and more
20915 indirect ways of creating type incorrect aliases which the compiler
20916 cannot detect. Examples are the use of address overlays and unchecked
20917 conversions involving composite types containing access types as
20918 components. In such cases, no warnings are generated, but there can
20919 still be aliasing problems. One safe coding practice is to forbid the
20920 use of address clauses for type overlaying, and to allow unchecked
20921 conversion only for primitive types. This is not really a significant
20922 restriction since any possible desired effect can be achieved by
20923 unchecked conversion of access values.
20925 The aliasing analysis done in strict aliasing mode can certainly
20926 have significant benefits. We have seen cases of large scale
20927 application code where the time is increased by up to 5% by turning
20928 this optimization off. If you have code that includes significant
20929 usage of unchecked conversion, you might want to just stick with
20930 @code{-O1} and avoid the entire issue. If you get adequate
20931 performance at this level of optimization level, that’s probably
20932 the safest approach. If tests show that you really need higher
20933 levels of optimization, then you can experiment with @code{-O2}
20934 and @code{-O2 -fno-strict-aliasing} to see how much effect this
20935 has on size and speed of the code. If you really need to use
20936 @code{-O2} with strict aliasing in effect, then you should
20937 review any uses of unchecked conversion of access types,
20938 particularly if you are getting the warnings described above.
20940 @node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
20941 @anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{18f}@anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{190}
20942 @subsubsection Aliased Variables and Optimization
20945 @geindex Aliasing
20947 There are scenarios in which programs may
20948 use low level techniques to modify variables
20949 that otherwise might be considered to be unassigned. For example,
20950 a variable can be passed to a procedure by reference, which takes
20951 the address of the parameter and uses the address to modify the
20952 variable’s value, even though it is passed as an IN parameter.
20953 Consider the following example:
20955 @quotation
20957 @example
20958 procedure P is
20959    Max_Length : constant Natural := 16;
20960    type Char_Ptr is access all Character;
20962    procedure Get_String(Buffer: Char_Ptr; Size : Integer);
20963    pragma Import (C, Get_String, "get_string");
20965    Name : aliased String (1 .. Max_Length) := (others => ' ');
20966    Temp : Char_Ptr;
20968    function Addr (S : String) return Char_Ptr is
20969       function To_Char_Ptr is
20970         new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
20971    begin
20972       return To_Char_Ptr (S (S'First)'Address);
20973    end;
20975 begin
20976    Temp := Addr (Name);
20977    Get_String (Temp, Max_Length);
20978 end;
20979 @end example
20980 @end quotation
20982 where Get_String is a C function that uses the address in Temp to
20983 modify the variable @code{Name}. This code is dubious, and arguably
20984 erroneous, and the compiler would be entitled to assume that
20985 @code{Name} is never modified, and generate code accordingly.
20987 However, in practice, this would cause some existing code that
20988 seems to work with no optimization to start failing at high
20989 levels of optimization.
20991 What the compiler does for such cases is to assume that marking
20992 a variable as aliased indicates that some “funny business” may
20993 be going on. The optimizer recognizes the aliased keyword and
20994 inhibits optimizations that assume the value cannot be assigned.
20995 This means that the above example will in fact “work” reliably,
20996 that is, it will produce the expected results.
20998 @node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
20999 @anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{191}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{192}
21000 @subsubsection Atomic Variables and Optimization
21003 @geindex Atomic
21005 There are two considerations with regard to performance when
21006 atomic variables are used.
21008 First, the RM only guarantees that access to atomic variables
21009 be atomic, it has nothing to say about how this is achieved,
21010 though there is a strong implication that this should not be
21011 achieved by explicit locking code. Indeed GNAT will never
21012 generate any locking code for atomic variable access (it will
21013 simply reject any attempt to make a variable or type atomic
21014 if the atomic access cannot be achieved without such locking code).
21016 That being said, it is important to understand that you cannot
21017 assume that the entire variable will always be accessed. Consider
21018 this example:
21020 @quotation
21022 @example
21023 type R is record
21024    A,B,C,D : Character;
21025 end record;
21026 for R'Size use 32;
21027 for R'Alignment use 4;
21029 RV : R;
21030 pragma Atomic (RV);
21031 X : Character;
21033 X := RV.B;
21034 @end example
21035 @end quotation
21037 You cannot assume that the reference to @code{RV.B}
21038 will read the entire 32-bit
21039 variable with a single load instruction. It is perfectly legitimate if
21040 the hardware allows it to do a byte read of just the B field. This read
21041 is still atomic, which is all the RM requires. GNAT can and does take
21042 advantage of this, depending on the architecture and optimization level.
21043 Any assumption to the contrary is non-portable and risky. Even if you
21044 examine the assembly language and see a full 32-bit load, this might
21045 change in a future version of the compiler.
21047 If your application requires that all accesses to @code{RV} in this
21048 example be full 32-bit loads, you need to make a copy for the access
21049 as in:
21051 @quotation
21053 @example
21054 declare
21055    RV_Copy : constant R := RV;
21056 begin
21057    X := RV_Copy.B;
21058 end;
21059 @end example
21060 @end quotation
21062 Now the reference to RV must read the whole variable.
21063 Actually one can imagine some compiler which figures
21064 out that the whole copy is not required (because only
21065 the B field is actually accessed), but GNAT
21066 certainly won’t do that, and we don’t know of any
21067 compiler that would not handle this right, and the
21068 above code will in practice work portably across
21069 all architectures (that permit the Atomic declaration).
21071 The second issue with atomic variables has to do with
21072 the possible requirement of generating synchronization
21073 code. For more details on this, consult the sections on
21074 the pragmas Enable/Disable_Atomic_Synchronization in the
21075 GNAT Reference Manual. If performance is critical, and
21076 such synchronization code is not required, it may be
21077 useful to disable it.
21079 @node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
21080 @anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{193}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{194}
21081 @subsubsection Passive Task Optimization
21084 @geindex Passive Task
21086 A passive task is one which is sufficiently simple that
21087 in theory a compiler could recognize it an implement it
21088 efficiently without creating a new thread. The original design
21089 of Ada 83 had in mind this kind of passive task optimization, but
21090 only a few Ada 83 compilers attempted it. The problem was that
21091 it was difficult to determine the exact conditions under which
21092 the optimization was possible. The result is a very fragile
21093 optimization where a very minor change in the program can
21094 suddenly silently make a task non-optimizable.
21096 With the revisiting of this issue in Ada 95, there was general
21097 agreement that this approach was fundamentally flawed, and the
21098 notion of protected types was introduced. When using protected
21099 types, the restrictions are well defined, and you KNOW that the
21100 operations will be optimized, and furthermore this optimized
21101 performance is fully portable.
21103 Although it would theoretically be possible for GNAT to attempt to
21104 do this optimization, but it really doesn’t make sense in the
21105 context of Ada 95, and none of the Ada 95 compilers implement
21106 this optimization as far as we know. In particular GNAT never
21107 attempts to perform this optimization.
21109 In any new Ada 95 code that is written, you should always
21110 use protected types in place of tasks that might be able to
21111 be optimized in this manner.
21112 Of course this does not help if you have legacy Ada 83 code
21113 that depends on this optimization, but it is unusual to encounter
21114 a case where the performance gains from this optimization
21115 are significant.
21117 Your program should work correctly without this optimization. If
21118 you have performance problems, then the most practical
21119 approach is to figure out exactly where these performance problems
21120 arise, and update those particular tasks to be protected types. Note
21121 that typically clients of the tasks who call entries, will not have
21122 to be modified, only the task definition itself.
21124 @node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
21125 @anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{195}@anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{196}
21126 @subsection @code{Text_IO} Suggestions
21129 @geindex Text_IO and performance
21131 The @code{Ada.Text_IO} package has fairly high overheads due in part to
21132 the requirement of maintaining page and line counts. If performance
21133 is critical, a recommendation is to use @code{Stream_IO} instead of
21134 @code{Text_IO} for volume output, since this package has less overhead.
21136 If @code{Text_IO} must be used, note that by default output to the standard
21137 output and standard error files is unbuffered (this provides better
21138 behavior when output statements are used for debugging, or if the
21139 progress of a program is observed by tracking the output, e.g. by
21140 using the Unix `tail -f' command to watch redirected output).
21142 If you are generating large volumes of output with @code{Text_IO} and
21143 performance is an important factor, use a designated file instead
21144 of the standard output file, or change the standard output file to
21145 be buffered using @code{Interfaces.C_Streams.setvbuf}.
21147 @node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
21148 @anchor{gnat_ugn/gnat_and_program_execution id41}@anchor{197}@anchor{gnat_ugn/gnat_and_program_execution reducing-size-of-executables-with-unused-subprogram-data-elimination}@anchor{198}
21149 @subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
21152 @geindex Uunused subprogram/data elimination
21154 This section describes how you can eliminate unused subprograms and data from
21155 your executable just by setting options at compilation time.
21157 @menu
21158 * About unused subprogram/data elimination:: 
21159 * Compilation options:: 
21160 * Example of unused subprogram/data elimination:: 
21162 @end menu
21164 @node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
21165 @anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{199}@anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{19a}
21166 @subsubsection About unused subprogram/data elimination
21169 By default, an executable contains all code and data of its composing objects
21170 (directly linked or coming from statically linked libraries), even data or code
21171 never used by this executable.
21173 This feature will allow you to eliminate such unused code from your
21174 executable, making it smaller (in disk and in memory).
21176 This functionality is available on all Linux platforms except for the IA-64
21177 architecture and on all cross platforms using the ELF binary file format.
21178 In both cases GNU binutils version 2.16 or later are required to enable it.
21180 @node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
21181 @anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{19b}@anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{19c}
21182 @subsubsection Compilation options
21185 The operation of eliminating the unused code and data from the final executable
21186 is directly performed by the linker.
21188 @geindex -ffunction-sections (gcc)
21190 @geindex -fdata-sections (gcc)
21192 In order to do this, it has to work with objects compiled with the
21193 following options:
21194 @code{-ffunction-sections} @code{-fdata-sections}.
21196 These options are usable with C and Ada files.
21197 They will place respectively each
21198 function or data in a separate section in the resulting object file.
21200 Once the objects and static libraries are created with these options, the
21201 linker can perform the dead code elimination. You can do this by setting
21202 the @code{-Wl,--gc-sections} option to gcc command or in the
21203 @code{-largs} section of @code{gnatmake}. This will perform a
21204 garbage collection of code and data never referenced.
21206 If the linker performs a partial link (@code{-r} linker option), then you
21207 will need to provide the entry point using the @code{-e} / @code{--entry}
21208 linker option.
21210 Note that objects compiled without the @code{-ffunction-sections} and
21211 @code{-fdata-sections} options can still be linked with the executable.
21212 However, no dead code elimination will be performed on those objects (they will
21213 be linked as is).
21215 The GNAT static library is now compiled with -ffunction-sections and
21216 -fdata-sections on some platforms. This allows you to eliminate the unused code
21217 and data of the GNAT library from your executable.
21219 @node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
21220 @anchor{gnat_ugn/gnat_and_program_execution example-of-unused-subprogram-data-elimination}@anchor{19d}@anchor{gnat_ugn/gnat_and_program_execution id44}@anchor{19e}
21221 @subsubsection Example of unused subprogram/data elimination
21224 Here is a simple example:
21226 @quotation
21228 @example
21229 with Aux;
21231 procedure Test is
21232 begin
21233    Aux.Used (10);
21234 end Test;
21236 package Aux is
21237    Used_Data   : Integer;
21238    Unused_Data : Integer;
21240    procedure Used   (Data : Integer);
21241    procedure Unused (Data : Integer);
21242 end Aux;
21244 package body Aux is
21245    procedure Used (Data : Integer) is
21246    begin
21247       Used_Data := Data;
21248    end Used;
21250    procedure Unused (Data : Integer) is
21251    begin
21252       Unused_Data := Data;
21253    end Unused;
21254 end Aux;
21255 @end example
21256 @end quotation
21258 @code{Unused} and @code{Unused_Data} are never referenced in this code
21259 excerpt, and hence they may be safely removed from the final executable.
21261 @quotation
21263 @example
21264 $ gnatmake test
21266 $ nm test | grep used
21267 020015f0 T aux__unused
21268 02005d88 B aux__unused_data
21269 020015cc T aux__used
21270 02005d84 B aux__used_data
21272 $ gnatmake test -cargs -fdata-sections -ffunction-sections \\
21273      -largs -Wl,--gc-sections
21275 $ nm test | grep used
21276 02005350 T aux__used
21277 0201ffe0 B aux__used_data
21278 @end example
21279 @end quotation
21281 It can be observed that the procedure @code{Unused} and the object
21282 @code{Unused_Data} are removed by the linker when using the
21283 appropriate options.
21285 @geindex Overflow checks
21287 @geindex Checks (overflow)
21289 @node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
21290 @anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{14b}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{19f}
21291 @section Overflow Check Handling in GNAT
21294 This section explains how to control the handling of overflow checks.
21296 @menu
21297 * Background:: 
21298 * Management of Overflows in GNAT:: 
21299 * Specifying the Desired Mode:: 
21300 * Default Settings:: 
21301 * Implementation Notes:: 
21303 @end menu
21305 @node Background,Management of Overflows in GNAT,,Overflow Check Handling in GNAT
21306 @anchor{gnat_ugn/gnat_and_program_execution background}@anchor{1a0}@anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{1a1}
21307 @subsection Background
21310 Overflow checks are checks that the compiler may make to ensure
21311 that intermediate results are not out of range. For example:
21313 @quotation
21315 @example
21316 A : Integer;
21318 A := A + 1;
21319 @end example
21320 @end quotation
21322 If @code{A} has the value @code{Integer'Last}, then the addition may cause
21323 overflow since the result is out of range of the type @code{Integer}.
21324 In this case @code{Constraint_Error} will be raised if checks are
21325 enabled.
21327 A trickier situation arises in examples like the following:
21329 @quotation
21331 @example
21332 A, C : Integer;
21334 A := (A + 1) + C;
21335 @end example
21336 @end quotation
21338 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
21339 Now the final result of the expression on the right hand side is
21340 @code{Integer'Last} which is in range, but the question arises whether the
21341 intermediate addition of @code{(A + 1)} raises an overflow error.
21343 The (perhaps surprising) answer is that the Ada language
21344 definition does not answer this question. Instead it leaves
21345 it up to the implementation to do one of two things if overflow
21346 checks are enabled.
21349 @itemize *
21351 @item 
21352 raise an exception (@code{Constraint_Error}), or
21354 @item 
21355 yield the correct mathematical result which is then used in
21356 subsequent operations.
21357 @end itemize
21359 If the compiler chooses the first approach, then the assignment of this
21360 example will indeed raise @code{Constraint_Error} if overflow checking is
21361 enabled, or result in erroneous execution if overflow checks are suppressed.
21363 But if the compiler
21364 chooses the second approach, then it can perform both additions yielding
21365 the correct mathematical result, which is in range, so no exception
21366 will be raised, and the right result is obtained, regardless of whether
21367 overflow checks are suppressed.
21369 Note that in the first example an
21370 exception will be raised in either case, since if the compiler
21371 gives the correct mathematical result for the addition, it will
21372 be out of range of the target type of the assignment, and thus
21373 fails the range check.
21375 This lack of specified behavior in the handling of overflow for
21376 intermediate results is a source of non-portability, and can thus
21377 be problematic when programs are ported. Most typically this arises
21378 in a situation where the original compiler did not raise an exception,
21379 and then the application is moved to a compiler where the check is
21380 performed on the intermediate result and an unexpected exception is
21381 raised.
21383 Furthermore, when using Ada 2012’s preconditions and other
21384 assertion forms, another issue arises. Consider:
21386 @quotation
21388 @example
21389 procedure P (A, B : Integer) with
21390   Pre => A + B <= Integer'Last;
21391 @end example
21392 @end quotation
21394 One often wants to regard arithmetic in a context like this from
21395 a mathematical point of view. So for example, if the two actual parameters
21396 for a call to @code{P} are both @code{Integer'Last}, then
21397 the precondition should be regarded as False. If we are executing
21398 in a mode with run-time checks enabled for preconditions, then we would
21399 like this precondition to fail, rather than raising an exception
21400 because of the intermediate overflow.
21402 However, the language definition leaves the specification of
21403 whether the above condition fails (raising @code{Assert_Error}) or
21404 causes an intermediate overflow (raising @code{Constraint_Error})
21405 up to the implementation.
21407 The situation is worse in a case such as the following:
21409 @quotation
21411 @example
21412 procedure Q (A, B, C : Integer) with
21413   Pre => A + B + C <= Integer'Last;
21414 @end example
21415 @end quotation
21417 Consider the call
21419 @quotation
21421 @example
21422 Q (A => Integer'Last, B => 1, C => -1);
21423 @end example
21424 @end quotation
21426 From a mathematical point of view the precondition
21427 is True, but at run time we may (but are not guaranteed to) get an
21428 exception raised because of the intermediate overflow (and we really
21429 would prefer this precondition to be considered True at run time).
21431 @node Management of Overflows in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
21432 @anchor{gnat_ugn/gnat_and_program_execution id47}@anchor{1a2}@anchor{gnat_ugn/gnat_and_program_execution management-of-overflows-in-gnat}@anchor{1a3}
21433 @subsection Management of Overflows in GNAT
21436 To deal with the portability issue, and with the problem of
21437 mathematical versus run-time interpretation of the expressions in
21438 assertions, GNAT provides comprehensive control over the handling
21439 of intermediate overflow. GNAT can operate in three modes, and
21440 furthermore, permits separate selection of operating modes for
21441 the expressions within assertions (here the term ‘assertions’
21442 is used in the technical sense, which includes preconditions and so forth)
21443 and for expressions appearing outside assertions.
21445 The three modes are:
21448 @itemize *
21450 @item 
21451 `Use base type for intermediate operations' (@code{STRICT})
21453 In this mode, all intermediate results for predefined arithmetic
21454 operators are computed using the base type, and the result must
21455 be in range of the base type. If this is not the
21456 case then either an exception is raised (if overflow checks are
21457 enabled) or the execution is erroneous (if overflow checks are suppressed).
21458 This is the normal default mode.
21460 @item 
21461 `Most intermediate overflows avoided' (@code{MINIMIZED})
21463 In this mode, the compiler attempts to avoid intermediate overflows by
21464 using a larger integer type, typically @code{Long_Long_Integer},
21465 as the type in which arithmetic is
21466 performed for predefined arithmetic operators. This may be slightly more
21467 expensive at
21468 run time (compared to suppressing intermediate overflow checks), though
21469 the cost is negligible on modern 64-bit machines. For the examples given
21470 earlier, no intermediate overflows would have resulted in exceptions,
21471 since the intermediate results are all in the range of
21472 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
21473 of GNAT). In addition, if checks are enabled, this reduces the number of
21474 checks that must be made, so this choice may actually result in an
21475 improvement in space and time behavior.
21477 However, there are cases where @code{Long_Long_Integer} is not large
21478 enough, consider the following example:
21480 @quotation
21482 @example
21483 procedure R (A, B, C, D : Integer) with
21484   Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
21485 @end example
21486 @end quotation
21488 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
21489 Now the intermediate results are
21490 out of the range of @code{Long_Long_Integer} even though the final result
21491 is in range and the precondition is True (from a mathematical point
21492 of view). In such a case, operating in this mode, an overflow occurs
21493 for the intermediate computation (which is why this mode
21494 says `most' intermediate overflows are avoided). In this case,
21495 an exception is raised if overflow checks are enabled, and the
21496 execution is erroneous if overflow checks are suppressed.
21498 @item 
21499 `All intermediate overflows avoided' (@code{ELIMINATED})
21501 In this mode, the compiler  avoids all intermediate overflows
21502 by using arbitrary precision arithmetic as required. In this
21503 mode, the above example with @code{A**2 * B**2} would
21504 not cause intermediate overflow, because the intermediate result
21505 would be evaluated using sufficient precision, and the result
21506 of evaluating the precondition would be True.
21508 This mode has the advantage of avoiding any intermediate
21509 overflows, but at the expense of significant run-time overhead,
21510 including the use of a library (included automatically in this
21511 mode) for multiple-precision arithmetic.
21513 This mode provides cleaner semantics for assertions, since now
21514 the run-time behavior emulates true arithmetic behavior for the
21515 predefined arithmetic operators, meaning that there is never a
21516 conflict between the mathematical view of the assertion, and its
21517 run-time behavior.
21519 Note that in this mode, the behavior is unaffected by whether or
21520 not overflow checks are suppressed, since overflow does not occur.
21521 It is possible for gigantic intermediate expressions to raise
21522 @code{Storage_Error} as a result of attempting to compute the
21523 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
21524 but overflow is impossible.
21525 @end itemize
21527 Note that these modes apply only to the evaluation of predefined
21528 arithmetic, membership, and comparison operators for signed integer
21529 arithmetic.
21531 For fixed-point arithmetic, checks can be suppressed. But if checks
21532 are enabled
21533 then fixed-point values are always checked for overflow against the
21534 base type for intermediate expressions (that is such checks always
21535 operate in the equivalent of @code{STRICT} mode).
21537 For floating-point, on nearly all architectures, @code{Machine_Overflows}
21538 is False, and IEEE infinities are generated, so overflow exceptions
21539 are never raised. If you want to avoid infinities, and check that
21540 final results of expressions are in range, then you can declare a
21541 constrained floating-point type, and range checks will be carried
21542 out in the normal manner (with infinite values always failing all
21543 range checks).
21545 @node Specifying the Desired Mode,Default Settings,Management of Overflows in GNAT,Overflow Check Handling in GNAT
21546 @anchor{gnat_ugn/gnat_and_program_execution id48}@anchor{1a4}@anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{eb}
21547 @subsection Specifying the Desired Mode
21550 @geindex pragma Overflow_Mode
21552 The desired mode of for handling intermediate overflow can be specified using
21553 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
21554 The pragma has the form
21556 @quotation
21558 @example
21559 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
21560 @end example
21561 @end quotation
21563 where @code{MODE} is one of
21566 @itemize *
21568 @item 
21569 @code{STRICT}:  intermediate overflows checked (using base type)
21571 @item 
21572 @code{MINIMIZED}: minimize intermediate overflows
21574 @item 
21575 @code{ELIMINATED}: eliminate intermediate overflows
21576 @end itemize
21578 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
21579 @code{minimized} all have the same effect.
21581 If only the @code{General} parameter is present, then the given @code{MODE} applies
21582 to expressions both within and outside assertions. If both arguments
21583 are present, then @code{General} applies to expressions outside assertions,
21584 and @code{Assertions} applies to expressions within assertions. For example:
21586 @quotation
21588 @example
21589 pragma Overflow_Mode
21590   (General => Minimized, Assertions => Eliminated);
21591 @end example
21592 @end quotation
21594 specifies that general expressions outside assertions be evaluated
21595 in ‘minimize intermediate overflows’ mode, and expressions within
21596 assertions be evaluated in ‘eliminate intermediate overflows’ mode.
21597 This is often a reasonable choice, avoiding excessive overhead
21598 outside assertions, but assuring a high degree of portability
21599 when importing code from another compiler, while incurring
21600 the extra overhead for assertion expressions to ensure that
21601 the behavior at run time matches the expected mathematical
21602 behavior.
21604 The @code{Overflow_Mode} pragma has the same scoping and placement
21605 rules as pragma @code{Suppress}, so it can occur either as a
21606 configuration pragma, specifying a default for the whole
21607 program, or in a declarative scope, where it applies to the
21608 remaining declarations and statements in that scope.
21610 Note that pragma @code{Overflow_Mode} does not affect whether
21611 overflow checks are enabled or suppressed. It only controls the
21612 method used to compute intermediate values. To control whether
21613 overflow checking is enabled or suppressed, use pragma @code{Suppress}
21614 or @code{Unsuppress} in the usual manner.
21616 @geindex -gnato? (gcc)
21618 @geindex -gnato?? (gcc)
21620 Additionally, a compiler switch @code{-gnato?} or @code{-gnato??}
21621 can be used to control the checking mode default (which can be subsequently
21622 overridden using pragmas).
21624 Here @code{?} is one of the digits @code{1} through @code{3}:
21626 @quotation
21629 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
21630 @item
21632 @code{1}
21634 @tab
21636 use base type for intermediate operations (@code{STRICT})
21638 @item
21640 @code{2}
21642 @tab
21644 minimize intermediate overflows (@code{MINIMIZED})
21646 @item
21648 @code{3}
21650 @tab
21652 eliminate intermediate overflows (@code{ELIMINATED})
21654 @end multitable
21656 @end quotation
21658 As with the pragma, if only one digit appears then it applies to all
21659 cases; if two digits are given, then the first applies outside
21660 assertions, and the second within assertions. Thus the equivalent
21661 of the example pragma above would be
21662 @code{-gnato23}.
21664 If no digits follow the @code{-gnato}, then it is equivalent to
21665 @code{-gnato11},
21666 causing all intermediate operations to be computed using the base
21667 type (@code{STRICT} mode).
21669 @node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
21670 @anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{1a5}@anchor{gnat_ugn/gnat_and_program_execution id49}@anchor{1a6}
21671 @subsection Default Settings
21674 The default mode for overflow checks is
21676 @quotation
21678 @example
21679 General => Strict
21680 @end example
21681 @end quotation
21683 which causes all computations both inside and outside assertions to use the
21684 base type, and is equivalent to @code{-gnato} (with no digits following).
21686 The pragma @code{Suppress (Overflow_Check)} disables overflow
21687 checking, but it has no effect on the method used for computing
21688 intermediate results.
21690 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
21691 checking, but it has no effect on the method used for computing
21692 intermediate results.
21694 @node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
21695 @anchor{gnat_ugn/gnat_and_program_execution id50}@anchor{1a7}@anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{1a8}
21696 @subsection Implementation Notes
21699 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
21700 reasonably efficient, and can be generally used. It also helps
21701 to ensure compatibility with code imported from some other
21702 compiler to GNAT.
21704 Setting all intermediate overflows checking (@code{STRICT} mode)
21705 makes sense if you want to
21706 make sure that your code is compatible with any other possible
21707 Ada implementation. This may be useful in ensuring portability
21708 for code that is to be exported to some other compiler than GNAT.
21710 The Ada standard allows the reassociation of expressions at
21711 the same precedence level if no parentheses are present. For
21712 example, @code{A+B+C} parses as though it were @code{(A+B)+C}, but
21713 the compiler can reintepret this as @code{A+(B+C)}, possibly
21714 introducing or eliminating an overflow exception. The GNAT
21715 compiler never takes advantage of this freedom, and the
21716 expression @code{A+B+C} will be evaluated as @code{(A+B)+C}.
21717 If you need the other order, you can write the parentheses
21718 explicitly @code{A+(B+C)} and GNAT will respect this order.
21720 The use of @code{ELIMINATED} mode will cause the compiler to
21721 automatically include an appropriate arbitrary precision
21722 integer arithmetic package. The compiler will make calls
21723 to this package, though only in cases where it cannot be
21724 sure that @code{Long_Long_Integer} is sufficient to guard against
21725 intermediate overflows. This package does not use dynamic
21726 allocation, but it does use the secondary stack, so an
21727 appropriate secondary stack package must be present (this
21728 is always true for standard full Ada, but may require
21729 specific steps for restricted run times such as ZFP).
21731 Although @code{ELIMINATED} mode causes expressions to use arbitrary
21732 precision arithmetic, avoiding overflow, the final result
21733 must be in an appropriate range. This is true even if the
21734 final result is of type @code{[Long_[Long_]]Integer'Base}, which
21735 still has the same bounds as its associated constrained
21736 type at run-time.
21738 Currently, the @code{ELIMINATED} mode is only available on target
21739 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
21740 platforms).
21742 @node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
21743 @anchor{gnat_ugn/gnat_and_program_execution id51}@anchor{14c}@anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{1a9}
21744 @section Performing Dimensionality Analysis in GNAT
21747 @geindex Dimensionality analysis
21749 The GNAT compiler supports dimensionality checking. The user can
21750 specify physical units for objects, and the compiler will verify that uses
21751 of these objects are compatible with their dimensions, in a fashion that is
21752 familiar to engineering practice. The dimensions of algebraic expressions
21753 (including powers with static exponents) are computed from their constituents.
21755 @geindex Dimension_System aspect
21757 @geindex Dimension aspect
21759 This feature depends on Ada 2012 aspect specifications, and is available from
21760 version 7.0.1 of GNAT onwards.
21761 The GNAT-specific aspect @code{Dimension_System}
21762 allows you to define a system of units; the aspect @code{Dimension}
21763 then allows the user to declare dimensioned quantities within a given system.
21764 (These aspects are described in the `Implementation Defined Aspects'
21765 chapter of the `GNAT Reference Manual').
21767 The major advantage of this model is that it does not require the declaration of
21768 multiple operators for all possible combinations of types: it is only necessary
21769 to use the proper subtypes in object declarations.
21771 @geindex System.Dim.Mks package (GNAT library)
21773 @geindex MKS_Type type
21775 The simplest way to impose dimensionality checking on a computation is to make
21776 use of one of the instantiations of the package @code{System.Dim.Generic_Mks}, which
21777 are part of the GNAT library. This generic package defines a floating-point
21778 type @code{MKS_Type}, for which a sequence of dimension names are specified,
21779 together with their conventional abbreviations.  The following should be read
21780 together with the full specification of the package, in file
21781 @code{s-digemk.ads}.
21783 @quotation
21785 @geindex s-digemk.ads file
21787 @example
21788 type Mks_Type is new Float_Type
21789   with
21790    Dimension_System => (
21791      (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
21792      (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
21793      (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
21794      (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
21795      (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
21796      (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
21797      (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
21798 @end example
21799 @end quotation
21801 The package then defines a series of subtypes that correspond to these
21802 conventional units. For example:
21804 @quotation
21806 @example
21807 subtype Length is Mks_Type
21808   with
21809    Dimension => (Symbol => 'm', Meter  => 1, others => 0);
21810 @end example
21811 @end quotation
21813 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
21814 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
21815 @code{Luminous_Intensity} (the standard set of units of the SI system).
21817 The package also defines conventional names for values of each unit, for
21818 example:
21820 @quotation
21822 @example
21823 m   : constant Length           := 1.0;
21824 kg  : constant Mass             := 1.0;
21825 s   : constant Time             := 1.0;
21826 A   : constant Electric_Current := 1.0;
21827 @end example
21828 @end quotation
21830 as well as useful multiples of these units:
21832 @quotation
21834 @example
21835  cm  : constant Length := 1.0E-02;
21836  g   : constant Mass   := 1.0E-03;
21837  min : constant Time   := 60.0;
21838  day : constant Time   := 60.0 * 24.0 * min;
21840 @end example
21841 @end quotation
21843 There are three instantiations of @code{System.Dim.Generic_Mks} defined in the
21844 GNAT library:
21847 @itemize *
21849 @item 
21850 @code{System.Dim.Float_Mks} based on @code{Float} defined in @code{s-diflmk.ads}.
21852 @item 
21853 @code{System.Dim.Long_Mks} based on @code{Long_Float} defined in @code{s-dilomk.ads}.
21855 @item 
21856 @code{System.Dim.Mks} based on @code{Long_Long_Float} defined in @code{s-dimmks.ads}.
21857 @end itemize
21859 Using one of these packages, you can then define a derived unit by providing
21860 the aspect that specifies its dimensions within the MKS system, as well as the
21861 string to be used for output of a value of that unit:
21863 @quotation
21865 @example
21866 subtype Acceleration is Mks_Type
21867   with Dimension => ("m/sec^2",
21868                      Meter => 1,
21869                      Second => -2,
21870                      others => 0);
21871 @end example
21872 @end quotation
21874 Here is a complete example of use:
21876 @quotation
21878 @example
21879 with System.Dim.MKS; use System.Dim.Mks;
21880 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
21881 with Text_IO; use Text_IO;
21882 procedure Free_Fall is
21883   subtype Acceleration is Mks_Type
21884     with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
21885   G : constant acceleration := 9.81 * m / (s ** 2);
21886   T : Time := 10.0*s;
21887   Distance : Length;
21889 begin
21890   Put ("Gravitational constant: ");
21891   Put (G, Aft => 2, Exp => 0); Put_Line ("");
21892   Distance := 0.5 * G * T ** 2;
21893   Put ("distance travelled in 10 seconds of free fall ");
21894   Put (Distance, Aft => 2, Exp => 0);
21895   Put_Line ("");
21896 end Free_Fall;
21897 @end example
21898 @end quotation
21900 Execution of this program yields:
21902 @quotation
21904 @example
21905 Gravitational constant:  9.81 m/sec^2
21906 distance travelled in 10 seconds of free fall 490.50 m
21907 @end example
21908 @end quotation
21910 However, incorrect assignments such as:
21912 @quotation
21914 @example
21915 Distance := 5.0;
21916 Distance := 5.0 * kg;
21917 @end example
21918 @end quotation
21920 are rejected with the following diagnoses:
21922 @quotation
21924 @example
21925 Distance := 5.0;
21926    >>> dimensions mismatch in assignment
21927    >>> left-hand side has dimension [L]
21928    >>> right-hand side is dimensionless
21930 Distance := 5.0 * kg:
21931    >>> dimensions mismatch in assignment
21932    >>> left-hand side has dimension [L]
21933    >>> right-hand side has dimension [M]
21934 @end example
21935 @end quotation
21937 The dimensions of an expression are properly displayed, even if there is
21938 no explicit subtype for it. If we add to the program:
21940 @quotation
21942 @example
21943 Put ("Final velocity: ");
21944 Put (G * T, Aft =>2, Exp =>0);
21945 Put_Line ("");
21946 @end example
21947 @end quotation
21949 then the output includes:
21951 @quotation
21953 @example
21954 Final velocity: 98.10 m.s**(-1)
21955 @end example
21957 @geindex Dimensionable type
21959 @geindex Dimensioned subtype
21960 @end quotation
21962 The type @code{Mks_Type} is said to be a `dimensionable type' since it has a
21963 @code{Dimension_System} aspect, and the subtypes @code{Length}, @code{Mass}, etc.,
21964 are said to be `dimensioned subtypes' since each one has a @code{Dimension}
21965 aspect.
21967 @quotation
21969 @geindex Dimension Vector (for a dimensioned subtype)
21971 @geindex Dimension aspect
21973 @geindex Dimension_System aspect
21974 @end quotation
21976 The @code{Dimension} aspect of a dimensioned subtype @code{S} defines a mapping
21977 from the base type’s Unit_Names to integer (or, more generally, rational)
21978 values. This mapping is the `dimension vector' (also referred to as the
21979 `dimensionality') for that subtype, denoted by @code{DV(S)}, and thus for each
21980 object of that subtype. Intuitively, the value specified for each
21981 @code{Unit_Name} is the exponent associated with that unit; a zero value
21982 means that the unit is not used. For example:
21984 @quotation
21986 @example
21987 declare
21988    Acc : Acceleration;
21989    ...
21990 begin
21991    ...
21992 end;
21993 @end example
21994 @end quotation
21996 Here @code{DV(Acc)} = @code{DV(Acceleration)} =
21997 @code{(Meter=>1, Kilogram=>0, Second=>-2, Ampere=>0, Kelvin=>0, Mole=>0, Candela=>0)}.
21998 Symbolically, we can express this as @code{Meter / Second**2}.
22000 The dimension vector of an arithmetic expression is synthesized from the
22001 dimension vectors of its components, with compile-time dimensionality checks
22002 that help prevent mismatches such as using an @code{Acceleration} where a
22003 @code{Length} is required.
22005 The dimension vector of the result of an arithmetic expression `expr', or
22006 @code{DV(@var{expr})}, is defined as follows, assuming conventional
22007 mathematical definitions for the vector operations that are used:
22010 @itemize *
22012 @item 
22013 If `expr' is of the type `universal_real', or is not of a dimensioned subtype,
22014 then `expr' is dimensionless; @code{DV(@var{expr})} is the empty vector.
22016 @item 
22017 @code{DV(@var{op expr})}, where `op' is a unary operator, is @code{DV(@var{expr})}
22019 @item 
22020 @code{DV(@var{expr1 op expr2})} where `op' is “+” or “-” is @code{DV(@var{expr1})}
22021 provided that @code{DV(@var{expr1})} = @code{DV(@var{expr2})}.
22022 If this condition is not met then the construct is illegal.
22024 @item 
22025 @code{DV(@var{expr1} * @var{expr2})} is @code{DV(@var{expr1})} + @code{DV(@var{expr2})},
22026 and @code{DV(@var{expr1} / @var{expr2})} = @code{DV(@var{expr1})} - @code{DV(@var{expr2})}.
22027 In this context if one of the `expr's is dimensionless then its empty
22028 dimension vector is treated as @code{(others => 0)}.
22030 @item 
22031 @code{DV(@var{expr} ** @var{power})} is `power' * @code{DV(@var{expr})},
22032 provided that `power' is a static rational value. If this condition is not
22033 met then the construct is illegal.
22034 @end itemize
22036 Note that, by the above rules, it is illegal to use binary “+” or “-” to
22037 combine a dimensioned and dimensionless value.  Thus an expression such as
22038 @code{acc-10.0} is illegal, where @code{acc} is an object of subtype
22039 @code{Acceleration}.
22041 The dimensionality checks for relationals use the same rules as
22042 for “+” and “-”, except when comparing to a literal; thus
22044 @quotation
22046 @example
22047 acc > len
22048 @end example
22049 @end quotation
22051 is equivalent to
22053 @quotation
22055 @example
22056 acc-len > 0.0
22057 @end example
22058 @end quotation
22060 and is thus illegal, but
22062 @quotation
22064 @example
22065 acc > 10.0
22066 @end example
22067 @end quotation
22069 is accepted with a warning. Analogously a conditional expression requires the
22070 same dimension vector for each branch (with no exception for literals).
22072 The dimension vector of a type conversion @code{T(@var{expr})} is defined
22073 as follows, based on the nature of @code{T}:
22076 @itemize *
22078 @item 
22079 If @code{T} is a dimensioned subtype then @code{DV(T(@var{expr}))} is @code{DV(T)}
22080 provided that either `expr' is dimensionless or
22081 @code{DV(T)} = @code{DV(@var{expr})}. The conversion is illegal
22082 if `expr' is dimensioned and @code{DV(@var{expr})} /= @code{DV(T)}.
22083 Note that vector equality does not require that the corresponding
22084 Unit_Names be the same.
22086 As a consequence of the above rule, it is possible to convert between
22087 different dimension systems that follow the same international system
22088 of units, with the seven physical components given in the standard order
22089 (length, mass, time, etc.). Thus a length in meters can be converted to
22090 a length in inches (with a suitable conversion factor) but cannot be
22091 converted, for example, to a mass in pounds.
22093 @item 
22094 If @code{T} is the base type for `expr' (and the dimensionless root type of
22095 the dimension system), then @code{DV(T(@var{expr}))} is @code{DV(expr)}.
22096 Thus, if `expr' is of a dimensioned subtype of @code{T}, the conversion may
22097 be regarded as a “view conversion” that preserves dimensionality.
22099 This rule makes it possible to write generic code that can be instantiated
22100 with compatible dimensioned subtypes.  The generic unit will contain
22101 conversions that will consequently be present in instantiations, but
22102 conversions to the base type will preserve dimensionality and make it
22103 possible to write generic code that is correct with respect to
22104 dimensionality.
22106 @item 
22107 Otherwise (i.e., @code{T} is neither a dimensioned subtype nor a dimensionable
22108 base type), @code{DV(T(@var{expr}))} is the empty vector. Thus a dimensioned
22109 value can be explicitly converted to a non-dimensioned subtype, which
22110 of course then escapes dimensionality analysis.
22111 @end itemize
22113 The dimension vector for a type qualification @code{T'(@var{expr})} is the same
22114 as for the type conversion @code{T(@var{expr})}.
22116 An assignment statement
22118 @quotation
22120 @example
22121 Source := Target;
22122 @end example
22123 @end quotation
22125 requires @code{DV(Source)} = @code{DV(Target)}, and analogously for parameter
22126 passing (the dimension vector for the actual parameter must be equal to the
22127 dimension vector for the formal parameter).
22129 When using dimensioned types with elementary functions it is necessary to
22130 instantiate the @code{Ada.Numerics.Generic_Elementary_Functions} package using
22131 the @code{Mks_Type} and not any of the derived subtypes such as @code{Distance}.
22132 For functions such as @code{Sqrt} the dimensional analysis will fail when using
22133 the subtypes because both the parameter and return are of the same type.
22135 An example instantiation
22137 @quotation
22139 @example
22140 package Mks_Numerics is new
22141    Ada.Numerics.Generic_Elementary_Functions (System.Dim.Mks.Mks_Type);
22142 @end example
22143 @end quotation
22145 @node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
22146 @anchor{gnat_ugn/gnat_and_program_execution id52}@anchor{14d}@anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{1aa}
22147 @section Stack Related Facilities
22150 This section describes some useful tools associated with stack
22151 checking and analysis. In
22152 particular, it deals with dynamic and static stack usage measurements.
22154 @menu
22155 * Stack Overflow Checking:: 
22156 * Static Stack Usage Analysis:: 
22157 * Dynamic Stack Usage Analysis:: 
22159 @end menu
22161 @node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
22162 @anchor{gnat_ugn/gnat_and_program_execution id53}@anchor{1ab}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{e7}
22163 @subsection Stack Overflow Checking
22166 @geindex Stack Overflow Checking
22168 @geindex -fstack-check (gcc)
22170 For most operating systems, @code{gcc} does not perform stack overflow
22171 checking by default. This means that if the main environment task or
22172 some other task exceeds the available stack space, then unpredictable
22173 behavior will occur. Most native systems offer some level of protection by
22174 adding a guard page at the end of each task stack. This mechanism is usually
22175 not enough for dealing properly with stack overflow situations because
22176 a large local variable could “jump” above the guard page.
22177 Furthermore, when the
22178 guard page is hit, there may not be any space left on the stack for executing
22179 the exception propagation code. Enabling stack checking avoids
22180 such situations.
22182 To activate stack checking, compile all units with the @code{gcc} option
22183 @code{-fstack-check}. For example:
22185 @quotation
22187 @example
22188 $ gcc -c -fstack-check package1.adb
22189 @end example
22190 @end quotation
22192 Units compiled with this option will generate extra instructions to check
22193 that any use of the stack (for procedure calls or for declaring local
22194 variables in declare blocks) does not exceed the available stack space.
22195 If the space is exceeded, then a @code{Storage_Error} exception is raised.
22197 For declared tasks, the default stack size is defined by the GNAT runtime,
22198 whose size may be modified at bind time through the @code{-d} bind switch
22199 (@ref{112,,Switches for gnatbind}). Task specific stack sizes may be set using the
22200 @code{Storage_Size} pragma.
22202 For the environment task, the stack size is determined by the operating system.
22203 Consequently, to modify the size of the environment task please refer to your
22204 operating system documentation.
22206 @node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
22207 @anchor{gnat_ugn/gnat_and_program_execution id54}@anchor{1ac}@anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{e8}
22208 @subsection Static Stack Usage Analysis
22211 @geindex Static Stack Usage Analysis
22213 @geindex -fstack-usage
22215 A unit compiled with @code{-fstack-usage} will generate an extra file
22216 that specifies
22217 the maximum amount of stack used, on a per-function basis.
22218 The file has the same
22219 basename as the target object file with a @code{.su} extension.
22220 Each line of this file is made up of three fields:
22223 @itemize *
22225 @item 
22226 The name of the function.
22228 @item 
22229 A number of bytes.
22231 @item 
22232 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
22233 @end itemize
22235 The second field corresponds to the size of the known part of the function
22236 frame.
22238 The qualifier @code{static} means that the function frame size
22239 is purely static.
22240 It usually means that all local variables have a static size.
22241 In this case, the second field is a reliable measure of the function stack
22242 utilization.
22244 The qualifier @code{dynamic} means that the function frame size is not static.
22245 It happens mainly when some local variables have a dynamic size. When this
22246 qualifier appears alone, the second field is not a reliable measure
22247 of the function stack analysis. When it is qualified with  @code{bounded}, it
22248 means that the second field is a reliable maximum of the function stack
22249 utilization.
22251 A unit compiled with @code{-Wstack-usage} will issue a warning for each
22252 subprogram whose stack usage might be larger than the specified amount of
22253 bytes.  The wording is in keeping with the qualifier documented above.
22255 @node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
22256 @anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{115}@anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{1ad}
22257 @subsection Dynamic Stack Usage Analysis
22260 It is possible to measure the maximum amount of stack used by a task, by
22261 adding a switch to @code{gnatbind}, as:
22263 @quotation
22265 @example
22266 $ gnatbind -u0 file
22267 @end example
22268 @end quotation
22270 With this option, at each task termination, its stack usage is output on
22271 @code{stderr}.
22272 Note that this switch is not compatible with tools like
22273 Valgrind and DrMemory; they will report errors.
22275 It is not always convenient to output the stack usage when the program
22276 is still running. Hence, it is possible to delay this output until program
22277 termination. for a given number of tasks specified as the argument of the
22278 @code{-u} option. For instance:
22280 @quotation
22282 @example
22283 $ gnatbind -u100 file
22284 @end example
22285 @end quotation
22287 will buffer the stack usage information of the first 100 tasks to terminate and
22288 output this info at program termination. Results are displayed in four
22289 columns:
22291 @quotation
22293 @example
22294 Index | Task Name | Stack Size | Stack Usage
22295 @end example
22296 @end quotation
22298 where:
22301 @itemize *
22303 @item 
22304 `Index' is a number associated with each task.
22306 @item 
22307 `Task Name' is the name of the task analyzed.
22309 @item 
22310 `Stack Size' is the maximum size for the stack.
22312 @item 
22313 `Stack Usage' is the measure done by the stack analyzer.
22314 In order to prevent overflow, the stack
22315 is not entirely analyzed, and it’s not possible to know exactly how
22316 much has actually been used.
22317 @end itemize
22319 By default the environment task stack, the stack that contains the main unit,
22320 is not processed. To enable processing of the environment task stack, the
22321 environment variable GNAT_STACK_LIMIT needs to be set to the maximum size of
22322 the environment task stack. This amount is given in kilobytes. For example:
22324 @quotation
22326 @example
22327 $ set GNAT_STACK_LIMIT 1600
22328 @end example
22329 @end quotation
22331 would specify to the analyzer that the environment task stack has a limit
22332 of 1.6 megabytes. Any stack usage beyond this will be ignored by the analysis.
22334 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
22335 stack-usage reports at run time. See its body for the details.
22337 @node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
22338 @anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{14e}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{1ae}
22339 @section Memory Management Issues
22342 This section describes some useful memory pools provided in the GNAT library
22343 and in particular the GNAT Debug Pool facility, which can be used to detect
22344 incorrect uses of access values (including ‘dangling references’).
22347 @menu
22348 * Some Useful Memory Pools:: 
22349 * The GNAT Debug Pool Facility:: 
22351 @end menu
22353 @node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
22354 @anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{1af}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{1b0}
22355 @subsection Some Useful Memory Pools
22358 @geindex Memory Pool
22360 @geindex storage
22361 @geindex pool
22363 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
22364 storage pool. Allocations use the standard system call @code{malloc} while
22365 deallocations use the standard system call @code{free}. No reclamation is
22366 performed when the pool goes out of scope. For performance reasons, the
22367 standard default Ada allocators/deallocators do not use any explicit storage
22368 pools but if they did, they could use this storage pool without any change in
22369 behavior. That is why this storage pool is used  when the user
22370 manages to make the default implicit allocator explicit as in this example:
22372 @quotation
22374 @example
22375 type T1 is access Something;
22376  -- no Storage pool is defined for T2
22378 type T2 is access Something_Else;
22379 for T2'Storage_Pool use T1'Storage_Pool;
22380 -- the above is equivalent to
22381 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
22382 @end example
22383 @end quotation
22385 The @code{System.Pool_Local} package offers the @code{Unbounded_Reclaim_Pool} storage
22386 pool. The allocation strategy is similar to @code{Pool_Local}
22387 except that the all
22388 storage allocated with this pool is reclaimed when the pool object goes out of
22389 scope. This pool provides a explicit mechanism similar to the implicit one
22390 provided by several Ada 83 compilers for allocations performed through a local
22391 access type and whose purpose was to reclaim memory when exiting the
22392 scope of a given local access. As an example, the following program does not
22393 leak memory even though it does not perform explicit deallocation:
22395 @quotation
22397 @example
22398 with System.Pool_Local;
22399 procedure Pooloc1 is
22400    procedure Internal is
22401       type A is access Integer;
22402       X : System.Pool_Local.Unbounded_Reclaim_Pool;
22403       for A'Storage_Pool use X;
22404       v : A;
22405    begin
22406       for I in 1 .. 50 loop
22407          v := new Integer;
22408       end loop;
22409    end Internal;
22410 begin
22411    for I in 1 .. 100 loop
22412       Internal;
22413    end loop;
22414 end Pooloc1;
22415 @end example
22416 @end quotation
22418 The @code{System.Pool_Size} package implements the @code{Stack_Bounded_Pool} used when
22419 @code{Storage_Size} is specified for an access type.
22420 The whole storage for the pool is
22421 allocated at once, usually on the stack at the point where the access type is
22422 elaborated. It is automatically reclaimed when exiting the scope where the
22423 access type is defined. This package is not intended to be used directly by the
22424 user and it is implicitly used for each such declaration:
22426 @quotation
22428 @example
22429 type T1 is access Something;
22430 for T1'Storage_Size use 10_000;
22431 @end example
22432 @end quotation
22434 @node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
22435 @anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{1b1}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{1b2}
22436 @subsection The GNAT Debug Pool Facility
22439 @geindex Debug Pool
22441 @geindex storage
22442 @geindex pool
22443 @geindex memory corruption
22445 The use of unchecked deallocation and unchecked conversion can easily
22446 lead to incorrect memory references. The problems generated by such
22447 references are usually difficult to tackle because the symptoms can be
22448 very remote from the origin of the problem. In such cases, it is
22449 very helpful to detect the problem as early as possible. This is the
22450 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
22452 In order to use the GNAT specific debugging pool, the user must
22453 associate a debug pool object with each of the access types that may be
22454 related to suspected memory problems. See Ada Reference Manual 13.11.
22456 @quotation
22458 @example
22459 type Ptr is access Some_Type;
22460 Pool : GNAT.Debug_Pools.Debug_Pool;
22461 for Ptr'Storage_Pool use Pool;
22462 @end example
22463 @end quotation
22465 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
22466 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
22467 allow the user to redefine allocation and deallocation strategies. They
22468 also provide a checkpoint for each dereference, through the use of
22469 the primitive operation @code{Dereference} which is implicitly called at
22470 each dereference of an access value.
22472 Once an access type has been associated with a debug pool, operations on
22473 values of the type may raise four distinct exceptions,
22474 which correspond to four potential kinds of memory corruption:
22477 @itemize *
22479 @item 
22480 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
22482 @item 
22483 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
22485 @item 
22486 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
22488 @item 
22489 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
22490 @end itemize
22492 For types associated with a Debug_Pool, dynamic allocation is performed using
22493 the standard GNAT allocation routine. References to all allocated chunks of
22494 memory are kept in an internal dictionary. Several deallocation strategies are
22495 provided, whereupon the user can choose to release the memory to the system,
22496 keep it allocated for further invalid access checks, or fill it with an easily
22497 recognizable pattern for debug sessions. The memory pattern is the old IBM
22498 hexadecimal convention: @code{16#DEADBEEF#}.
22500 See the documentation in the file g-debpoo.ads for more information on the
22501 various strategies.
22503 Upon each dereference, a check is made that the access value denotes a
22504 properly allocated memory location. Here is a complete example of use of
22505 @code{Debug_Pools}, that includes typical instances of  memory corruption:
22507 @quotation
22509 @example
22510 with GNAT.IO; use GNAT.IO;
22511 with Ada.Unchecked_Deallocation;
22512 with Ada.Unchecked_Conversion;
22513 with GNAT.Debug_Pools;
22514 with System.Storage_Elements;
22515 with Ada.Exceptions; use Ada.Exceptions;
22516 procedure Debug_Pool_Test is
22518    type T is access Integer;
22519    type U is access all T;
22521    P : GNAT.Debug_Pools.Debug_Pool;
22522    for T'Storage_Pool use P;
22524    procedure Free is new Ada.Unchecked_Deallocation (Integer, T);
22525    function UC is new Ada.Unchecked_Conversion (U, T);
22526    A, B : aliased T;
22528    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
22530 begin
22531    Info (P);
22532    A := new Integer;
22533    B := new Integer;
22534    B := A;
22535    Info (P);
22536    Free (A);
22537    begin
22538       Put_Line (Integer'Image(B.all));
22539    exception
22540       when E : others => Put_Line ("raised: " & Exception_Name (E));
22541    end;
22542    begin
22543       Free (B);
22544    exception
22545       when E : others => Put_Line ("raised: " & Exception_Name (E));
22546    end;
22547    B := UC(A'Access);
22548    begin
22549       Put_Line (Integer'Image(B.all));
22550    exception
22551       when E : others => Put_Line ("raised: " & Exception_Name (E));
22552    end;
22553    begin
22554       Free (B);
22555    exception
22556       when E : others => Put_Line ("raised: " & Exception_Name (E));
22557    end;
22558    Info (P);
22559 end Debug_Pool_Test;
22560 @end example
22561 @end quotation
22563 The debug pool mechanism provides the following precise diagnostics on the
22564 execution of this erroneous program:
22566 @quotation
22568 @example
22569 Debug Pool info:
22570   Total allocated bytes :  0
22571   Total deallocated bytes :  0
22572   Current Water Mark:  0
22573   High Water Mark:  0
22575 Debug Pool info:
22576   Total allocated bytes :  8
22577   Total deallocated bytes :  0
22578   Current Water Mark:  8
22579   High Water Mark:  8
22581 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
22582 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
22583 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
22584 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
22585 Debug Pool info:
22586   Total allocated bytes :  8
22587   Total deallocated bytes :  4
22588   Current Water Mark:  4
22589   High Water Mark:  8
22590 @end example
22591 @end quotation
22594 @c -- Non-breaking space in running text
22595 @c -- E.g. Ada |nbsp| 95
22597 @node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
22598 @anchor{gnat_ugn/platform_specific_information doc}@anchor{1b3}@anchor{gnat_ugn/platform_specific_information id1}@anchor{1b4}@anchor{gnat_ugn/platform_specific_information platform-specific-information}@anchor{d}
22599 @chapter Platform-Specific Information
22602 This appendix contains information relating to the implementation
22603 of run-time libraries on various platforms and also covers topics
22604 related to the GNAT implementation on specific Operating Systems.
22606 @menu
22607 * Run-Time Libraries:: 
22608 * Specifying a Run-Time Library:: 
22609 * GNU/Linux Topics:: 
22610 * Microsoft Windows Topics:: 
22611 * Mac OS Topics:: 
22613 @end menu
22615 @node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
22616 @anchor{gnat_ugn/platform_specific_information id2}@anchor{1b5}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{1b6}
22617 @section Run-Time Libraries
22620 @geindex Tasking and threads libraries
22622 @geindex Threads libraries and tasking
22624 @geindex Run-time libraries (platform-specific information)
22626 The GNAT run-time implementation may vary with respect to both the
22627 underlying threads library and the exception-handling scheme.
22628 For threads support, the default run-time will bind to the thread
22629 package of the underlying operating system.
22631 For exception handling, either or both of two models are supplied:
22633 @quotation
22635 @geindex Zero-Cost Exceptions
22637 @geindex ZCX (Zero-Cost Exceptions)
22638 @end quotation
22641 @itemize *
22643 @item 
22644 `Zero-Cost Exceptions' (“ZCX”),
22645 which uses binder-generated tables that
22646 are interrogated at run time to locate a handler.
22648 @geindex setjmp/longjmp Exception Model
22650 @geindex SJLJ (setjmp/longjmp Exception Model)
22652 @item 
22653 `setjmp / longjmp' (‘SJLJ’),
22654 which uses dynamically-set data to establish
22655 the set of handlers
22656 @end itemize
22658 Most programs should experience a substantial speed improvement by
22659 being compiled with a ZCX run-time.
22660 This is especially true for
22661 tasking applications or applications with many exception handlers.
22662 Note however that the ZCX run-time does not support asynchronous abort
22663 of tasks (@code{abort} and @code{select-then-abort} constructs) and will instead
22664 implement abort by polling points in the runtime. You can also add additional
22665 polling points explicitly if needed in your application via @code{pragma
22666 Abort_Defer}.
22668 This section summarizes which combinations of threads and exception support
22669 are supplied on various GNAT platforms.
22671 @menu
22672 * Summary of Run-Time Configurations:: 
22674 @end menu
22676 @node Summary of Run-Time Configurations,,,Run-Time Libraries
22677 @anchor{gnat_ugn/platform_specific_information id3}@anchor{1b7}@anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{1b8}
22678 @subsection Summary of Run-Time Configurations
22682 @multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
22683 @headitem
22685 Platform
22687 @tab
22689 Run-Time
22691 @tab
22693 Tasking
22695 @tab
22697 Exceptions
22699 @item
22701 GNU/Linux
22703 @tab
22705 rts-native
22706 (default)
22708 @tab
22710 pthread library
22712 @tab
22716 @item
22718 rts-sjlj
22720 @tab
22722 pthread library
22724 @tab
22726 SJLJ
22728 @item
22730 Windows
22732 @tab
22734 rts-native
22735 (default)
22737 @tab
22739 native Win32 threads
22741 @tab
22745 @item
22747 rts-sjlj
22749 @tab
22751 native Win32 threads
22753 @tab
22755 SJLJ
22757 @item
22759 Mac OS
22761 @tab
22763 rts-native
22765 @tab
22767 pthread library
22769 @tab
22773 @end multitable
22776 @node Specifying a Run-Time Library,GNU/Linux Topics,Run-Time Libraries,Platform-Specific Information
22777 @anchor{gnat_ugn/platform_specific_information id4}@anchor{1b9}@anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{1ba}
22778 @section Specifying a Run-Time Library
22781 The @code{adainclude} subdirectory containing the sources of the GNAT
22782 run-time library, and the @code{adalib} subdirectory containing the
22783 @code{ALI} files and the static and/or shared GNAT library, are located
22784 in the gcc target-dependent area:
22786 @quotation
22788 @example
22789 target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
22790 @end example
22791 @end quotation
22793 As indicated above, on some platforms several run-time libraries are supplied.
22794 These libraries are installed in the target dependent area and
22795 contain a complete source and binary subdirectory. The detailed description
22796 below explains the differences between the different libraries in terms of
22797 their thread support.
22799 The default run-time library (when GNAT is installed) is `rts-native'.
22800 This default run-time is selected by the means of soft links.
22801 For example on x86-linux:
22803 @c --
22804 @c --  $(target-dir)
22805 @c --      |
22806 @c --      +--- adainclude----------+
22807 @c --      |                        |
22808 @c --      +--- adalib-----------+  |
22809 @c --      |                     |  |
22810 @c --      +--- rts-native       |  |
22811 @c --      |    |                |  |
22812 @c --      |    +--- adainclude <---+
22813 @c --      |    |                |
22814 @c --      |    +--- adalib <----+
22815 @c --      |
22816 @c --      +--- rts-sjlj
22817 @c --           |
22818 @c --           +--- adainclude
22819 @c --           |
22820 @c --           +--- adalib
22823 @example
22824                $(target-dir)
22825               __/ /      \ \___
22826       _______/   /        \    \_________________
22827      /          /          \                     \
22828     /          /            \                     \
22829 ADAINCLUDE  ADALIB      rts-native             rts-sjlj
22830    :          :            /    \                 /   \
22831    :          :           /      \               /     \
22832    :          :          /        \             /       \
22833    :          :         /          \           /         \
22834    +-------------> adainclude     adalib   adainclude   adalib
22835               :                     ^
22836               :                     :
22837               +---------------------+
22839               Run-Time Library Directory Structure
22840    (Upper-case names and dotted/dashed arrows represent soft links)
22841 @end example
22843 If the `rts-sjlj' library is to be selected on a permanent basis,
22844 these soft links can be modified with the following commands:
22846 @quotation
22848 @example
22849 $ cd $target
22850 $ rm -f adainclude adalib
22851 $ ln -s rts-sjlj/adainclude adainclude
22852 $ ln -s rts-sjlj/adalib adalib
22853 @end example
22854 @end quotation
22856 Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
22857 @code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
22858 @code{$target/ada_object_path}.
22860 @geindex --RTS option
22862 Selecting another run-time library temporarily can be
22863 achieved by using the @code{--RTS} switch, e.g., @code{--RTS=sjlj}
22864 @anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{1bb}
22865 @geindex SCHED_FIFO scheduling policy
22867 @geindex SCHED_RR scheduling policy
22869 @geindex SCHED_OTHER scheduling policy
22871 @menu
22872 * Choosing the Scheduling Policy:: 
22874 @end menu
22876 @node Choosing the Scheduling Policy,,,Specifying a Run-Time Library
22877 @anchor{gnat_ugn/platform_specific_information id5}@anchor{1bc}
22878 @subsection Choosing the Scheduling Policy
22881 When using a POSIX threads implementation, you have a choice of several
22882 scheduling policies: @code{SCHED_FIFO}, @code{SCHED_RR} and @code{SCHED_OTHER}.
22884 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22885 or @code{SCHED_RR} requires special (e.g., root) privileges.
22887 @geindex pragma Time_Slice
22889 @geindex -T0 option
22891 @geindex pragma Task_Dispatching_Policy
22893 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22894 @code{SCHED_FIFO},
22895 you can use one of the following:
22898 @itemize *
22900 @item 
22901 @code{pragma Time_Slice (0.0)}
22903 @item 
22904 the corresponding binder option @code{-T0}
22906 @item 
22907 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22908 @end itemize
22910 To specify @code{SCHED_RR},
22911 you should use @code{pragma Time_Slice} with a
22912 value greater than 0.0, or else use the corresponding @code{-T}
22913 binder option.
22915 To make sure a program is running as root, you can put something like
22916 this in a library package body in your application:
22918 @quotation
22920 @example
22921 function geteuid return Integer;
22922 pragma Import (C, geteuid, "geteuid");
22923 Ignore : constant Boolean :=
22924   (if geteuid = 0 then True else raise Program_Error with "must be root");
22925 @end example
22926 @end quotation
22928 It gets the effective user id, and if it’s not 0 (i.e. root), it raises
22929 Program_Error. Note that if you re running the code in a container, this may
22930 not be sufficient, as you may have sufficient priviledge on the container,
22931 but not on the host machine running the container, so check that you also
22932 have sufficient priviledge for running the container image.
22934 @geindex Linux
22936 @geindex GNU/Linux
22938 @node GNU/Linux Topics,Microsoft Windows Topics,Specifying a Run-Time Library,Platform-Specific Information
22939 @anchor{gnat_ugn/platform_specific_information gnu-linux-topics}@anchor{1bd}@anchor{gnat_ugn/platform_specific_information id6}@anchor{1be}
22940 @section GNU/Linux Topics
22943 This section describes topics that are specific to GNU/Linux platforms.
22945 @menu
22946 * Required Packages on GNU/Linux:: 
22947 * Position Independent Executable (PIE) Enabled by Default on Linux: Position Independent Executable PIE Enabled by Default on Linux. 
22948 * A GNU/Linux Debug Quirk:: 
22950 @end menu
22952 @node Required Packages on GNU/Linux,Position Independent Executable PIE Enabled by Default on Linux,,GNU/Linux Topics
22953 @anchor{gnat_ugn/platform_specific_information id7}@anchor{1bf}@anchor{gnat_ugn/platform_specific_information required-packages-on-gnu-linux}@anchor{1c0}
22954 @subsection Required Packages on GNU/Linux
22957 GNAT requires the C library developer’s package to be installed.
22958 The name of of that package depends on your GNU/Linux distribution:
22961 @itemize *
22963 @item 
22964 RedHat, SUSE: @code{glibc-devel};
22966 @item 
22967 Debian, Ubuntu: @code{libc6-dev} (normally installed by default).
22968 @end itemize
22970 If using the 32-bit version of GNAT on a 64-bit version of GNU/Linux,
22971 you’ll need the 32-bit version of the following packages:
22974 @itemize *
22976 @item 
22977 RedHat, SUSE: @code{glibc.i686}, @code{glibc-devel.i686}, @code{ncurses-libs.i686}
22979 @item 
22980 SUSE: @code{glibc-locale-base-32bit}
22982 @item 
22983 Debian, Ubuntu: @code{libc6:i386}, @code{libc6-dev:i386}, @code{lib32ncursesw5}
22984 @end itemize
22986 Other GNU/Linux distributions might be choosing a different name
22987 for those packages.
22989 @node Position Independent Executable PIE Enabled by Default on Linux,A GNU/Linux Debug Quirk,Required Packages on GNU/Linux,GNU/Linux Topics
22990 @anchor{gnat_ugn/platform_specific_information pie-enabled-by-default-on-linux}@anchor{1c1}@anchor{gnat_ugn/platform_specific_information position-independent-executable-pie-enabled-by-default-on-linux}@anchor{1c2}
22991 @subsection Position Independent Executable (PIE) Enabled by Default on Linux
22994 GNAT generates Position Independent Executable (PIE) code by default.
22995 PIE binaries are loaded into random memory locations, introducing
22996 an additional layer of protection against attacks.
22998 Building PIE binaries requires that all of their dependencies also be
22999 built as Position Independent. If the link of your project fails with
23000 an error like:
23002 @example
23003 /[...]/ld: /path/to/object/file: relocation R_X86_64_32S against symbol
23004 `symbol name' can not be used when making a PIE object;
23005 recompile with -fPIE
23006 @end example
23008 it means the identified object file has not been built as Position
23009 Independent.
23011 If you are not interested in building PIE binaries, you can simply
23012 turn this feature off by first compiling your code with @code{-fno-pie}
23013 and then by linking with @code{-no-pie} (note the subtle but important
23014 difference in the names of the options – the linker option does `not'
23015 have an @cite{f} after the dash!). When using gprbuild, this is
23016 achieved by updating the `Required_Switches' attribute in package @cite{Compiler}
23017 and, depending on your type of project, either attribute `Switches'
23018 or attribute `Library_Options' in package @cite{Linker}.
23020 On the other hand, if you would like to build PIE binaries and you are
23021 getting the error above, a quick and easy workaround to allow linking
23022 to succeed again is to disable PIE during the link, thus temporarily
23023 lifting the requirement that all dependencies also be Position
23024 Independent code. To do so, you simply need to add @code{-no-pie} to
23025 the list of switches passed to the linker. As part of this workaround,
23026 there is no need to adjust the compiler switches.
23028 From there, to be able to link your binaries with PIE and therefore
23029 drop the @code{-no-pie} workaround, you’ll need to get the identified
23030 dependencies rebuilt with PIE enabled (compiled with @code{-fPIE}
23031 and linked with @code{-pie}).
23033 @node A GNU/Linux Debug Quirk,,Position Independent Executable PIE Enabled by Default on Linux,GNU/Linux Topics
23034 @anchor{gnat_ugn/platform_specific_information a-gnu-linux-debug-quirk}@anchor{1c3}@anchor{gnat_ugn/platform_specific_information id8}@anchor{1c4}
23035 @subsection A GNU/Linux Debug Quirk
23038 On SuSE 15, some kernels have a defect causing issues when debugging
23039 programs using threads or Ada tasks. Due to the lack of documentation
23040 found regarding this kernel issue, we can only provide limited
23041 information about which kernels are impacted: kernel version 5.3.18 is
23042 known to be impacted, and kernels in the 5.14 range or newer are
23043 believed to fix this problem.
23045 The bug affects the debugging of 32-bit processes on a 64-bit system.
23046 Symptoms can vary: Unexpected @code{SIGABRT} signals being received by
23047 the program, “The futex facility returned an unexpected error code”
23048 error message, and inferior programs hanging indefinitely range among
23049 the symptoms most commonly observed.
23051 @geindex Windows
23053 @node Microsoft Windows Topics,Mac OS Topics,GNU/Linux Topics,Platform-Specific Information
23054 @anchor{gnat_ugn/platform_specific_information id9}@anchor{1c5}@anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{1c6}
23055 @section Microsoft Windows Topics
23058 This section describes topics that are specific to the Microsoft Windows
23059 platforms.
23062 @menu
23063 * Using GNAT on Windows:: 
23064 * Using a network installation of GNAT:: 
23065 * CONSOLE and WINDOWS subsystems:: 
23066 * Temporary Files:: 
23067 * Disabling Command Line Argument Expansion:: 
23068 * Windows Socket Timeouts:: 
23069 * Mixed-Language Programming on Windows:: 
23070 * Windows Specific Add-Ons:: 
23072 @end menu
23074 @node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
23075 @anchor{gnat_ugn/platform_specific_information id10}@anchor{1c7}@anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{1c8}
23076 @subsection Using GNAT on Windows
23079 One of the strengths of the GNAT technology is that its tool set
23080 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
23081 @code{gdb} debugger, etc.) is used in the same way regardless of the
23082 platform.
23084 On Windows this tool set is complemented by a number of Microsoft-specific
23085 tools that have been provided to facilitate interoperability with Windows
23086 when this is required. With these tools:
23089 @itemize *
23091 @item 
23092 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
23093 subsystems.
23095 @item 
23096 You can use any Dynamically Linked Library (DLL) in your Ada code (both
23097 relocatable and non-relocatable DLLs are supported).
23099 @item 
23100 You can build Ada DLLs for use in other applications. These applications
23101 can be written in a language other than Ada (e.g., C, C++, etc). Again both
23102 relocatable and non-relocatable Ada DLLs are supported.
23104 @item 
23105 You can include Windows resources in your Ada application.
23107 @item 
23108 You can use or create COM/DCOM objects.
23109 @end itemize
23111 Immediately below are listed all known general GNAT-for-Windows restrictions.
23112 Other restrictions about specific features like Windows Resources and DLLs
23113 are listed in separate sections below.
23116 @itemize *
23118 @item 
23119 It is not possible to use @code{GetLastError} and @code{SetLastError}
23120 when tasking, protected records, or exceptions are used. In these
23121 cases, in order to implement Ada semantics, the GNAT run-time system
23122 calls certain Win32 routines that set the last error variable to 0 upon
23123 success. It should be possible to use @code{GetLastError} and
23124 @code{SetLastError} when tasking, protected record, and exception
23125 features are not used, but it is not guaranteed to work.
23127 @item 
23128 It is not possible to link against Microsoft C++ libraries except for
23129 import libraries. Interfacing must be done by the mean of DLLs.
23131 @item 
23132 It is possible to link against Microsoft C libraries. Yet the preferred
23133 solution is to use C/C++ compiler that comes with GNAT, since it
23134 doesn’t require having two different development environments and makes the
23135 inter-language debugging experience smoother.
23137 @item 
23138 When the compilation environment is located on FAT32 drives, users may
23139 experience recompilations of the source files that have not changed if
23140 Daylight Saving Time (DST) state has changed since the last time files
23141 were compiled. NTFS drives do not have this problem.
23143 @item 
23144 No components of the GNAT toolset use any entries in the Windows
23145 registry. The only entries that can be created are file associations and
23146 PATH settings, provided the user has chosen to create them at installation
23147 time, as well as some minimal book-keeping information needed to correctly
23148 uninstall or integrate different GNAT products.
23149 @end itemize
23151 @node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
23152 @anchor{gnat_ugn/platform_specific_information id11}@anchor{1c9}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{1ca}
23153 @subsection Using a network installation of GNAT
23156 Make sure the system on which GNAT is installed is accessible from the
23157 current machine, i.e., the install location is shared over the network.
23158 Shared resources are accessed on Windows by means of UNC paths, which
23159 have the format @code{\\\\server\\sharename\\path}
23161 In order to use such a network installation, simply add the UNC path of the
23162 @code{bin} directory of your GNAT installation in front of your PATH. For
23163 example, if GNAT is installed in @code{\GNAT} directory of a share location
23164 called @code{c-drive} on a machine @code{LOKI}, the following command will
23165 make it available:
23167 @quotation
23169 @example
23170 $ path \\loki\c-drive\gnat\bin;%path%`
23171 @end example
23172 @end quotation
23174 Be aware that every compilation using the network installation results in the
23175 transfer of large amounts of data across the network and will likely cause
23176 serious performance penalty.
23178 @node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
23179 @anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{1cb}@anchor{gnat_ugn/platform_specific_information id12}@anchor{1cc}
23180 @subsection CONSOLE and WINDOWS subsystems
23183 @geindex CONSOLE Subsystem
23185 @geindex WINDOWS Subsystem
23187 @geindex -mwindows
23189 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
23190 (which is the default subsystem) will always create a console when
23191 launching the application. This is not something desirable when the
23192 application has a Windows GUI. To get rid of this console the
23193 application must be using the @code{WINDOWS} subsystem. To do so
23194 the @code{-mwindows} linker option must be specified.
23196 @quotation
23198 @example
23199 $ gnatmake winprog -largs -mwindows
23200 @end example
23201 @end quotation
23203 @node Temporary Files,Disabling Command Line Argument Expansion,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
23204 @anchor{gnat_ugn/platform_specific_information id13}@anchor{1cd}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{1ce}
23205 @subsection Temporary Files
23208 @geindex Temporary files
23210 It is possible to control where temporary files gets created by setting
23211 the 
23212 @geindex TMP
23213 @geindex environment variable; TMP
23214 @code{TMP} environment variable. The file will be created:
23217 @itemize *
23219 @item 
23220 Under the directory pointed to by the 
23221 @geindex TMP
23222 @geindex environment variable; TMP
23223 @code{TMP} environment variable if
23224 this directory exists.
23226 @item 
23227 Under @code{c:\temp}, if the 
23228 @geindex TMP
23229 @geindex environment variable; TMP
23230 @code{TMP} environment variable is not
23231 set (or not pointing to a directory) and if this directory exists.
23233 @item 
23234 Under the current working directory otherwise.
23235 @end itemize
23237 This allows you to determine exactly where the temporary
23238 file will be created. This is particularly useful in networked
23239 environments where you may not have write access to some
23240 directories.
23242 @node Disabling Command Line Argument Expansion,Windows Socket Timeouts,Temporary Files,Microsoft Windows Topics
23243 @anchor{gnat_ugn/platform_specific_information disabling-command-line-argument-expansion}@anchor{1cf}
23244 @subsection Disabling Command Line Argument Expansion
23247 @geindex Command Line Argument Expansion
23249 By default, an executable compiled for the Windows platform will do
23250 the following postprocessing on the arguments passed on the command
23251 line:
23254 @itemize *
23256 @item 
23257 If the argument contains the characters @code{*} and/or @code{?}, then
23258 file expansion will be attempted. For example, if the current directory
23259 contains @code{a.txt} and @code{b.txt}, then when calling:
23261 @example
23262 $ my_ada_program *.txt
23263 @end example
23265 The following arguments will effectively be passed to the main program
23266 (for example when using @code{Ada.Command_Line.Argument}):
23268 @example
23269 Ada.Command_Line.Argument (1) -> "a.txt"
23270 Ada.Command_Line.Argument (2) -> "b.txt"
23271 @end example
23273 @item 
23274 Filename expansion can be disabled for a given argument by using single
23275 quotes. Thus, calling:
23277 @example
23278 $ my_ada_program '*.txt'
23279 @end example
23281 will result in:
23283 @example
23284 Ada.Command_Line.Argument (1) -> "*.txt"
23285 @end example
23286 @end itemize
23288 Note that if the program is launched from a shell such as Cygwin Bash
23289 then quote removal might be performed by the shell.
23291 In some contexts it might be useful to disable this feature (for example if
23292 the program performs its own argument expansion). In order to do this, a C
23293 symbol needs to be defined and set to @code{0}. You can do this by
23294 adding the following code fragment in one of your Ada units:
23296 @example
23297 Do_Argv_Expansion : Integer := 0;
23298 pragma Export (C, Do_Argv_Expansion, "__gnat_do_argv_expansion");
23299 @end example
23301 The results of previous examples will be respectively:
23303 @example
23304 Ada.Command_Line.Argument (1) -> "*.txt"
23305 @end example
23307 and:
23309 @example
23310 Ada.Command_Line.Argument (1) -> "'*.txt'"
23311 @end example
23313 @node Windows Socket Timeouts,Mixed-Language Programming on Windows,Disabling Command Line Argument Expansion,Microsoft Windows Topics
23314 @anchor{gnat_ugn/platform_specific_information windows-socket-timeouts}@anchor{1d0}
23315 @subsection Windows Socket Timeouts
23318 Microsoft Windows desktops older than @code{8.0} and Microsoft Windows Servers
23319 older than @code{2019} set a socket timeout 500 milliseconds longer than the value
23320 set by setsockopt with @code{SO_RCVTIMEO} and @code{SO_SNDTIMEO} options. The GNAT
23321 runtime makes a correction for the difference in the corresponding Windows
23322 versions. For Windows Server starting with version @code{2019}, the user must
23323 provide a manifest file for the GNAT runtime to be able to recognize that
23324 the Windows version does not need the timeout correction. The manifest file
23325 should be located in the same directory as the executable file, and its file
23326 name must match the executable name suffixed by @code{.manifest}. For example,
23327 if the executable name is @code{sock_wto.exe}, then the manifest file name
23328 has to be @code{sock_wto.exe.manifest}. The manifest file must contain at
23329 least the following data:
23331 @example
23332 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
23333 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
23334 <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
23335 <application>
23336    <!-- Windows Vista -->
23337    <supportedOS Id="@{e2011457-1546-43c5-a5fe-008deee3d3f0@}"/>
23338    <!-- Windows 7 -->
23339    <supportedOS Id="@{35138b9a-5d96-4fbd-8e2d-a2440225f93a@}"/>
23340    <!-- Windows 8 -->
23341    <supportedOS Id="@{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38@}"/>
23342    <!-- Windows 8.1 -->
23343    <supportedOS Id="@{1f676c76-80e1-4239-95bb-83d0f6d0da78@}"/>
23344    <!-- Windows 10 -->
23345    <supportedOS Id="@{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a@}"/>
23346 </application>
23347 </compatibility>
23348 </assembly>
23349 @end example
23351 Without the manifest file, the socket timeout is going to be overcorrected on
23352 these Windows Server versions and the actual time is going to be 500
23353 milliseconds shorter than what was set with GNAT.Sockets.Set_Socket_Option.
23354 Note that on Microsoft Windows versions where correction is necessary, there
23355 is no way to set a socket timeout shorter than 500 ms. If a socket timeout
23356 shorter than 500 ms is needed on these Windows versions, a call to
23357 Check_Selector should be added before any socket read or write operations.
23359 @node Mixed-Language Programming on Windows,Windows Specific Add-Ons,Windows Socket Timeouts,Microsoft Windows Topics
23360 @anchor{gnat_ugn/platform_specific_information id14}@anchor{1d1}@anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{1d2}
23361 @subsection Mixed-Language Programming on Windows
23364 Developing pure Ada applications on Windows is no different than on
23365 other GNAT-supported platforms. However, when developing or porting an
23366 application that contains a mix of Ada and C/C++, the choice of your
23367 Windows C/C++ development environment conditions your overall
23368 interoperability strategy.
23370 If you use @code{gcc} or Microsoft C to compile the non-Ada part of
23371 your application, there are no Windows-specific restrictions that
23372 affect the overall interoperability with your Ada code. If you do want
23373 to use the Microsoft tools for your C++ code, you have two choices:
23376 @itemize *
23378 @item 
23379 Encapsulate your C++ code in a DLL to be linked with your Ada
23380 application. In this case, use the Microsoft or whatever environment to
23381 build the DLL and use GNAT to build your executable
23382 (@ref{1d3,,Using DLLs with GNAT}).
23384 @item 
23385 Or you can encapsulate your Ada code in a DLL to be linked with the
23386 other part of your application. In this case, use GNAT to build the DLL
23387 (@ref{1d4,,Building DLLs with GNAT Project files}) and use the Microsoft
23388 or whatever environment to build your executable.
23389 @end itemize
23391 In addition to the description about C main in
23392 @ref{2c,,Mixed Language Programming} section, if the C main uses a
23393 stand-alone library it is required on x86-windows to
23394 setup the SEH context. For this the C main must looks like this:
23396 @quotation
23398 @example
23399 /* main.c */
23400 extern void adainit (void);
23401 extern void adafinal (void);
23402 extern void __gnat_initialize(void*);
23403 extern void call_to_ada (void);
23405 int main (int argc, char *argv[])
23407   int SEH [2];
23409   /* Initialize the SEH context */
23410   __gnat_initialize (&SEH);
23412   adainit();
23414   /* Then call Ada services in the stand-alone library */
23416   call_to_ada();
23418   adafinal();
23420 @end example
23421 @end quotation
23423 Note that this is not needed on x86_64-windows where the Windows
23424 native SEH support is used.
23426 @menu
23427 * Windows Calling Conventions:: 
23428 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
23429 * Using DLLs with GNAT:: 
23430 * Building DLLs with GNAT Project files:: 
23431 * Building DLLs with GNAT:: 
23432 * Building DLLs with gnatdll:: 
23433 * Ada DLLs and Finalization:: 
23434 * Creating a Spec for Ada DLLs:: 
23435 * GNAT and Windows Resources:: 
23436 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
23437 * Debugging a DLL:: 
23438 * Setting Stack Size from gnatlink:: 
23439 * Setting Heap Size from gnatlink:: 
23441 @end menu
23443 @node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
23444 @anchor{gnat_ugn/platform_specific_information id15}@anchor{1d5}@anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{1d6}
23445 @subsubsection Windows Calling Conventions
23448 @geindex Stdcall
23450 @geindex APIENTRY
23452 This section pertain only to Win32. On Win64 there is a single native
23453 calling convention. All convention specifiers are ignored on this
23454 platform.
23456 When a subprogram @code{F} (caller) calls a subprogram @code{G}
23457 (callee), there are several ways to push @code{G}‘s parameters on the
23458 stack and there are several possible scenarios to clean up the stack
23459 upon @code{G}‘s return. A calling convention is an agreed upon software
23460 protocol whereby the responsibilities between the caller (@code{F}) and
23461 the callee (@code{G}) are clearly defined. Several calling conventions
23462 are available for Windows:
23465 @itemize *
23467 @item 
23468 @code{C} (Microsoft defined)
23470 @item 
23471 @code{Stdcall} (Microsoft defined)
23473 @item 
23474 @code{Win32} (GNAT specific)
23476 @item 
23477 @code{DLL} (GNAT specific)
23478 @end itemize
23480 @menu
23481 * C Calling Convention:: 
23482 * Stdcall Calling Convention:: 
23483 * Win32 Calling Convention:: 
23484 * DLL Calling Convention:: 
23486 @end menu
23488 @node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
23489 @anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{1d7}@anchor{gnat_ugn/platform_specific_information id16}@anchor{1d8}
23490 @subsubsection @code{C} Calling Convention
23493 This is the default calling convention used when interfacing to C/C++
23494 routines compiled with either @code{gcc} or Microsoft Visual C++.
23496 In the @code{C} calling convention subprogram parameters are pushed on the
23497 stack by the caller from right to left. The caller itself is in charge of
23498 cleaning up the stack after the call. In addition, the name of a routine
23499 with @code{C} calling convention is mangled by adding a leading underscore.
23501 The name to use on the Ada side when importing (or exporting) a routine
23502 with @code{C} calling convention is the name of the routine. For
23503 instance the C function:
23505 @quotation
23507 @example
23508 int get_val (long);
23509 @end example
23510 @end quotation
23512 should be imported from Ada as follows:
23514 @quotation
23516 @example
23517 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23518 pragma Import (C, Get_Val, External_Name => "get_val");
23519 @end example
23520 @end quotation
23522 Note that in this particular case the @code{External_Name} parameter could
23523 have been omitted since, when missing, this parameter is taken to be the
23524 name of the Ada entity in lower case. When the @code{Link_Name} parameter
23525 is missing, as in the above example, this parameter is set to be the
23526 @code{External_Name} with a leading underscore.
23528 When importing a variable defined in C, you should always use the @code{C}
23529 calling convention unless the object containing the variable is part of a
23530 DLL (in which case you should use the @code{Stdcall} calling
23531 convention, @ref{1d9,,Stdcall Calling Convention}).
23533 @node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
23534 @anchor{gnat_ugn/platform_specific_information id17}@anchor{1da}@anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{1d9}
23535 @subsubsection @code{Stdcall} Calling Convention
23538 This convention, which was the calling convention used for Pascal
23539 programs, is used by Microsoft for all the routines in the Win32 API for
23540 efficiency reasons. It must be used to import any routine for which this
23541 convention was specified.
23543 In the @code{Stdcall} calling convention subprogram parameters are pushed
23544 on the stack by the caller from right to left. The callee (and not the
23545 caller) is in charge of cleaning the stack on routine exit. In addition,
23546 the name of a routine with @code{Stdcall} calling convention is mangled by
23547 adding a leading underscore (as for the @code{C} calling convention) and a
23548 trailing @code{@@@var{nn}}, where @code{nn} is the overall size (in
23549 bytes) of the parameters passed to the routine.
23551 The name to use on the Ada side when importing a C routine with a
23552 @code{Stdcall} calling convention is the name of the C routine. The leading
23553 underscore and trailing @code{@@@var{nn}} are added automatically by
23554 the compiler. For instance the Win32 function:
23556 @quotation
23558 @example
23559 APIENTRY int get_val (long);
23560 @end example
23561 @end quotation
23563 should be imported from Ada as follows:
23565 @quotation
23567 @example
23568 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23569 pragma Import (Stdcall, Get_Val);
23570 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
23571 @end example
23572 @end quotation
23574 As for the @code{C} calling convention, when the @code{External_Name}
23575 parameter is missing, it is taken to be the name of the Ada entity in lower
23576 case. If instead of writing the above import pragma you write:
23578 @quotation
23580 @example
23581 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23582 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
23583 @end example
23584 @end quotation
23586 then the imported routine is @code{_retrieve_val@@4}. However, if instead
23587 of specifying the @code{External_Name} parameter you specify the
23588 @code{Link_Name} as in the following example:
23590 @quotation
23592 @example
23593 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23594 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
23595 @end example
23596 @end quotation
23598 then the imported routine is @code{retrieve_val}, that is, there is no
23599 decoration at all. No leading underscore and no Stdcall suffix
23600 @code{@@@var{nn}}.
23602 This is especially important as in some special cases a DLL’s entry
23603 point name lacks a trailing @code{@@@var{nn}} while the exported
23604 name generated for a call has it.
23606 It is also possible to import variables defined in a DLL by using an
23607 import pragma for a variable. As an example, if a DLL contains a
23608 variable defined as:
23610 @quotation
23612 @example
23613 int my_var;
23614 @end example
23615 @end quotation
23617 then, to access this variable from Ada you should write:
23619 @quotation
23621 @example
23622 My_Var : Interfaces.C.int;
23623 pragma Import (Stdcall, My_Var);
23624 @end example
23625 @end quotation
23627 Note that to ease building cross-platform bindings this convention
23628 will be handled as a @code{C} calling convention on non-Windows platforms.
23630 @node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
23631 @anchor{gnat_ugn/platform_specific_information id18}@anchor{1db}@anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{1dc}
23632 @subsubsection @code{Win32} Calling Convention
23635 This convention, which is GNAT-specific is fully equivalent to the
23636 @code{Stdcall} calling convention described above.
23638 @node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
23639 @anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{1dd}@anchor{gnat_ugn/platform_specific_information id19}@anchor{1de}
23640 @subsubsection @code{DLL} Calling Convention
23643 This convention, which is GNAT-specific is fully equivalent to the
23644 @code{Stdcall} calling convention described above.
23646 @node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
23647 @anchor{gnat_ugn/platform_specific_information id20}@anchor{1df}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{1e0}
23648 @subsubsection Introduction to Dynamic Link Libraries (DLLs)
23651 @geindex DLL
23653 A Dynamically Linked Library (DLL) is a library that can be shared by
23654 several applications running under Windows. A DLL can contain any number of
23655 routines and variables.
23657 One advantage of DLLs is that you can change and enhance them without
23658 forcing all the applications that depend on them to be relinked or
23659 recompiled. However, you should be aware than all calls to DLL routines are
23660 slower since, as you will understand below, such calls are indirect.
23662 To illustrate the remainder of this section, suppose that an application
23663 wants to use the services of a DLL @code{API.dll}. To use the services
23664 provided by @code{API.dll} you must statically link against the DLL or
23665 an import library which contains a jump table with an entry for each
23666 routine and variable exported by the DLL. In the Microsoft world this
23667 import library is called @code{API.lib}. When using GNAT this import
23668 library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
23669 @code{libAPI.a} or @code{libapi.a} (names are case insensitive).
23671 After you have linked your application with the DLL or the import library
23672 and you run your application, here is what happens:
23675 @itemize *
23677 @item 
23678 Your application is loaded into memory.
23680 @item 
23681 The DLL @code{API.dll} is mapped into the address space of your
23682 application. This means that:
23685 @itemize -
23687 @item 
23688 The DLL will use the stack of the calling thread.
23690 @item 
23691 The DLL will use the virtual address space of the calling process.
23693 @item 
23694 The DLL will allocate memory from the virtual address space of the calling
23695 process.
23697 @item 
23698 Handles (pointers) can be safely exchanged between routines in the DLL
23699 routines and routines in the application using the DLL.
23700 @end itemize
23702 @item 
23703 The entries in the jump table (from the import library @code{libAPI.dll.a}
23704 or @code{API.lib} or automatically created when linking against a DLL)
23705 which is part of your application are initialized with the addresses
23706 of the routines and variables in @code{API.dll}.
23708 @item 
23709 If present in @code{API.dll}, routines @code{DllMain} or
23710 @code{DllMainCRTStartup} are invoked. These routines typically contain
23711 the initialization code needed for the well-being of the routines and
23712 variables exported by the DLL.
23713 @end itemize
23715 There is an additional point which is worth mentioning. In the Windows
23716 world there are two kind of DLLs: relocatable and non-relocatable
23717 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
23718 in the target application address space. If the addresses of two
23719 non-relocatable DLLs overlap and these happen to be used by the same
23720 application, a conflict will occur and the application will run
23721 incorrectly. Hence, when possible, it is always preferable to use and
23722 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
23723 supported by GNAT. Note that the @code{-s} linker option (see GNU Linker
23724 User’s Guide) removes the debugging symbols from the DLL but the DLL can
23725 still be relocated.
23727 As a side note, an interesting difference between Microsoft DLLs and
23728 Unix shared libraries, is the fact that on most Unix systems all public
23729 routines are exported by default in a Unix shared library, while under
23730 Windows it is possible (but not required) to list exported routines in
23731 a definition file (see @ref{1e1,,The Definition File}).
23733 @node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
23734 @anchor{gnat_ugn/platform_specific_information id21}@anchor{1e2}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{1d3}
23735 @subsubsection Using DLLs with GNAT
23738 To use the services of a DLL, say @code{API.dll}, in your Ada application
23739 you must have:
23742 @itemize *
23744 @item 
23745 The Ada spec for the routines and/or variables you want to access in
23746 @code{API.dll}. If not available this Ada spec must be built from the C/C++
23747 header files provided with the DLL.
23749 @item 
23750 The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
23751 mentioned an import library is a statically linked library containing the
23752 import table which will be filled at load time to point to the actual
23753 @code{API.dll} routines. Sometimes you don’t have an import library for the
23754 DLL you want to use. The following sections will explain how to build
23755 one. Note that this is optional.
23757 @item 
23758 The actual DLL, @code{API.dll}.
23759 @end itemize
23761 Once you have all the above, to compile an Ada application that uses the
23762 services of @code{API.dll} and whose main subprogram is @code{My_Ada_App},
23763 you simply issue the command
23765 @quotation
23767 @example
23768 $ gnatmake my_ada_app -largs -lAPI
23769 @end example
23770 @end quotation
23772 The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
23773 tells the GNAT linker to look for an import library. The linker will
23774 look for a library name in this specific order:
23777 @itemize *
23779 @item 
23780 @code{libAPI.dll.a}
23782 @item 
23783 @code{API.dll.a}
23785 @item 
23786 @code{libAPI.a}
23788 @item 
23789 @code{API.lib}
23791 @item 
23792 @code{libAPI.dll}
23794 @item 
23795 @code{API.dll}
23796 @end itemize
23798 The first three are the GNU style import libraries. The third is the
23799 Microsoft style import libraries. The last two are the actual DLL names.
23801 Note that if the Ada package spec for @code{API.dll} contains the
23802 following pragma
23804 @quotation
23806 @example
23807 pragma Linker_Options ("-lAPI");
23808 @end example
23809 @end quotation
23811 you do not have to add @code{-largs -lAPI} at the end of the
23812 @code{gnatmake} command.
23814 If any one of the items above is missing you will have to create it
23815 yourself. The following sections explain how to do so using as an
23816 example a fictitious DLL called @code{API.dll}.
23818 @menu
23819 * Creating an Ada Spec for the DLL Services:: 
23820 * Creating an Import Library:: 
23822 @end menu
23824 @node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
23825 @anchor{gnat_ugn/platform_specific_information creating-an-ada-spec-for-the-dll-services}@anchor{1e3}@anchor{gnat_ugn/platform_specific_information id22}@anchor{1e4}
23826 @subsubsection Creating an Ada Spec for the DLL Services
23829 A DLL typically comes with a C/C++ header file which provides the
23830 definitions of the routines and variables exported by the DLL. The Ada
23831 equivalent of this header file is a package spec that contains definitions
23832 for the imported entities. If the DLL you intend to use does not come with
23833 an Ada spec you have to generate one such spec yourself. For example if
23834 the header file of @code{API.dll} is a file @code{api.h} containing the
23835 following two definitions:
23837 @quotation
23839 @example
23840 int some_var;
23841 int get (char *);
23842 @end example
23843 @end quotation
23845 then the equivalent Ada spec could be:
23847 @quotation
23849 @example
23850 with Interfaces.C.Strings;
23851 package API is
23852    use Interfaces;
23854    Some_Var : C.int;
23855    function Get (Str : C.Strings.Chars_Ptr) return C.int;
23857 private
23858    pragma Import (C, Get);
23859    pragma Import (DLL, Some_Var);
23860 end API;
23861 @end example
23862 @end quotation
23864 @node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
23865 @anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{1e5}@anchor{gnat_ugn/platform_specific_information id23}@anchor{1e6}
23866 @subsubsection Creating an Import Library
23869 @geindex Import library
23871 If a Microsoft-style import library @code{API.lib} or a GNAT-style
23872 import library @code{libAPI.dll.a} or @code{libAPI.a} is available
23873 with @code{API.dll} you can skip this section. You can also skip this
23874 section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
23875 as in this case it is possible to link directly against the
23876 DLL. Otherwise read on.
23878 @geindex Definition file
23879 @anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{1e1}
23880 @subsubheading The Definition File
23883 As previously mentioned, and unlike Unix systems, the list of symbols
23884 that are exported from a DLL must be provided explicitly in Windows.
23885 The main goal of a definition file is precisely that: list the symbols
23886 exported by a DLL. A definition file (usually a file with a @code{.def}
23887 suffix) has the following structure:
23889 @quotation
23891 @example
23892 [LIBRARY `@w{`}name`@w{`}]
23893 [DESCRIPTION `@w{`}string`@w{`}]
23894 EXPORTS
23895    `@w{`}symbol1`@w{`}
23896    `@w{`}symbol2`@w{`}
23897    ...
23898 @end example
23899 @end quotation
23902 @table @asis
23904 @item `LIBRARY name'
23906 This section, which is optional, gives the name of the DLL.
23908 @item `DESCRIPTION string'
23910 This section, which is optional, gives a description string that will be
23911 embedded in the import library.
23913 @item `EXPORTS'
23915 This section gives the list of exported symbols (procedures, functions or
23916 variables). For instance in the case of @code{API.dll} the @code{EXPORTS}
23917 section of @code{API.def} looks like:
23919 @example
23920 EXPORTS
23921    some_var
23922    get
23923 @end example
23924 @end table
23926 Note that you must specify the correct suffix (@code{@@@var{nn}})
23927 (see @ref{1d6,,Windows Calling Conventions}) for a Stdcall
23928 calling convention function in the exported symbols list.
23930 There can actually be other sections in a definition file, but these
23931 sections are not relevant to the discussion at hand.
23932 @anchor{gnat_ugn/platform_specific_information create-def-file-automatically}@anchor{1e7}
23933 @subsubheading Creating a Definition File Automatically
23936 You can automatically create the definition file @code{API.def}
23937 (see @ref{1e1,,The Definition File}) from a DLL.
23938 For that use the @code{dlltool} program as follows:
23940 @quotation
23942 @example
23943 $ dlltool API.dll -z API.def --export-all-symbols
23944 @end example
23946 Note that if some routines in the DLL have the @code{Stdcall} convention
23947 (@ref{1d6,,Windows Calling Conventions}) with stripped @code{@@@var{nn}}
23948 suffix then you’ll have to edit @code{api.def} to add it, and specify
23949 @code{-k} to @code{gnatdll} when creating the import library.
23951 Here are some hints to find the right @code{@@@var{nn}} suffix.
23954 @itemize -
23956 @item 
23957 If you have the Microsoft import library (.lib), it is possible to get
23958 the right symbols by using Microsoft @code{dumpbin} tool (see the
23959 corresponding Microsoft documentation for further details).
23961 @example
23962 $ dumpbin /exports api.lib
23963 @end example
23965 @item 
23966 If you have a message about a missing symbol at link time the compiler
23967 tells you what symbol is expected. You just have to go back to the
23968 definition file and add the right suffix.
23969 @end itemize
23970 @end quotation
23971 @anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{1e8}
23972 @subsubheading GNAT-Style Import Library
23975 To create a static import library from @code{API.dll} with the GNAT tools
23976 you should create the .def file, then use @code{gnatdll} tool
23977 (see @ref{1e9,,Using gnatdll}) as follows:
23979 @quotation
23981 @example
23982 $ gnatdll -e API.def -d API.dll
23983 @end example
23985 @code{gnatdll} takes as input a definition file @code{API.def} and the
23986 name of the DLL containing the services listed in the definition file
23987 @code{API.dll}. The name of the static import library generated is
23988 computed from the name of the definition file as follows: if the
23989 definition file name is @code{xyz.def}, the import library name will
23990 be @code{libxyz.a}. Note that in the previous example option
23991 @code{-e} could have been removed because the name of the definition
23992 file (before the @code{.def} suffix) is the same as the name of the
23993 DLL (@ref{1e9,,Using gnatdll} for more information about @code{gnatdll}).
23994 @end quotation
23995 @anchor{gnat_ugn/platform_specific_information msvs-style-import-library}@anchor{1ea}
23996 @subsubheading Microsoft-Style Import Library
23999 A Microsoft import library is needed only if you plan to make an
24000 Ada DLL available to applications developed with Microsoft
24001 tools (@ref{1d2,,Mixed-Language Programming on Windows}).
24003 To create a Microsoft-style import library for @code{API.dll} you
24004 should create the .def file, then build the actual import library using
24005 Microsoft’s @code{lib} utility:
24007 @quotation
24009 @example
24010 $ lib -machine:IX86 -def:API.def -out:API.lib
24011 @end example
24013 If you use the above command the definition file @code{API.def} must
24014 contain a line giving the name of the DLL:
24016 @example
24017 LIBRARY      "API"
24018 @end example
24020 See the Microsoft documentation for further details about the usage of
24021 @code{lib}.
24022 @end quotation
24024 @node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
24025 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{1d4}@anchor{gnat_ugn/platform_specific_information id24}@anchor{1eb}
24026 @subsubsection Building DLLs with GNAT Project files
24029 @geindex DLLs
24030 @geindex building
24032 There is nothing specific to Windows in the build process.
24033 See the `Library Projects' section in the `GNAT Project Manager'
24034 chapter of the `GPRbuild User’s Guide'.
24036 Due to a system limitation, it is not possible under Windows to create threads
24037 when inside the @code{DllMain} routine which is used for auto-initialization
24038 of shared libraries, so it is not possible to have library level tasks in SALs.
24040 @node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
24041 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{1ec}@anchor{gnat_ugn/platform_specific_information id25}@anchor{1ed}
24042 @subsubsection Building DLLs with GNAT
24045 @geindex DLLs
24046 @geindex building
24048 This section explain how to build DLLs using the GNAT built-in DLL
24049 support. With the following procedure it is straight forward to build
24050 and use DLLs with GNAT.
24053 @itemize *
24055 @item 
24056 Building object files.
24057 The first step is to build all objects files that are to be included
24058 into the DLL. This is done by using the standard @code{gnatmake} tool.
24060 @item 
24061 Building the DLL.
24062 To build the DLL you must use the @code{gcc} @code{-shared} and
24063 @code{-shared-libgcc} options. It is quite simple to use this method:
24065 @example
24066 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
24067 @end example
24069 It is important to note that in this case all symbols found in the
24070 object files are automatically exported. It is possible to restrict
24071 the set of symbols to export by passing to @code{gcc} a definition
24072 file (see @ref{1e1,,The Definition File}).
24073 For example:
24075 @example
24076 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
24077 @end example
24079 If you use a definition file you must export the elaboration procedures
24080 for every package that required one. Elaboration procedures are named
24081 using the package name followed by “_E”.
24083 @item 
24084 Preparing DLL to be used.
24085 For the DLL to be used by client programs the bodies must be hidden
24086 from it and the .ali set with read-only attribute. This is very important
24087 otherwise GNAT will recompile all packages and will not actually use
24088 the code in the DLL. For example:
24090 @example
24091 $ mkdir apilib
24092 $ copy *.ads *.ali api.dll apilib
24093 $ attrib +R apilib\\*.ali
24094 @end example
24095 @end itemize
24097 At this point it is possible to use the DLL by directly linking
24098 against it. Note that you must use the GNAT shared runtime when using
24099 GNAT shared libraries. This is achieved by using the @code{-shared} binder
24100 option.
24102 @quotation
24104 @example
24105 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
24106 @end example
24107 @end quotation
24109 @node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
24110 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{1ee}@anchor{gnat_ugn/platform_specific_information id26}@anchor{1ef}
24111 @subsubsection Building DLLs with gnatdll
24114 @geindex DLLs
24115 @geindex building
24117 Note that it is preferred to use GNAT Project files
24118 (@ref{1d4,,Building DLLs with GNAT Project files}) or the built-in GNAT
24119 DLL support (@ref{1ec,,Building DLLs with GNAT}) or to build DLLs.
24121 This section explains how to build DLLs containing Ada code using
24122 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
24123 remainder of this section.
24125 The steps required to build an Ada DLL that is to be used by Ada as well as
24126 non-Ada applications are as follows:
24129 @itemize *
24131 @item 
24132 You need to mark each Ada entity exported by the DLL with a @code{C} or
24133 @code{Stdcall} calling convention to avoid any Ada name mangling for the
24134 entities exported by the DLL
24135 (see @ref{1f0,,Exporting Ada Entities}). You can
24136 skip this step if you plan to use the Ada DLL only from Ada applications.
24138 @item 
24139 Your Ada code must export an initialization routine which calls the routine
24140 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
24141 the Ada code in the DLL (@ref{1f1,,Ada DLLs and Elaboration}). The initialization
24142 routine exported by the Ada DLL must be invoked by the clients of the DLL
24143 to initialize the DLL.
24145 @item 
24146 When useful, the DLL should also export a finalization routine which calls
24147 routine @code{adafinal} generated by @code{gnatbind} to perform the
24148 finalization of the Ada code in the DLL (@ref{1f2,,Ada DLLs and Finalization}).
24149 The finalization routine exported by the Ada DLL must be invoked by the
24150 clients of the DLL when the DLL services are no further needed.
24152 @item 
24153 You must provide a spec for the services exported by the Ada DLL in each
24154 of the programming languages to which you plan to make the DLL available.
24156 @item 
24157 You must provide a definition file listing the exported entities
24158 (@ref{1e1,,The Definition File}).
24160 @item 
24161 Finally you must use @code{gnatdll} to produce the DLL and the import
24162 library (@ref{1e9,,Using gnatdll}).
24163 @end itemize
24165 Note that a relocatable DLL stripped using the @code{strip}
24166 binutils tool will not be relocatable anymore. To build a DLL without
24167 debug information pass @code{-largs -s} to @code{gnatdll}. This
24168 restriction does not apply to a DLL built using a Library Project.
24169 See the `Library Projects' section in the `GNAT Project Manager'
24170 chapter of the `GPRbuild User’s Guide'.
24172 @c Limitations_When_Using_Ada_DLLs_from Ada:
24174 @menu
24175 * Limitations When Using Ada DLLs from Ada:: 
24176 * Exporting Ada Entities:: 
24177 * Ada DLLs and Elaboration:: 
24179 @end menu
24181 @node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
24182 @anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{1f3}
24183 @subsubsection Limitations When Using Ada DLLs from Ada
24186 When using Ada DLLs from Ada applications there is a limitation users
24187 should be aware of. Because on Windows the GNAT run-time is not in a DLL of
24188 its own, each Ada DLL includes a part of the GNAT run-time. Specifically,
24189 each Ada DLL includes the services of the GNAT run-time that are necessary
24190 to the Ada code inside the DLL. As a result, when an Ada program uses an
24191 Ada DLL there are two independent GNAT run-times: one in the Ada DLL and
24192 one in the main program.
24194 It is therefore not possible to exchange GNAT run-time objects between the
24195 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
24196 handles (e.g., @code{Text_IO.File_Type}), tasks types, protected objects
24197 types, etc.
24199 It is completely safe to exchange plain elementary, array or record types,
24200 Windows object handles, etc.
24202 @node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
24203 @anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{1f0}@anchor{gnat_ugn/platform_specific_information id27}@anchor{1f4}
24204 @subsubsection Exporting Ada Entities
24207 @geindex Export table
24209 Building a DLL is a way to encapsulate a set of services usable from any
24210 application. As a result, the Ada entities exported by a DLL should be
24211 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
24212 any Ada name mangling. As an example here is an Ada package
24213 @code{API}, spec and body, exporting two procedures, a function, and a
24214 variable:
24216 @quotation
24218 @example
24219 with Interfaces.C; use Interfaces;
24220 package API is
24221    Count : C.int := 0;
24222    function Factorial (Val : C.int) return C.int;
24224    procedure Initialize_API;
24225    procedure Finalize_API;
24226    --  Initialization & Finalization routines. More in the next section.
24227 private
24228    pragma Export (C, Initialize_API);
24229    pragma Export (C, Finalize_API);
24230    pragma Export (C, Count);
24231    pragma Export (C, Factorial);
24232 end API;
24233 @end example
24235 @example
24236 package body API is
24237    function Factorial (Val : C.int) return C.int is
24238       Fact : C.int := 1;
24239    begin
24240       Count := Count + 1;
24241       for K in 1 .. Val loop
24242          Fact := Fact * K;
24243       end loop;
24244       return Fact;
24245    end Factorial;
24247    procedure Initialize_API is
24248       procedure Adainit;
24249       pragma Import (C, Adainit);
24250    begin
24251       Adainit;
24252    end Initialize_API;
24254    procedure Finalize_API is
24255       procedure Adafinal;
24256       pragma Import (C, Adafinal);
24257    begin
24258       Adafinal;
24259    end Finalize_API;
24260 end API;
24261 @end example
24262 @end quotation
24264 If the Ada DLL you are building will only be used by Ada applications
24265 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
24266 convention. As an example, the previous package could be written as
24267 follows:
24269 @quotation
24271 @example
24272 package API is
24273    Count : Integer := 0;
24274    function Factorial (Val : Integer) return Integer;
24276    procedure Initialize_API;
24277    procedure Finalize_API;
24278    --  Initialization and Finalization routines.
24279 end API;
24280 @end example
24282 @example
24283 package body API is
24284    function Factorial (Val : Integer) return Integer is
24285       Fact : Integer := 1;
24286    begin
24287       Count := Count + 1;
24288       for K in 1 .. Val loop
24289          Fact := Fact * K;
24290       end loop;
24291       return Fact;
24292    end Factorial;
24294    ...
24295    --  The remainder of this package body is unchanged.
24296 end API;
24297 @end example
24298 @end quotation
24300 Note that if you do not export the Ada entities with a @code{C} or
24301 @code{Stdcall} convention you will have to provide the mangled Ada names
24302 in the definition file of the Ada DLL
24303 (@ref{1f5,,Creating the Definition File}).
24305 @node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
24306 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{1f1}@anchor{gnat_ugn/platform_specific_information id28}@anchor{1f6}
24307 @subsubsection Ada DLLs and Elaboration
24310 @geindex DLLs and elaboration
24312 The DLL that you are building contains your Ada code as well as all the
24313 routines in the Ada library that are needed by it. The first thing a
24314 user of your DLL must do is elaborate the Ada code
24315 (@ref{f,,Elaboration Order Handling in GNAT}).
24317 To achieve this you must export an initialization routine
24318 (@code{Initialize_API} in the previous example), which must be invoked
24319 before using any of the DLL services. This elaboration routine must call
24320 the Ada elaboration routine @code{adainit} generated by the GNAT binder
24321 (@ref{7e,,Binding with Non-Ada Main Programs}). See the body of
24322 @code{Initialize_Api} for an example. Note that the GNAT binder is
24323 automatically invoked during the DLL build process by the @code{gnatdll}
24324 tool (@ref{1e9,,Using gnatdll}).
24326 When a DLL is loaded, Windows systematically invokes a routine called
24327 @code{DllMain}. It would therefore be possible to call @code{adainit}
24328 directly from @code{DllMain} without having to provide an explicit
24329 initialization routine. Unfortunately, it is not possible to call
24330 @code{adainit} from the @code{DllMain} if your program has library level
24331 tasks because access to the @code{DllMain} entry point is serialized by
24332 the system (that is, only a single thread can execute ‘through’ it at a
24333 time), which means that the GNAT run-time will deadlock waiting for the
24334 newly created task to complete its initialization.
24336 @node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
24337 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{1f2}@anchor{gnat_ugn/platform_specific_information id29}@anchor{1f7}
24338 @subsubsection Ada DLLs and Finalization
24341 @geindex DLLs and finalization
24343 When the services of an Ada DLL are no longer needed, the client code should
24344 invoke the DLL finalization routine, if available. The DLL finalization
24345 routine is in charge of releasing all resources acquired by the DLL. In the
24346 case of the Ada code contained in the DLL, this is achieved by calling
24347 routine @code{adafinal} generated by the GNAT binder
24348 (@ref{7e,,Binding with Non-Ada Main Programs}).
24349 See the body of @code{Finalize_Api} for an
24350 example. As already pointed out the GNAT binder is automatically invoked
24351 during the DLL build process by the @code{gnatdll} tool
24352 (@ref{1e9,,Using gnatdll}).
24354 @node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
24355 @anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{1f8}@anchor{gnat_ugn/platform_specific_information id30}@anchor{1f9}
24356 @subsubsection Creating a Spec for Ada DLLs
24359 To use the services exported by the Ada DLL from another programming
24360 language (e.g., C), you have to translate the specs of the exported Ada
24361 entities in that language. For instance in the case of @code{API.dll},
24362 the corresponding C header file could look like:
24364 @quotation
24366 @example
24367 extern int *_imp__count;
24368 #define count (*_imp__count)
24369 int factorial (int);
24370 @end example
24371 @end quotation
24373 It is important to understand that when building an Ada DLL to be used by
24374 other Ada applications, you need two different specs for the packages
24375 contained in the DLL: one for building the DLL and the other for using
24376 the DLL. This is because the @code{DLL} calling convention is needed to
24377 use a variable defined in a DLL, but when building the DLL, the variable
24378 must have either the @code{Ada} or @code{C} calling convention. As an
24379 example consider a DLL comprising the following package @code{API}:
24381 @quotation
24383 @example
24384 package API is
24385    Count : Integer := 0;
24386    ...
24387    --  Remainder of the package omitted.
24388 end API;
24389 @end example
24390 @end quotation
24392 After producing a DLL containing package @code{API}, the spec that
24393 must be used to import @code{API.Count} from Ada code outside of the
24394 DLL is:
24396 @quotation
24398 @example
24399 package API is
24400    Count : Integer;
24401    pragma Import (DLL, Count);
24402 end API;
24403 @end example
24404 @end quotation
24406 @menu
24407 * Creating the Definition File:: 
24408 * Using gnatdll:: 
24410 @end menu
24412 @node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
24413 @anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{1f5}@anchor{gnat_ugn/platform_specific_information id31}@anchor{1fa}
24414 @subsubsection Creating the Definition File
24417 The definition file is the last file needed to build the DLL. It lists
24418 the exported symbols. As an example, the definition file for a DLL
24419 containing only package @code{API} (where all the entities are exported
24420 with a @code{C} calling convention) is:
24422 @quotation
24424 @example
24425 EXPORTS
24426     count
24427     factorial
24428     finalize_api
24429     initialize_api
24430 @end example
24431 @end quotation
24433 If the @code{C} calling convention is missing from package @code{API},
24434 then the definition file contains the mangled Ada names of the above
24435 entities, which in this case are:
24437 @quotation
24439 @example
24440 EXPORTS
24441     api__count
24442     api__factorial
24443     api__finalize_api
24444     api__initialize_api
24445 @end example
24446 @end quotation
24448 @node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
24449 @anchor{gnat_ugn/platform_specific_information id32}@anchor{1fb}@anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{1e9}
24450 @subsubsection Using @code{gnatdll}
24453 @geindex gnatdll
24455 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
24456 and non-Ada sources that make up your DLL have been compiled.
24457 @code{gnatdll} is actually in charge of two distinct tasks: build the
24458 static import library for the DLL and the actual DLL. The form of the
24459 @code{gnatdll} command is
24461 @quotation
24463 @example
24464 $ gnatdll [ switches ] list-of-files [ -largs opts ]
24465 @end example
24466 @end quotation
24468 where @code{list-of-files} is a list of ALI and object files. The object
24469 file list must be the exact list of objects corresponding to the non-Ada
24470 sources whose services are to be included in the DLL. The ALI file list
24471 must be the exact list of ALI files for the corresponding Ada sources
24472 whose services are to be included in the DLL. If @code{list-of-files} is
24473 missing, only the static import library is generated.
24475 You may specify any of the following switches to @code{gnatdll}:
24477 @quotation
24479 @geindex -a (gnatdll)
24480 @end quotation
24483 @table @asis
24485 @item @code{-a[`address']}
24487 Build a non-relocatable DLL at @code{address}. If @code{address} is not
24488 specified the default address @code{0x11000000} will be used. By default,
24489 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
24490 advise the reader to build relocatable DLL.
24492 @geindex -b (gnatdll)
24494 @item @code{-b `address'}
24496 Set the relocatable DLL base address. By default the address is
24497 @code{0x11000000}.
24499 @geindex -bargs (gnatdll)
24501 @item @code{-bargs `opts'}
24503 Binder options. Pass @code{opts} to the binder.
24505 @geindex -d (gnatdll)
24507 @item @code{-d `dllfile'}
24509 @code{dllfile} is the name of the DLL. This switch must be present for
24510 @code{gnatdll} to do anything. The name of the generated import library is
24511 obtained algorithmically from @code{dllfile} as shown in the following
24512 example: if @code{dllfile} is @code{xyz.dll}, the import library name is
24513 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
24514 by option @code{-e}) is obtained algorithmically from @code{dllfile}
24515 as shown in the following example:
24516 if @code{dllfile} is @code{xyz.dll}, the definition
24517 file used is @code{xyz.def}.
24519 @geindex -e (gnatdll)
24521 @item @code{-e `deffile'}
24523 @code{deffile} is the name of the definition file.
24525 @geindex -g (gnatdll)
24527 @item @code{-g}
24529 Generate debugging information. This information is stored in the object
24530 file and copied from there to the final DLL file by the linker,
24531 where it can be read by the debugger. You must use the
24532 @code{-g} switch if you plan on using the debugger or the symbolic
24533 stack traceback.
24535 @geindex -h (gnatdll)
24537 @item @code{-h}
24539 Help mode. Displays @code{gnatdll} switch usage information.
24541 @geindex -I (gnatdll)
24543 @item @code{-I`dir'}
24545 Direct @code{gnatdll} to search the @code{dir} directory for source and
24546 object files needed to build the DLL.
24547 (@ref{73,,Search Paths and the Run-Time Library (RTL)}).
24549 @geindex -k (gnatdll)
24551 @item @code{-k}
24553 Removes the @code{@@@var{nn}} suffix from the import library’s exported
24554 names, but keeps them for the link names. You must specify this
24555 option if you want to use a @code{Stdcall} function in a DLL for which
24556 the @code{@@@var{nn}} suffix has been removed. This is the case for most
24557 of the Windows NT DLL for example. This option has no effect when
24558 @code{-n} option is specified.
24560 @geindex -l (gnatdll)
24562 @item @code{-l `file'}
24564 The list of ALI and object files used to build the DLL are listed in
24565 @code{file}, instead of being given in the command line. Each line in
24566 @code{file} contains the name of an ALI or object file.
24568 @geindex -n (gnatdll)
24570 @item @code{-n}
24572 No Import. Do not create the import library.
24574 @geindex -q (gnatdll)
24576 @item @code{-q}
24578 Quiet mode. Do not display unnecessary messages.
24580 @geindex -v (gnatdll)
24582 @item @code{-v}
24584 Verbose mode. Display extra information.
24586 @geindex -largs (gnatdll)
24588 @item @code{-largs `opts'}
24590 Linker options. Pass @code{opts} to the linker.
24591 @end table
24593 @subsubheading @code{gnatdll} Example
24596 As an example the command to build a relocatable DLL from @code{api.adb}
24597 once @code{api.adb} has been compiled and @code{api.def} created is
24599 @quotation
24601 @example
24602 $ gnatdll -d api.dll api.ali
24603 @end example
24604 @end quotation
24606 The above command creates two files: @code{libapi.dll.a} (the import
24607 library) and @code{api.dll} (the actual DLL). If you want to create
24608 only the DLL, just type:
24610 @quotation
24612 @example
24613 $ gnatdll -d api.dll -n api.ali
24614 @end example
24615 @end quotation
24617 Alternatively if you want to create just the import library, type:
24619 @quotation
24621 @example
24622 $ gnatdll -d api.dll
24623 @end example
24624 @end quotation
24626 @subsubheading @code{gnatdll} behind the Scenes
24629 This section details the steps involved in creating a DLL. @code{gnatdll}
24630 does these steps for you. Unless you are interested in understanding what
24631 goes on behind the scenes, you should skip this section.
24633 We use the previous example of a DLL containing the Ada package @code{API},
24634 to illustrate the steps necessary to build a DLL. The starting point is a
24635 set of objects that will make up the DLL and the corresponding ALI
24636 files. In the case of this example this means that @code{api.o} and
24637 @code{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
24638 the following:
24641 @itemize *
24643 @item 
24644 @code{gnatdll} builds the base file (@code{api.base}). A base file gives
24645 the information necessary to generate relocation information for the
24646 DLL.
24648 @example
24649 $ gnatbind -n api
24650 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
24651 @end example
24653 In addition to the base file, the @code{gnatlink} command generates an
24654 output file @code{api.jnk} which can be discarded. The @code{-mdll} switch
24655 asks @code{gnatlink} to generate the routines @code{DllMain} and
24656 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
24657 is loaded into memory.
24659 @item 
24660 @code{gnatdll} uses @code{dlltool} (see @ref{1fc,,Using dlltool}) to build the
24661 export table (@code{api.exp}). The export table contains the relocation
24662 information in a form which can be used during the final link to ensure
24663 that the Windows loader is able to place the DLL anywhere in memory.
24665 @example
24666 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
24667           --output-exp api.exp
24668 @end example
24670 @item 
24671 @code{gnatdll} builds the base file using the new export table. Note that
24672 @code{gnatbind} must be called once again since the binder generated file
24673 has been deleted during the previous call to @code{gnatlink}.
24675 @example
24676 $ gnatbind -n api
24677 $ gnatlink api -o api.jnk api.exp -mdll
24678       -Wl,--base-file,api.base
24679 @end example
24681 @item 
24682 @code{gnatdll} builds the new export table using the new base file and
24683 generates the DLL import library @code{libAPI.dll.a}.
24685 @example
24686 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
24687           --output-exp api.exp --output-lib libAPI.a
24688 @end example
24690 @item 
24691 Finally @code{gnatdll} builds the relocatable DLL using the final export
24692 table.
24694 @example
24695 $ gnatbind -n api
24696 $ gnatlink api api.exp -o api.dll -mdll
24697 @end example
24698 @end itemize
24699 @anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{1fc}
24700 @subsubheading Using @code{dlltool}
24703 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
24704 DLLs and static import libraries. This section summarizes the most
24705 common @code{dlltool} switches. The form of the @code{dlltool} command
24708 @quotation
24710 @example
24711 $ dlltool [`switches`]
24712 @end example
24713 @end quotation
24715 @code{dlltool} switches include:
24717 @geindex --base-file (dlltool)
24720 @table @asis
24722 @item @code{--base-file `basefile'}
24724 Read the base file @code{basefile} generated by the linker. This switch
24725 is used to create a relocatable DLL.
24726 @end table
24728 @geindex --def (dlltool)
24731 @table @asis
24733 @item @code{--def `deffile'}
24735 Read the definition file.
24736 @end table
24738 @geindex --dllname (dlltool)
24741 @table @asis
24743 @item @code{--dllname `name'}
24745 Gives the name of the DLL. This switch is used to embed the name of the
24746 DLL in the static import library generated by @code{dlltool} with switch
24747 @code{--output-lib}.
24748 @end table
24750 @geindex -k (dlltool)
24753 @table @asis
24755 @item @code{-k}
24757 Kill @code{@@@var{nn}} from exported names
24758 (@ref{1d6,,Windows Calling Conventions}
24759 for a discussion about @code{Stdcall}-style symbols).
24760 @end table
24762 @geindex --help (dlltool)
24765 @table @asis
24767 @item @code{--help}
24769 Prints the @code{dlltool} switches with a concise description.
24770 @end table
24772 @geindex --output-exp (dlltool)
24775 @table @asis
24777 @item @code{--output-exp `exportfile'}
24779 Generate an export file @code{exportfile}. The export file contains the
24780 export table (list of symbols in the DLL) and is used to create the DLL.
24781 @end table
24783 @geindex --output-lib (dlltool)
24786 @table @asis
24788 @item @code{--output-lib `libfile'}
24790 Generate a static import library @code{libfile}.
24791 @end table
24793 @geindex -v (dlltool)
24796 @table @asis
24798 @item @code{-v}
24800 Verbose mode.
24801 @end table
24803 @geindex --as (dlltool)
24806 @table @asis
24808 @item @code{--as `assembler-name'}
24810 Use @code{assembler-name} as the assembler. The default is @code{as}.
24811 @end table
24813 @node GNAT and Windows Resources,Using GNAT DLLs from Microsoft Visual Studio Applications,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
24814 @anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{1fd}@anchor{gnat_ugn/platform_specific_information id33}@anchor{1fe}
24815 @subsubsection GNAT and Windows Resources
24818 @geindex Resources
24819 @geindex windows
24821 Resources are an easy way to add Windows specific objects to your
24822 application. The objects that can be added as resources include:
24825 @itemize *
24827 @item 
24828 menus
24830 @item 
24831 accelerators
24833 @item 
24834 dialog boxes
24836 @item 
24837 string tables
24839 @item 
24840 bitmaps
24842 @item 
24843 cursors
24845 @item 
24846 icons
24848 @item 
24849 fonts
24851 @item 
24852 version information
24853 @end itemize
24855 For example, a version information resource can be defined as follow and
24856 embedded into an executable or DLL:
24858 A version information resource can be used to embed information into an
24859 executable or a DLL. These information can be viewed using the file properties
24860 from the Windows Explorer. Here is an example of a version information
24861 resource:
24863 @quotation
24865 @example
24866 1 VERSIONINFO
24867 FILEVERSION     1,0,0,0
24868 PRODUCTVERSION  1,0,0,0
24869 BEGIN
24870   BLOCK "StringFileInfo"
24871   BEGIN
24872     BLOCK "080904E4"
24873     BEGIN
24874       VALUE "CompanyName", "My Company Name"
24875       VALUE "FileDescription", "My application"
24876       VALUE "FileVersion", "1.0"
24877       VALUE "InternalName", "my_app"
24878       VALUE "LegalCopyright", "My Name"
24879       VALUE "OriginalFilename", "my_app.exe"
24880       VALUE "ProductName", "My App"
24881       VALUE "ProductVersion", "1.0"
24882     END
24883   END
24885   BLOCK "VarFileInfo"
24886   BEGIN
24887     VALUE "Translation", 0x809, 1252
24888   END
24890 @end example
24891 @end quotation
24893 The value @code{0809} (langID) is for the U.K English language and
24894 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
24895 multilingual.
24897 This section explains how to build, compile and use resources. Note that this
24898 section does not cover all resource objects, for a complete description see
24899 the corresponding Microsoft documentation.
24901 @menu
24902 * Building Resources:: 
24903 * Compiling Resources:: 
24904 * Using Resources:: 
24906 @end menu
24908 @node Building Resources,Compiling Resources,,GNAT and Windows Resources
24909 @anchor{gnat_ugn/platform_specific_information building-resources}@anchor{1ff}@anchor{gnat_ugn/platform_specific_information id34}@anchor{200}
24910 @subsubsection Building Resources
24913 @geindex Resources
24914 @geindex building
24916 A resource file is an ASCII file. By convention resource files have an
24917 @code{.rc} extension.
24918 The easiest way to build a resource file is to use Microsoft tools
24919 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
24920 @code{dlgedit.exe} to build dialogs.
24921 It is always possible to build an @code{.rc} file yourself by writing a
24922 resource script.
24924 It is not our objective to explain how to write a resource file. A
24925 complete description of the resource script language can be found in the
24926 Microsoft documentation.
24928 @node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
24929 @anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{201}@anchor{gnat_ugn/platform_specific_information id35}@anchor{202}
24930 @subsubsection Compiling Resources
24933 @geindex rc
24935 @geindex windres
24937 @geindex Resources
24938 @geindex compiling
24940 This section describes how to build a GNAT-compatible (COFF) object file
24941 containing the resources. This is done using the Resource Compiler
24942 @code{windres} as follows:
24944 @quotation
24946 @example
24947 $ windres -i myres.rc -o myres.o
24948 @end example
24949 @end quotation
24951 By default @code{windres} will run @code{gcc} to preprocess the @code{.rc}
24952 file. You can specify an alternate preprocessor (usually named
24953 @code{cpp.exe}) using the @code{windres} @code{--preprocessor}
24954 parameter. A list of all possible options may be obtained by entering
24955 the command @code{windres} @code{--help}.
24957 It is also possible to use the Microsoft resource compiler @code{rc.exe}
24958 to produce a @code{.res} file (binary resource file). See the
24959 corresponding Microsoft documentation for further details. In this case
24960 you need to use @code{windres} to translate the @code{.res} file to a
24961 GNAT-compatible object file as follows:
24963 @quotation
24965 @example
24966 $ windres -i myres.res -o myres.o
24967 @end example
24968 @end quotation
24970 @node Using Resources,,Compiling Resources,GNAT and Windows Resources
24971 @anchor{gnat_ugn/platform_specific_information id36}@anchor{203}@anchor{gnat_ugn/platform_specific_information using-resources}@anchor{204}
24972 @subsubsection Using Resources
24975 @geindex Resources
24976 @geindex using
24978 To include the resource file in your program just add the
24979 GNAT-compatible object file for the resource(s) to the linker
24980 arguments. With @code{gnatmake} this is done by using the @code{-largs}
24981 option:
24983 @quotation
24985 @example
24986 $ gnatmake myprog -largs myres.o
24987 @end example
24988 @end quotation
24990 @node Using GNAT DLLs from Microsoft Visual Studio Applications,Debugging a DLL,GNAT and Windows Resources,Mixed-Language Programming on Windows
24991 @anchor{gnat_ugn/platform_specific_information using-gnat-dll-from-msvs}@anchor{205}@anchor{gnat_ugn/platform_specific_information using-gnat-dlls-from-microsoft-visual-studio-applications}@anchor{206}
24992 @subsubsection Using GNAT DLLs from Microsoft Visual Studio Applications
24995 @geindex Microsoft Visual Studio
24996 @geindex use with GNAT DLLs
24998 This section describes a common case of mixed GNAT/Microsoft Visual Studio
24999 application development, where the main program is developed using MSVS, and
25000 is linked with a DLL developed using GNAT. Such a mixed application should
25001 be developed following the general guidelines outlined above; below is the
25002 cookbook-style sequence of steps to follow:
25005 @enumerate 
25007 @item 
25008 First develop and build the GNAT shared library using a library project
25009 (let’s assume the project is @code{mylib.gpr}, producing the library @code{libmylib.dll}):
25010 @end enumerate
25012 @quotation
25014 @example
25015 $ gprbuild -p mylib.gpr
25016 @end example
25017 @end quotation
25020 @enumerate 2
25022 @item 
25023 Produce a .def file for the symbols you need to interface with, either by
25024 hand or automatically with possibly some manual adjustments
25025 (see @ref{1e7,,Creating Definition File Automatically}):
25026 @end enumerate
25028 @quotation
25030 @example
25031 $ dlltool libmylib.dll -z libmylib.def --export-all-symbols
25032 @end example
25033 @end quotation
25036 @enumerate 3
25038 @item 
25039 Make sure that MSVS command-line tools are accessible on the path.
25041 @item 
25042 Create the Microsoft-style import library (see @ref{1ea,,MSVS-Style Import Library}):
25043 @end enumerate
25045 @quotation
25047 @example
25048 $ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
25049 @end example
25050 @end quotation
25052 If you are using a 64-bit toolchain, the above becomes…
25054 @quotation
25056 @example
25057 $ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
25058 @end example
25059 @end quotation
25062 @enumerate 5
25064 @item 
25065 Build the C main
25066 @end enumerate
25068 @quotation
25070 @example
25071 $ cl /O2 /MD main.c libmylib.lib
25072 @end example
25073 @end quotation
25076 @enumerate 6
25078 @item 
25079 Before running the executable, make sure you have set the PATH to the DLL,
25080 or copy the DLL into into the directory containing the .exe.
25081 @end enumerate
25083 @node Debugging a DLL,Setting Stack Size from gnatlink,Using GNAT DLLs from Microsoft Visual Studio Applications,Mixed-Language Programming on Windows
25084 @anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{207}@anchor{gnat_ugn/platform_specific_information id37}@anchor{208}
25085 @subsubsection Debugging a DLL
25088 @geindex DLL debugging
25090 Debugging a DLL is similar to debugging a standard program. But
25091 we have to deal with two different executable parts: the DLL and the
25092 program that uses it. We have the following four possibilities:
25095 @itemize *
25097 @item 
25098 The program and the DLL are built with GCC/GNAT.
25100 @item 
25101 The program is built with foreign tools and the DLL is built with
25102 GCC/GNAT.
25104 @item 
25105 The program is built with GCC/GNAT and the DLL is built with
25106 foreign tools.
25107 @end itemize
25109 In this section we address only cases one and two above.
25110 There is no point in trying to debug
25111 a DLL with GNU/GDB, if there is no GDB-compatible debugging
25112 information in it. To do so you must use a debugger compatible with the
25113 tools suite used to build the DLL.
25115 @menu
25116 * Program and DLL Both Built with GCC/GNAT:: 
25117 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
25119 @end menu
25121 @node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
25122 @anchor{gnat_ugn/platform_specific_information id38}@anchor{209}@anchor{gnat_ugn/platform_specific_information program-and-dll-both-built-with-gcc-gnat}@anchor{20a}
25123 @subsubsection Program and DLL Both Built with GCC/GNAT
25126 This is the simplest case. Both the DLL and the program have @code{GDB}
25127 compatible debugging information. It is then possible to break anywhere in
25128 the process. Let’s suppose here that the main procedure is named
25129 @code{ada_main} and that in the DLL there is an entry point named
25130 @code{ada_dll}.
25132 The DLL (@ref{1e0,,Introduction to Dynamic Link Libraries (DLLs)}) and
25133 program must have been built with the debugging information (see GNAT -g
25134 switch). Here are the step-by-step instructions for debugging it:
25137 @itemize *
25139 @item 
25140 Launch @code{GDB} on the main program.
25142 @example
25143 $ gdb -nw ada_main
25144 @end example
25146 @item 
25147 Start the program and stop at the beginning of the main procedure
25149 @example
25150 (gdb) start
25151 @end example
25153 This step is required to be able to set a breakpoint inside the DLL. As long
25154 as the program is not run, the DLL is not loaded. This has the
25155 consequence that the DLL debugging information is also not loaded, so it is not
25156 possible to set a breakpoint in the DLL.
25158 @item 
25159 Set a breakpoint inside the DLL
25161 @example
25162 (gdb) break ada_dll
25163 (gdb) cont
25164 @end example
25165 @end itemize
25167 At this stage a breakpoint is set inside the DLL. From there on
25168 you can use the standard approach to debug the whole program
25169 (@ref{14f,,Running and Debugging Ada Programs}).
25171 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
25172 @anchor{gnat_ugn/platform_specific_information id39}@anchor{20b}@anchor{gnat_ugn/platform_specific_information program-built-with-foreign-tools-and-dll-built-with-gcc-gnat}@anchor{20c}
25173 @subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
25176 In this case things are slightly more complex because it is not possible to
25177 start the main program and then break at the beginning to load the DLL and the
25178 associated DLL debugging information. It is not possible to break at the
25179 beginning of the program because there is no @code{GDB} debugging information,
25180 and therefore there is no direct way of getting initial control. This
25181 section addresses this issue by describing some methods that can be used
25182 to break somewhere in the DLL to debug it.
25184 First suppose that the main procedure is named @code{main} (this is for
25185 example some C code built with Microsoft Visual C) and that there is a
25186 DLL named @code{test.dll} containing an Ada entry point named
25187 @code{ada_dll}.
25189 The DLL (see @ref{1e0,,Introduction to Dynamic Link Libraries (DLLs)}) must have
25190 been built with debugging information (see the GNAT @code{-g} option).
25192 @subsubheading Debugging the DLL Directly
25196 @itemize *
25198 @item 
25199 Find out the executable starting address
25201 @example
25202 $ objdump --file-header main.exe
25203 @end example
25205 The starting address is reported on the last line. For example:
25207 @example
25208 main.exe:     file format pei-i386
25209 architecture: i386, flags 0x0000010a:
25210 EXEC_P, HAS_DEBUG, D_PAGED
25211 start address 0x00401010
25212 @end example
25214 @item 
25215 Launch the debugger on the executable.
25217 @example
25218 $ gdb main.exe
25219 @end example
25221 @item 
25222 Set a breakpoint at the starting address, and launch the program.
25224 @example
25225 $ (gdb) break *0x00401010
25226 $ (gdb) run
25227 @end example
25229 The program will stop at the given address.
25231 @item 
25232 Set a breakpoint on a DLL subroutine.
25234 @example
25235 (gdb) break ada_dll.adb:45
25236 @end example
25238 Or if you want to break using a symbol on the DLL, you need first to
25239 select the Ada language (language used by the DLL).
25241 @example
25242 (gdb) set language ada
25243 (gdb) break ada_dll
25244 @end example
25246 @item 
25247 Continue the program.
25249 @example
25250 (gdb) cont
25251 @end example
25253 This will run the program until it reaches the breakpoint that has been
25254 set. From that point you can use the standard way to debug a program
25255 as described in (@ref{14f,,Running and Debugging Ada Programs}).
25256 @end itemize
25258 It is also possible to debug the DLL by attaching to a running process.
25260 @subsubheading Attaching to a Running Process
25263 @geindex DLL debugging
25264 @geindex attach to process
25266 With @code{GDB} it is always possible to debug a running process by
25267 attaching to it. It is possible to debug a DLL this way. The limitation
25268 of this approach is that the DLL must run long enough to perform the
25269 attach operation. It may be useful for instance to insert a time wasting
25270 loop in the code of the DLL to meet this criterion.
25273 @itemize *
25275 @item 
25276 Launch the main program @code{main.exe}.
25278 @example
25279 $ main
25280 @end example
25282 @item 
25283 Use the Windows `Task Manager' to find the process ID. Let’s say
25284 that the process PID for @code{main.exe} is 208.
25286 @item 
25287 Launch gdb.
25289 @example
25290 $ gdb
25291 @end example
25293 @item 
25294 Attach to the running process to be debugged.
25296 @example
25297 (gdb) attach 208
25298 @end example
25300 @item 
25301 Load the process debugging information.
25303 @example
25304 (gdb) symbol-file main.exe
25305 @end example
25307 @item 
25308 Break somewhere in the DLL.
25310 @example
25311 (gdb) break ada_dll
25312 @end example
25314 @item 
25315 Continue process execution.
25317 @example
25318 (gdb) cont
25319 @end example
25320 @end itemize
25322 This last step will resume the process execution, and stop at
25323 the breakpoint we have set. From there you can use the standard
25324 approach to debug a program as described in
25325 @ref{14f,,Running and Debugging Ada Programs}.
25327 @node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
25328 @anchor{gnat_ugn/platform_specific_information id40}@anchor{20d}@anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{129}
25329 @subsubsection Setting Stack Size from @code{gnatlink}
25332 It is possible to specify the program stack size at link time. On modern
25333 versions of Windows, starting with XP, this is mostly useful to set the size of
25334 the main stack (environment task). The other task stacks are set with pragma
25335 Storage_Size or with the `gnatbind -d' command.
25337 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
25338 reserve size of individual tasks, the link-time stack size applies to all
25339 tasks, and pragma Storage_Size has no effect.
25340 In particular, Stack Overflow checks are made against this
25341 link-time specified size.
25343 This setting can be done with @code{gnatlink} using either of the following:
25346 @itemize *
25348 @item 
25349 @code{-Xlinker} linker option
25351 @example
25352 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
25353 @end example
25355 This sets the stack reserve size to 0x10000 bytes and the stack commit
25356 size to 0x1000 bytes.
25358 @item 
25359 @code{-Wl} linker option
25361 @example
25362 $ gnatlink hello -Wl,--stack=0x1000000
25363 @end example
25365 This sets the stack reserve size to 0x1000000 bytes. Note that with
25366 @code{-Wl} option it is not possible to set the stack commit size
25367 because the comma is a separator for this option.
25368 @end itemize
25370 @node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
25371 @anchor{gnat_ugn/platform_specific_information id41}@anchor{20e}@anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{12a}
25372 @subsubsection Setting Heap Size from @code{gnatlink}
25375 Under Windows systems, it is possible to specify the program heap size from
25376 @code{gnatlink} using either of the following:
25379 @itemize *
25381 @item 
25382 @code{-Xlinker} linker option
25384 @example
25385 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
25386 @end example
25388 This sets the heap reserve size to 0x10000 bytes and the heap commit
25389 size to 0x1000 bytes.
25391 @item 
25392 @code{-Wl} linker option
25394 @example
25395 $ gnatlink hello -Wl,--heap=0x1000000
25396 @end example
25398 This sets the heap reserve size to 0x1000000 bytes. Note that with
25399 @code{-Wl} option it is not possible to set the heap commit size
25400 because the comma is a separator for this option.
25401 @end itemize
25403 @node Windows Specific Add-Ons,,Mixed-Language Programming on Windows,Microsoft Windows Topics
25404 @anchor{gnat_ugn/platform_specific_information win32-specific-addons}@anchor{20f}@anchor{gnat_ugn/platform_specific_information windows-specific-add-ons}@anchor{210}
25405 @subsection Windows Specific Add-Ons
25408 This section describes the Windows specific add-ons.
25410 @menu
25411 * Win32Ada:: 
25412 * wPOSIX:: 
25414 @end menu
25416 @node Win32Ada,wPOSIX,,Windows Specific Add-Ons
25417 @anchor{gnat_ugn/platform_specific_information id42}@anchor{211}@anchor{gnat_ugn/platform_specific_information win32ada}@anchor{212}
25418 @subsubsection Win32Ada
25421 Win32Ada is a binding for the Microsoft Win32 API. This binding can be
25422 easily installed from the provided installer. To use the Win32Ada
25423 binding you need to use a project file, and adding a single with_clause
25424 will give you full access to the Win32Ada binding sources and ensure
25425 that the proper libraries are passed to the linker.
25427 @quotation
25429 @example
25430 with "win32ada";
25431 project P is
25432    for Sources use ...;
25433 end P;
25434 @end example
25435 @end quotation
25437 To build the application you just need to call gprbuild for the
25438 application’s project, here p.gpr:
25440 @quotation
25442 @example
25443 gprbuild p.gpr
25444 @end example
25445 @end quotation
25447 @node wPOSIX,,Win32Ada,Windows Specific Add-Ons
25448 @anchor{gnat_ugn/platform_specific_information id43}@anchor{213}@anchor{gnat_ugn/platform_specific_information wposix}@anchor{214}
25449 @subsubsection wPOSIX
25452 wPOSIX is a minimal POSIX binding whose goal is to help with building
25453 cross-platforms applications. This binding is not complete though, as
25454 the Win32 API does not provide the necessary support for all POSIX APIs.
25456 To use the wPOSIX binding you need to use a project file, and adding
25457 a single with_clause will give you full access to the wPOSIX binding
25458 sources and ensure that the proper libraries are passed to the linker.
25460 @quotation
25462 @example
25463 with "wposix";
25464 project P is
25465    for Sources use ...;
25466 end P;
25467 @end example
25468 @end quotation
25470 To build the application you just need to call gprbuild for the
25471 application’s project, here p.gpr:
25473 @quotation
25475 @example
25476 gprbuild p.gpr
25477 @end example
25478 @end quotation
25480 @node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
25481 @anchor{gnat_ugn/platform_specific_information id44}@anchor{215}@anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{216}
25482 @section Mac OS Topics
25485 @geindex OS X
25487 This section describes topics that are specific to Apple’s OS X
25488 platform.
25490 @menu
25491 * Codesigning the Debugger:: 
25493 @end menu
25495 @node Codesigning the Debugger,,,Mac OS Topics
25496 @anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{217}
25497 @subsection Codesigning the Debugger
25500 The Darwin Kernel requires the debugger to have special permissions
25501 before it is allowed to control other processes. These permissions
25502 are granted by codesigning the GDB executable. Without these
25503 permissions, the debugger will report error messages such as:
25505 @example
25506 Starting program: /x/y/foo
25507 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
25508 (please check gdb is codesigned - see taskgated(8))
25509 @end example
25511 Codesigning requires a certificate.  The following procedure explains
25512 how to create one:
25515 @itemize *
25517 @item 
25518 Start the Keychain Access application (in
25519 /Applications/Utilities/Keychain Access.app)
25521 @item 
25522 Select the Keychain Access -> Certificate Assistant ->
25523 Create a Certificate… menu
25525 @item 
25526 Then:
25529 @itemize *
25531 @item 
25532 Choose a name for the new certificate (this procedure will use
25533 “gdb-cert” as an example)
25535 @item 
25536 Set “Identity Type” to “Self Signed Root”
25538 @item 
25539 Set “Certificate Type” to “Code Signing”
25541 @item 
25542 Activate the “Let me override defaults” option
25543 @end itemize
25545 @item 
25546 Click several times on “Continue” until the “Specify a Location
25547 For The Certificate” screen appears, then set “Keychain” to “System”
25549 @item 
25550 Click on “Continue” until the certificate is created
25552 @item 
25553 Finally, in the view, double-click on the new certificate,
25554 and set “When using this certificate” to “Always Trust”
25556 @item 
25557 Exit the Keychain Access application and restart the computer
25558 (this is unfortunately required)
25559 @end itemize
25561 Once a certificate has been created, the debugger can be codesigned
25562 as follow. In a Terminal, run the following command:
25564 @quotation
25566 @example
25567 $ codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
25568 @end example
25569 @end quotation
25571 where “gdb-cert” should be replaced by the actual certificate
25572 name chosen above, and <gnat_install_prefix> should be replaced by
25573 the location where you installed GNAT.  Also, be sure that users are
25574 in the Unix group @code{_developer}.
25576 @node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
25577 @anchor{gnat_ugn/example_of_binder_output doc}@anchor{218}@anchor{gnat_ugn/example_of_binder_output example-of-binder-output-file}@anchor{e}@anchor{gnat_ugn/example_of_binder_output id1}@anchor{219}
25578 @chapter Example of Binder Output File
25581 @geindex Binder output (example)
25583 This Appendix displays the source code for the output file
25584 generated by `gnatbind' for a simple ‘Hello World’ program.
25585 Comments have been added for clarification purposes.
25587 @example
25588 --  The package is called Ada_Main unless this name is actually used
25589 --  as a unit name in the partition, in which case some other unique
25590 --  name is used.
25592 pragma Ada_95;
25593 with System;
25594 package ada_main is
25595    pragma Warnings (Off);
25597    --  The main program saves the parameters (argument count,
25598    --  argument values, environment pointer) in global variables
25599    --  for later access by other units including
25600    --  Ada.Command_Line.
25602    gnat_argc : Integer;
25603    gnat_argv : System.Address;
25604    gnat_envp : System.Address;
25606    --  The actual variables are stored in a library routine. This
25607    --  is useful for some shared library situations, where there
25608    --  are problems if variables are not in the library.
25610    pragma Import (C, gnat_argc);
25611    pragma Import (C, gnat_argv);
25612    pragma Import (C, gnat_envp);
25614    --  The exit status is similarly an external location
25616    gnat_exit_status : Integer;
25617    pragma Import (C, gnat_exit_status);
25619    GNAT_Version : constant String :=
25620                     "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
25621    pragma Export (C, GNAT_Version, "__gnat_version");
25623    Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
25624    pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
25626    --  This is the generated adainit routine that performs
25627    --  initialization at the start of execution. In the case
25628    --  where Ada is the main program, this main program makes
25629    --  a call to adainit at program startup.
25631    procedure adainit;
25632    pragma Export (C, adainit, "adainit");
25634    --  This is the generated adafinal routine that performs
25635    --  finalization at the end of execution. In the case where
25636    --  Ada is the main program, this main program makes a call
25637    --  to adafinal at program termination.
25639    procedure adafinal;
25640    pragma Export (C, adafinal, "adafinal");
25642    --  This routine is called at the start of execution. It is
25643    --  a dummy routine that is used by the debugger to breakpoint
25644    --  at the start of execution.
25646    --  This is the actual generated main program (it would be
25647    --  suppressed if the no main program switch were used). As
25648    --  required by standard system conventions, this program has
25649    --  the external name main.
25651    function main
25652      (argc : Integer;
25653       argv : System.Address;
25654       envp : System.Address)
25655       return Integer;
25656    pragma Export (C, main, "main");
25658    --  The following set of constants give the version
25659    --  identification values for every unit in the bound
25660    --  partition. This identification is computed from all
25661    --  dependent semantic units, and corresponds to the
25662    --  string that would be returned by use of the
25663    --  Body_Version or Version attributes.
25665    --  The following Export pragmas export the version numbers
25666    --  with symbolic names ending in B (for body) or S
25667    --  (for spec) so that they can be located in a link. The
25668    --  information provided here is sufficient to track down
25669    --  the exact versions of units used in a given build.
25671    type Version_32 is mod 2 ** 32;
25672    u00001 : constant Version_32 := 16#8ad6e54a#;
25673    pragma Export (C, u00001, "helloB");
25674    u00002 : constant Version_32 := 16#fbff4c67#;
25675    pragma Export (C, u00002, "system__standard_libraryB");
25676    u00003 : constant Version_32 := 16#1ec6fd90#;
25677    pragma Export (C, u00003, "system__standard_libraryS");
25678    u00004 : constant Version_32 := 16#3ffc8e18#;
25679    pragma Export (C, u00004, "adaS");
25680    u00005 : constant Version_32 := 16#28f088c2#;
25681    pragma Export (C, u00005, "ada__text_ioB");
25682    u00006 : constant Version_32 := 16#f372c8ac#;
25683    pragma Export (C, u00006, "ada__text_ioS");
25684    u00007 : constant Version_32 := 16#2c143749#;
25685    pragma Export (C, u00007, "ada__exceptionsB");
25686    u00008 : constant Version_32 := 16#f4f0cce8#;
25687    pragma Export (C, u00008, "ada__exceptionsS");
25688    u00009 : constant Version_32 := 16#a46739c0#;
25689    pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
25690    u00010 : constant Version_32 := 16#3aac8c92#;
25691    pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
25692    u00011 : constant Version_32 := 16#1d274481#;
25693    pragma Export (C, u00011, "systemS");
25694    u00012 : constant Version_32 := 16#a207fefe#;
25695    pragma Export (C, u00012, "system__soft_linksB");
25696    u00013 : constant Version_32 := 16#467d9556#;
25697    pragma Export (C, u00013, "system__soft_linksS");
25698    u00014 : constant Version_32 := 16#b01dad17#;
25699    pragma Export (C, u00014, "system__parametersB");
25700    u00015 : constant Version_32 := 16#630d49fe#;
25701    pragma Export (C, u00015, "system__parametersS");
25702    u00016 : constant Version_32 := 16#b19b6653#;
25703    pragma Export (C, u00016, "system__secondary_stackB");
25704    u00017 : constant Version_32 := 16#b6468be8#;
25705    pragma Export (C, u00017, "system__secondary_stackS");
25706    u00018 : constant Version_32 := 16#39a03df9#;
25707    pragma Export (C, u00018, "system__storage_elementsB");
25708    u00019 : constant Version_32 := 16#30e40e85#;
25709    pragma Export (C, u00019, "system__storage_elementsS");
25710    u00020 : constant Version_32 := 16#41837d1e#;
25711    pragma Export (C, u00020, "system__stack_checkingB");
25712    u00021 : constant Version_32 := 16#93982f69#;
25713    pragma Export (C, u00021, "system__stack_checkingS");
25714    u00022 : constant Version_32 := 16#393398c1#;
25715    pragma Export (C, u00022, "system__exception_tableB");
25716    u00023 : constant Version_32 := 16#b33e2294#;
25717    pragma Export (C, u00023, "system__exception_tableS");
25718    u00024 : constant Version_32 := 16#ce4af020#;
25719    pragma Export (C, u00024, "system__exceptionsB");
25720    u00025 : constant Version_32 := 16#75442977#;
25721    pragma Export (C, u00025, "system__exceptionsS");
25722    u00026 : constant Version_32 := 16#37d758f1#;
25723    pragma Export (C, u00026, "system__exceptions__machineS");
25724    u00027 : constant Version_32 := 16#b895431d#;
25725    pragma Export (C, u00027, "system__exceptions_debugB");
25726    u00028 : constant Version_32 := 16#aec55d3f#;
25727    pragma Export (C, u00028, "system__exceptions_debugS");
25728    u00029 : constant Version_32 := 16#570325c8#;
25729    pragma Export (C, u00029, "system__img_intB");
25730    u00030 : constant Version_32 := 16#1ffca443#;
25731    pragma Export (C, u00030, "system__img_intS");
25732    u00031 : constant Version_32 := 16#b98c3e16#;
25733    pragma Export (C, u00031, "system__tracebackB");
25734    u00032 : constant Version_32 := 16#831a9d5a#;
25735    pragma Export (C, u00032, "system__tracebackS");
25736    u00033 : constant Version_32 := 16#9ed49525#;
25737    pragma Export (C, u00033, "system__traceback_entriesB");
25738    u00034 : constant Version_32 := 16#1d7cb2f1#;
25739    pragma Export (C, u00034, "system__traceback_entriesS");
25740    u00035 : constant Version_32 := 16#8c33a517#;
25741    pragma Export (C, u00035, "system__wch_conB");
25742    u00036 : constant Version_32 := 16#065a6653#;
25743    pragma Export (C, u00036, "system__wch_conS");
25744    u00037 : constant Version_32 := 16#9721e840#;
25745    pragma Export (C, u00037, "system__wch_stwB");
25746    u00038 : constant Version_32 := 16#2b4b4a52#;
25747    pragma Export (C, u00038, "system__wch_stwS");
25748    u00039 : constant Version_32 := 16#92b797cb#;
25749    pragma Export (C, u00039, "system__wch_cnvB");
25750    u00040 : constant Version_32 := 16#09eddca0#;
25751    pragma Export (C, u00040, "system__wch_cnvS");
25752    u00041 : constant Version_32 := 16#6033a23f#;
25753    pragma Export (C, u00041, "interfacesS");
25754    u00042 : constant Version_32 := 16#ece6fdb6#;
25755    pragma Export (C, u00042, "system__wch_jisB");
25756    u00043 : constant Version_32 := 16#899dc581#;
25757    pragma Export (C, u00043, "system__wch_jisS");
25758    u00044 : constant Version_32 := 16#10558b11#;
25759    pragma Export (C, u00044, "ada__streamsB");
25760    u00045 : constant Version_32 := 16#2e6701ab#;
25761    pragma Export (C, u00045, "ada__streamsS");
25762    u00046 : constant Version_32 := 16#db5c917c#;
25763    pragma Export (C, u00046, "ada__io_exceptionsS");
25764    u00047 : constant Version_32 := 16#12c8cd7d#;
25765    pragma Export (C, u00047, "ada__tagsB");
25766    u00048 : constant Version_32 := 16#ce72c228#;
25767    pragma Export (C, u00048, "ada__tagsS");
25768    u00049 : constant Version_32 := 16#c3335bfd#;
25769    pragma Export (C, u00049, "system__htableB");
25770    u00050 : constant Version_32 := 16#99e5f76b#;
25771    pragma Export (C, u00050, "system__htableS");
25772    u00051 : constant Version_32 := 16#089f5cd0#;
25773    pragma Export (C, u00051, "system__string_hashB");
25774    u00052 : constant Version_32 := 16#3bbb9c15#;
25775    pragma Export (C, u00052, "system__string_hashS");
25776    u00053 : constant Version_32 := 16#807fe041#;
25777    pragma Export (C, u00053, "system__unsigned_typesS");
25778    u00054 : constant Version_32 := 16#d27be59e#;
25779    pragma Export (C, u00054, "system__val_lluB");
25780    u00055 : constant Version_32 := 16#fa8db733#;
25781    pragma Export (C, u00055, "system__val_lluS");
25782    u00056 : constant Version_32 := 16#27b600b2#;
25783    pragma Export (C, u00056, "system__val_utilB");
25784    u00057 : constant Version_32 := 16#b187f27f#;
25785    pragma Export (C, u00057, "system__val_utilS");
25786    u00058 : constant Version_32 := 16#d1060688#;
25787    pragma Export (C, u00058, "system__case_utilB");
25788    u00059 : constant Version_32 := 16#392e2d56#;
25789    pragma Export (C, u00059, "system__case_utilS");
25790    u00060 : constant Version_32 := 16#84a27f0d#;
25791    pragma Export (C, u00060, "interfaces__c_streamsB");
25792    u00061 : constant Version_32 := 16#8bb5f2c0#;
25793    pragma Export (C, u00061, "interfaces__c_streamsS");
25794    u00062 : constant Version_32 := 16#6db6928f#;
25795    pragma Export (C, u00062, "system__crtlS");
25796    u00063 : constant Version_32 := 16#4e6a342b#;
25797    pragma Export (C, u00063, "system__file_ioB");
25798    u00064 : constant Version_32 := 16#ba56a5e4#;
25799    pragma Export (C, u00064, "system__file_ioS");
25800    u00065 : constant Version_32 := 16#b7ab275c#;
25801    pragma Export (C, u00065, "ada__finalizationB");
25802    u00066 : constant Version_32 := 16#19f764ca#;
25803    pragma Export (C, u00066, "ada__finalizationS");
25804    u00067 : constant Version_32 := 16#95817ed8#;
25805    pragma Export (C, u00067, "system__finalization_rootB");
25806    u00068 : constant Version_32 := 16#52d53711#;
25807    pragma Export (C, u00068, "system__finalization_rootS");
25808    u00069 : constant Version_32 := 16#769e25e6#;
25809    pragma Export (C, u00069, "interfaces__cB");
25810    u00070 : constant Version_32 := 16#4a38bedb#;
25811    pragma Export (C, u00070, "interfaces__cS");
25812    u00071 : constant Version_32 := 16#07e6ee66#;
25813    pragma Export (C, u00071, "system__os_libB");
25814    u00072 : constant Version_32 := 16#d7b69782#;
25815    pragma Export (C, u00072, "system__os_libS");
25816    u00073 : constant Version_32 := 16#1a817b8e#;
25817    pragma Export (C, u00073, "system__stringsB");
25818    u00074 : constant Version_32 := 16#639855e7#;
25819    pragma Export (C, u00074, "system__stringsS");
25820    u00075 : constant Version_32 := 16#e0b8de29#;
25821    pragma Export (C, u00075, "system__file_control_blockS");
25822    u00076 : constant Version_32 := 16#b5b2aca1#;
25823    pragma Export (C, u00076, "system__finalization_mastersB");
25824    u00077 : constant Version_32 := 16#69316dc1#;
25825    pragma Export (C, u00077, "system__finalization_mastersS");
25826    u00078 : constant Version_32 := 16#57a37a42#;
25827    pragma Export (C, u00078, "system__address_imageB");
25828    u00079 : constant Version_32 := 16#bccbd9bb#;
25829    pragma Export (C, u00079, "system__address_imageS");
25830    u00080 : constant Version_32 := 16#7268f812#;
25831    pragma Export (C, u00080, "system__img_boolB");
25832    u00081 : constant Version_32 := 16#e8fe356a#;
25833    pragma Export (C, u00081, "system__img_boolS");
25834    u00082 : constant Version_32 := 16#d7aac20c#;
25835    pragma Export (C, u00082, "system__ioB");
25836    u00083 : constant Version_32 := 16#8365b3ce#;
25837    pragma Export (C, u00083, "system__ioS");
25838    u00084 : constant Version_32 := 16#6d4d969a#;
25839    pragma Export (C, u00084, "system__storage_poolsB");
25840    u00085 : constant Version_32 := 16#e87cc305#;
25841    pragma Export (C, u00085, "system__storage_poolsS");
25842    u00086 : constant Version_32 := 16#e34550ca#;
25843    pragma Export (C, u00086, "system__pool_globalB");
25844    u00087 : constant Version_32 := 16#c88d2d16#;
25845    pragma Export (C, u00087, "system__pool_globalS");
25846    u00088 : constant Version_32 := 16#9d39c675#;
25847    pragma Export (C, u00088, "system__memoryB");
25848    u00089 : constant Version_32 := 16#445a22b5#;
25849    pragma Export (C, u00089, "system__memoryS");
25850    u00090 : constant Version_32 := 16#6a859064#;
25851    pragma Export (C, u00090, "system__storage_pools__subpoolsB");
25852    u00091 : constant Version_32 := 16#e3b008dc#;
25853    pragma Export (C, u00091, "system__storage_pools__subpoolsS");
25854    u00092 : constant Version_32 := 16#63f11652#;
25855    pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
25856    u00093 : constant Version_32 := 16#fe2f4b3a#;
25857    pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
25859    --  BEGIN ELABORATION ORDER
25860    --  ada%s
25861    --  interfaces%s
25862    --  system%s
25863    --  system.case_util%s
25864    --  system.case_util%b
25865    --  system.htable%s
25866    --  system.img_bool%s
25867    --  system.img_bool%b
25868    --  system.img_int%s
25869    --  system.img_int%b
25870    --  system.io%s
25871    --  system.io%b
25872    --  system.parameters%s
25873    --  system.parameters%b
25874    --  system.crtl%s
25875    --  interfaces.c_streams%s
25876    --  interfaces.c_streams%b
25877    --  system.standard_library%s
25878    --  system.exceptions_debug%s
25879    --  system.exceptions_debug%b
25880    --  system.storage_elements%s
25881    --  system.storage_elements%b
25882    --  system.stack_checking%s
25883    --  system.stack_checking%b
25884    --  system.string_hash%s
25885    --  system.string_hash%b
25886    --  system.htable%b
25887    --  system.strings%s
25888    --  system.strings%b
25889    --  system.os_lib%s
25890    --  system.traceback_entries%s
25891    --  system.traceback_entries%b
25892    --  ada.exceptions%s
25893    --  system.soft_links%s
25894    --  system.unsigned_types%s
25895    --  system.val_llu%s
25896    --  system.val_util%s
25897    --  system.val_util%b
25898    --  system.val_llu%b
25899    --  system.wch_con%s
25900    --  system.wch_con%b
25901    --  system.wch_cnv%s
25902    --  system.wch_jis%s
25903    --  system.wch_jis%b
25904    --  system.wch_cnv%b
25905    --  system.wch_stw%s
25906    --  system.wch_stw%b
25907    --  ada.exceptions.last_chance_handler%s
25908    --  ada.exceptions.last_chance_handler%b
25909    --  system.address_image%s
25910    --  system.exception_table%s
25911    --  system.exception_table%b
25912    --  ada.io_exceptions%s
25913    --  ada.tags%s
25914    --  ada.streams%s
25915    --  ada.streams%b
25916    --  interfaces.c%s
25917    --  system.exceptions%s
25918    --  system.exceptions%b
25919    --  system.exceptions.machine%s
25920    --  system.finalization_root%s
25921    --  system.finalization_root%b
25922    --  ada.finalization%s
25923    --  ada.finalization%b
25924    --  system.storage_pools%s
25925    --  system.storage_pools%b
25926    --  system.finalization_masters%s
25927    --  system.storage_pools.subpools%s
25928    --  system.storage_pools.subpools.finalization%s
25929    --  system.storage_pools.subpools.finalization%b
25930    --  system.memory%s
25931    --  system.memory%b
25932    --  system.standard_library%b
25933    --  system.pool_global%s
25934    --  system.pool_global%b
25935    --  system.file_control_block%s
25936    --  system.file_io%s
25937    --  system.secondary_stack%s
25938    --  system.file_io%b
25939    --  system.storage_pools.subpools%b
25940    --  system.finalization_masters%b
25941    --  interfaces.c%b
25942    --  ada.tags%b
25943    --  system.soft_links%b
25944    --  system.os_lib%b
25945    --  system.secondary_stack%b
25946    --  system.address_image%b
25947    --  system.traceback%s
25948    --  ada.exceptions%b
25949    --  system.traceback%b
25950    --  ada.text_io%s
25951    --  ada.text_io%b
25952    --  hello%b
25953    --  END ELABORATION ORDER
25955 end ada_main;
25956 @end example
25958 @example
25959 pragma Ada_95;
25960 --  The following source file name pragmas allow the generated file
25961 --  names to be unique for different main programs. They are needed
25962 --  since the package name will always be Ada_Main.
25964 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
25965 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
25967 pragma Suppress (Overflow_Check);
25968 with Ada.Exceptions;
25970 --  Generated package body for Ada_Main starts here
25972 package body ada_main is
25973    pragma Warnings (Off);
25975    --  These values are reference counter associated to units which have
25976    --  been elaborated. It is also used to avoid elaborating the
25977    --  same unit twice.
25979    E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
25980    E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
25981    E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
25982    E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
25983    E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
25984    E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
25985    E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
25986    E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
25987    E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
25988    E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
25989    E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
25990    E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
25991    E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
25992    E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
25993    E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
25994    E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
25995    E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
25996    E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
25998    Local_Priority_Specific_Dispatching : constant String := "";
25999    Local_Interrupt_States : constant String := "";
26001    Is_Elaborated : Boolean := False;
26003    procedure finalize_library is
26004    begin
26005       E06 := E06 - 1;
26006       declare
26007          procedure F1;
26008          pragma Import (Ada, F1, "ada__text_io__finalize_spec");
26009       begin
26010          F1;
26011       end;
26012       E77 := E77 - 1;
26013       E91 := E91 - 1;
26014       declare
26015          procedure F2;
26016          pragma Import (Ada, F2, "system__file_io__finalize_body");
26017       begin
26018          E64 := E64 - 1;
26019          F2;
26020       end;
26021       declare
26022          procedure F3;
26023          pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
26024       begin
26025          E75 := E75 - 1;
26026          F3;
26027       end;
26028       E87 := E87 - 1;
26029       declare
26030          procedure F4;
26031          pragma Import (Ada, F4, "system__pool_global__finalize_spec");
26032       begin
26033          F4;
26034       end;
26035       declare
26036          procedure F5;
26037          pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
26038       begin
26039          F5;
26040       end;
26041       declare
26042          procedure F6;
26043          pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
26044       begin
26045          F6;
26046       end;
26047       declare
26048          procedure Reraise_Library_Exception_If_Any;
26049          pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
26050       begin
26051          Reraise_Library_Exception_If_Any;
26052       end;
26053    end finalize_library;
26055    -------------
26056    -- adainit --
26057    -------------
26059    procedure adainit is
26061       Main_Priority : Integer;
26062       pragma Import (C, Main_Priority, "__gl_main_priority");
26063       Time_Slice_Value : Integer;
26064       pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
26065       WC_Encoding : Character;
26066       pragma Import (C, WC_Encoding, "__gl_wc_encoding");
26067       Locking_Policy : Character;
26068       pragma Import (C, Locking_Policy, "__gl_locking_policy");
26069       Queuing_Policy : Character;
26070       pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
26071       Task_Dispatching_Policy : Character;
26072       pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
26073       Priority_Specific_Dispatching : System.Address;
26074       pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
26075       Num_Specific_Dispatching : Integer;
26076       pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
26077       Main_CPU : Integer;
26078       pragma Import (C, Main_CPU, "__gl_main_cpu");
26079       Interrupt_States : System.Address;
26080       pragma Import (C, Interrupt_States, "__gl_interrupt_states");
26081       Num_Interrupt_States : Integer;
26082       pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
26083       Unreserve_All_Interrupts : Integer;
26084       pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
26085       Detect_Blocking : Integer;
26086       pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
26087       Default_Stack_Size : Integer;
26088       pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
26089       Leap_Seconds_Support : Integer;
26090       pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
26092       procedure Runtime_Initialize;
26093       pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
26095       Finalize_Library_Objects : No_Param_Proc;
26096       pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
26098    --  Start of processing for adainit
26100    begin
26102       --  Record various information for this partition.  The values
26103       --  are derived by the binder from information stored in the ali
26104       --  files by the compiler.
26106       if Is_Elaborated then
26107          return;
26108       end if;
26109       Is_Elaborated := True;
26110       Main_Priority := -1;
26111       Time_Slice_Value := -1;
26112       WC_Encoding := 'b';
26113       Locking_Policy := ' ';
26114       Queuing_Policy := ' ';
26115       Task_Dispatching_Policy := ' ';
26116       Priority_Specific_Dispatching :=
26117         Local_Priority_Specific_Dispatching'Address;
26118       Num_Specific_Dispatching := 0;
26119       Main_CPU := -1;
26120       Interrupt_States := Local_Interrupt_States'Address;
26121       Num_Interrupt_States := 0;
26122       Unreserve_All_Interrupts := 0;
26123       Detect_Blocking := 0;
26124       Default_Stack_Size := -1;
26125       Leap_Seconds_Support := 0;
26127       Runtime_Initialize;
26129       Finalize_Library_Objects := finalize_library'access;
26131       --  Now we have the elaboration calls for all units in the partition.
26132       --  The Elab_Spec and Elab_Body attributes generate references to the
26133       --  implicit elaboration procedures generated by the compiler for
26134       --  each unit that requires elaboration. Increment a counter of
26135       --  reference for each unit.
26137       System.Soft_Links'Elab_Spec;
26138       System.Exception_Table'Elab_Body;
26139       E23 := E23 + 1;
26140       Ada.Io_Exceptions'Elab_Spec;
26141       E46 := E46 + 1;
26142       Ada.Tags'Elab_Spec;
26143       Ada.Streams'Elab_Spec;
26144       E45 := E45 + 1;
26145       Interfaces.C'Elab_Spec;
26146       System.Exceptions'Elab_Spec;
26147       E25 := E25 + 1;
26148       System.Finalization_Root'Elab_Spec;
26149       E68 := E68 + 1;
26150       Ada.Finalization'Elab_Spec;
26151       E66 := E66 + 1;
26152       System.Storage_Pools'Elab_Spec;
26153       E85 := E85 + 1;
26154       System.Finalization_Masters'Elab_Spec;
26155       System.Storage_Pools.Subpools'Elab_Spec;
26156       System.Pool_Global'Elab_Spec;
26157       E87 := E87 + 1;
26158       System.File_Control_Block'Elab_Spec;
26159       E75 := E75 + 1;
26160       System.File_Io'Elab_Body;
26161       E64 := E64 + 1;
26162       E91 := E91 + 1;
26163       System.Finalization_Masters'Elab_Body;
26164       E77 := E77 + 1;
26165       E70 := E70 + 1;
26166       Ada.Tags'Elab_Body;
26167       E48 := E48 + 1;
26168       System.Soft_Links'Elab_Body;
26169       E13 := E13 + 1;
26170       System.Os_Lib'Elab_Body;
26171       E72 := E72 + 1;
26172       System.Secondary_Stack'Elab_Body;
26173       E17 := E17 + 1;
26174       Ada.Text_Io'Elab_Spec;
26175       Ada.Text_Io'Elab_Body;
26176       E06 := E06 + 1;
26177    end adainit;
26179    --------------
26180    -- adafinal --
26181    --------------
26183    procedure adafinal is
26184       procedure s_stalib_adafinal;
26185       pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
26187       procedure Runtime_Finalize;
26188       pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
26190    begin
26191       if not Is_Elaborated then
26192          return;
26193       end if;
26194       Is_Elaborated := False;
26195       Runtime_Finalize;
26196       s_stalib_adafinal;
26197    end adafinal;
26199    --  We get to the main program of the partition by using
26200    --  pragma Import because if we try to with the unit and
26201    --  call it Ada style, then not only do we waste time
26202    --  recompiling it, but also, we don't really know the right
26203    --  switches (e.g.@@: identifier character set) to be used
26204    --  to compile it.
26206    procedure Ada_Main_Program;
26207    pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26209    ----------
26210    -- main --
26211    ----------
26213    --  main is actually a function, as in the ANSI C standard,
26214    --  defined to return the exit status. The three parameters
26215    --  are the argument count, argument values and environment
26216    --  pointer.
26218    function main
26219      (argc : Integer;
26220       argv : System.Address;
26221       envp : System.Address)
26222       return Integer
26223    is
26224       --  The initialize routine performs low level system
26225       --  initialization using a standard library routine which
26226       --  sets up signal handling and performs any other
26227       --  required setup. The routine can be found in file
26228       --  a-init.c.
26230       procedure initialize;
26231       pragma Import (C, initialize, "__gnat_initialize");
26233       --  The finalize routine performs low level system
26234       --  finalization using a standard library routine. The
26235       --  routine is found in file a-final.c and in the standard
26236       --  distribution is a dummy routine that does nothing, so
26237       --  really this is a hook for special user finalization.
26239       procedure finalize;
26240       pragma Import (C, finalize, "__gnat_finalize");
26242       --  The following is to initialize the SEH exceptions
26244       SEH : aliased array (1 .. 2) of Integer;
26246       Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
26247       pragma Volatile (Ensure_Reference);
26249    --  Start of processing for main
26251    begin
26252       --  Save global variables
26254       gnat_argc := argc;
26255       gnat_argv := argv;
26256       gnat_envp := envp;
26258       --  Call low level system initialization
26260       Initialize (SEH'Address);
26262       --  Call our generated Ada initialization routine
26264       adainit;
26266       --  Now we call the main program of the partition
26268       Ada_Main_Program;
26270       --  Perform Ada finalization
26272       adafinal;
26274       --  Perform low level system finalization
26276       Finalize;
26278       --  Return the proper exit status
26279       return (gnat_exit_status);
26280    end;
26282 --  This section is entirely comments, so it has no effect on the
26283 --  compilation of the Ada_Main package. It provides the list of
26284 --  object files and linker options, as well as some standard
26285 --  libraries needed for the link. The gnatlink utility parses
26286 --  this b~hello.adb file to read these comment lines to generate
26287 --  the appropriate command line arguments for the call to the
26288 --  system linker. The BEGIN/END lines are used for sentinels for
26289 --  this parsing operation.
26291 --  The exact file names will of course depend on the environment,
26292 --  host/target and location of files on the host system.
26294 -- BEGIN Object file/option list
26295    --   ./hello.o
26296    --   -L./
26297    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
26298    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
26299 -- END Object file/option list
26301 end ada_main;
26302 @end example
26304 The Ada code in the above example is exactly what is generated by the
26305 binder. We have added comments to more clearly indicate the function
26306 of each part of the generated @code{Ada_Main} package.
26308 The code is standard Ada in all respects, and can be processed by any
26309 tools that handle Ada. In particular, it is possible to use the debugger
26310 in Ada mode to debug the generated @code{Ada_Main} package. For example,
26311 suppose that for reasons that you do not understand, your program is crashing
26312 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
26313 you can place a breakpoint on the call:
26315 @quotation
26317 @example
26318 Ada.Text_Io'Elab_Body;
26319 @end example
26320 @end quotation
26322 and trace the elaboration routine for this package to find out where
26323 the problem might be (more usually of course you would be debugging
26324 elaboration code in your own application).
26326 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
26328 @node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
26329 @anchor{gnat_ugn/elaboration_order_handling_in_gnat doc}@anchor{21a}@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{21b}
26330 @chapter Elaboration Order Handling in GNAT
26333 @geindex Order of elaboration
26335 @geindex Elaboration control
26337 This appendix describes the handling of elaboration code in Ada and GNAT, and
26338 discusses how the order of elaboration of program units can be controlled in
26339 GNAT, either automatically or with explicit programming features.
26341 @menu
26342 * Elaboration Code:: 
26343 * Elaboration Order:: 
26344 * Checking the Elaboration Order:: 
26345 * Controlling the Elaboration Order in Ada:: 
26346 * Controlling the Elaboration Order in GNAT:: 
26347 * Mixing Elaboration Models:: 
26348 * ABE Diagnostics:: 
26349 * SPARK Diagnostics:: 
26350 * Elaboration Circularities:: 
26351 * Resolving Elaboration Circularities:: 
26352 * Elaboration-related Compiler Switches:: 
26353 * Summary of Procedures for Elaboration Control:: 
26354 * Inspecting the Chosen Elaboration Order:: 
26356 @end menu
26358 @node Elaboration Code,Elaboration Order,,Elaboration Order Handling in GNAT
26359 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{21c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{21d}
26360 @section Elaboration Code
26363 Ada defines the term `execution' as the process by which a construct achieves
26364 its run-time effect. This process is also referred to as `elaboration' for
26365 declarations and `evaluation' for expressions.
26367 The execution model in Ada allows for certain sections of an Ada program to be
26368 executed prior to execution of the program itself, primarily with the intent of
26369 initializing data. These sections are referred to as `elaboration code'.
26370 Elaboration code is executed as follows:
26373 @itemize *
26375 @item 
26376 All partitions of an Ada program are executed in parallel with one another,
26377 possibly in a separate address space, and possibly on a separate computer.
26379 @item 
26380 The execution of a partition involves running the environment task for that
26381 partition.
26383 @item 
26384 The environment task executes all elaboration code (if available) for all
26385 units within that partition. This code is said to be executed at
26386 `elaboration time'.
26388 @item 
26389 The environment task executes the Ada program (if available) for that
26390 partition.
26391 @end itemize
26393 In addition to the Ada terminology, this appendix defines the following terms:
26396 @itemize *
26398 @item 
26399 `Invocation'
26401 The act of calling a subprogram, instantiating a generic, or activating a
26402 task.
26404 @item 
26405 `Scenario'
26407 A construct that is elaborated or invoked by elaboration code is referred to
26408 as an `elaboration scenario' or simply a `scenario'. GNAT recognizes the
26409 following scenarios:
26412 @itemize -
26414 @item 
26415 @code{'Access} of entries, operators, and subprograms
26417 @item 
26418 Activation of tasks
26420 @item 
26421 Calls to entries, operators, and subprograms
26423 @item 
26424 Instantiations of generic templates
26425 @end itemize
26427 @item 
26428 `Target'
26430 A construct elaborated by a scenario is referred to as `elaboration target'
26431 or simply `target'. GNAT recognizes the following targets:
26434 @itemize -
26436 @item 
26437 For @code{'Access} of entries, operators, and subprograms, the target is the
26438 entry, operator, or subprogram being aliased.
26440 @item 
26441 For activation of tasks, the target is the task body
26443 @item 
26444 For calls to entries, operators, and subprograms, the target is the entry,
26445 operator, or subprogram being invoked.
26447 @item 
26448 For instantiations of generic templates, the target is the generic template
26449 being instantiated.
26450 @end itemize
26451 @end itemize
26453 Elaboration code may appear in two distinct contexts:
26456 @itemize *
26458 @item 
26459 `Library level'
26461 A scenario appears at the library level when it is encapsulated by a package
26462 [body] compilation unit, ignoring any other package [body] declarations in
26463 between.
26465 @example
26466 with Server;
26467 package Client is
26468    procedure Proc;
26470    package Nested is
26471       Val : ... := Server.Func;
26472    end Nested;
26473 end Client;
26474 @end example
26476 In the example above, the call to @code{Server.Func} is an elaboration scenario
26477 because it appears at the library level of package @code{Client}. Note that the
26478 declaration of package @code{Nested} is ignored according to the definition
26479 given above. As a result, the call to @code{Server.Func} will be invoked when
26480 the spec of unit @code{Client} is elaborated.
26482 @item 
26483 `Package body statements'
26485 A scenario appears within the statement sequence of a package body when it is
26486 bounded by the region starting from the @code{begin} keyword of the package body
26487 and ending at the @code{end} keyword of the package body.
26489 @example
26490 package body Client is
26491    procedure Proc is
26492    begin
26493       ...
26494    end Proc;
26495 begin
26496    Proc;
26497 end Client;
26498 @end example
26500 In the example above, the call to @code{Proc} is an elaboration scenario because
26501 it appears within the statement sequence of package body @code{Client}. As a
26502 result, the call to @code{Proc} will be invoked when the body of @code{Client} is
26503 elaborated.
26504 @end itemize
26506 @node Elaboration Order,Checking the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
26507 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order}@anchor{21e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{21f}
26508 @section Elaboration Order
26511 The sequence by which the elaboration code of all units within a partition is
26512 executed is referred to as `elaboration order'.
26514 Within a single unit, elaboration code is executed in sequential order.
26516 @quotation
26518 @example
26519 package body Client is
26520    Result : ... := Server.Func;
26522    procedure Proc is
26523       package Inst is new Server.Gen;
26524    begin
26525       Inst.Eval (Result);
26526    end Proc;
26527 begin
26528    Proc;
26529 end Client;
26530 @end example
26531 @end quotation
26533 In the example above, the elaboration order within package body @code{Client} is
26534 as follows:
26537 @enumerate 
26539 @item 
26540 The object declaration of @code{Result} is elaborated.
26543 @itemize *
26545 @item 
26546 Function @code{Server.Func} is invoked.
26547 @end itemize
26549 @item 
26550 The subprogram body of @code{Proc} is elaborated.
26552 @item 
26553 Procedure @code{Proc} is invoked.
26556 @itemize *
26558 @item 
26559 Generic unit @code{Server.Gen} is instantiated as @code{Inst}.
26561 @item 
26562 Instance @code{Inst} is elaborated.
26564 @item 
26565 Procedure @code{Inst.Eval} is invoked.
26566 @end itemize
26567 @end enumerate
26569 The elaboration order of all units within a partition depends on the following
26570 factors:
26573 @itemize *
26575 @item 
26576 `with'ed units
26578 @item 
26579 parent units
26581 @item 
26582 purity of units
26584 @item 
26585 preelaborability of units
26587 @item 
26588 presence of elaboration-control pragmas
26590 @item 
26591 invocations performed in elaboration code
26592 @end itemize
26594 A program may have several elaboration orders depending on its structure.
26596 @quotation
26598 @example
26599 package Server is
26600    function Func (Index : Integer) return Integer;
26601 end Server;
26602 @end example
26604 @example
26605 package body Server is
26606    Results : array (1 .. 5) of Integer := (1, 2, 3, 4, 5);
26608    function Func (Index : Integer) return Integer is
26609    begin
26610       return Results (Index);
26611    end Func;
26612 end Server;
26613 @end example
26615 @example
26616 with Server;
26617 package Client is
26618    Val : constant Integer := Server.Func (3);
26619 end Client;
26620 @end example
26622 @example
26623 with Client;
26624 procedure Main is begin null; end Main;
26625 @end example
26626 @end quotation
26628 The following elaboration order exhibits a fundamental problem referred to as
26629 `access-before-elaboration' or simply `ABE'.
26631 @quotation
26633 @example
26634 spec of Server
26635 spec of Client
26636 body of Server
26637 body of Main
26638 @end example
26639 @end quotation
26641 The elaboration of @code{Server}’s spec materializes function @code{Func}, making it
26642 callable. The elaboration of @code{Client}’s spec elaborates the declaration of
26643 @code{Val}. This invokes function @code{Server.Func}, however the body of
26644 @code{Server.Func} has not been elaborated yet because @code{Server}’s body comes
26645 after @code{Client}’s spec in the elaboration order. As a result, the value of
26646 constant @code{Val} is now undefined.
26648 Without any guarantees from the language, an undetected ABE problem may hinder
26649 proper initialization of data, which in turn may lead to undefined behavior at
26650 run time. To prevent such ABE problems, Ada employs dynamic checks in the same
26651 vein as index or null exclusion checks. A failed ABE check raises exception
26652 @code{Program_Error}.
26654 The following elaboration order avoids the ABE problem and the program can be
26655 successfully elaborated.
26657 @quotation
26659 @example
26660 spec of Server
26661 body of Server
26662 spec of Client
26663 body of Main
26664 @end example
26665 @end quotation
26667 Ada states that a total elaboration order must exist, but it does not define
26668 what this order is. A compiler is thus tasked with choosing a suitable
26669 elaboration order which satisfies the dependencies imposed by `with' clauses,
26670 unit categorization, elaboration-control pragmas, and invocations performed in
26671 elaboration code. Ideally an order that avoids ABE problems should be chosen,
26672 however a compiler may not always find such an order due to complications with
26673 respect to control and data flow.
26675 @node Checking the Elaboration Order,Controlling the Elaboration Order in Ada,Elaboration Order,Elaboration Order Handling in GNAT
26676 @anchor{gnat_ugn/elaboration_order_handling_in_gnat checking-the-elaboration-order}@anchor{220}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id4}@anchor{221}
26677 @section Checking the Elaboration Order
26680 To avoid placing the entire elaboration-order burden on the programmer, Ada
26681 provides three lines of defense:
26684 @itemize *
26686 @item 
26687 `Static semantics'
26689 Static semantic rules restrict the possible choice of elaboration order. For
26690 instance, if unit Client `with's unit Server, then the spec of Server is
26691 always elaborated prior to Client. The same principle applies to child units
26692 - the spec of a parent unit is always elaborated prior to the child unit.
26694 @item 
26695 `Dynamic semantics'
26697 Dynamic checks are performed at run time, to ensure that a target is
26698 elaborated prior to a scenario that invokes it, thus avoiding ABE problems.
26699 A failed run-time check raises exception @code{Program_Error}. The following
26700 restrictions apply:
26703 @itemize -
26705 @item 
26706 `Restrictions on calls'
26708 An entry, operator, or subprogram can be called from elaboration code only
26709 when the corresponding body has been elaborated.
26711 @item 
26712 `Restrictions on instantiations'
26714 A generic unit can be instantiated by elaboration code only when the
26715 corresponding body has been elaborated.
26717 @item 
26718 `Restrictions on task activation'
26720 A task can be activated by elaboration code only when the body of the
26721 associated task type has been elaborated.
26722 @end itemize
26724 The restrictions above can be summarized by the following rule:
26726 `If a target has a body, then this body must be elaborated prior to the
26727 scenario that invokes the target.'
26729 @item 
26730 `Elaboration control'
26732 Pragmas are provided for the programmer to specify the desired elaboration
26733 order.
26734 @end itemize
26736 @node Controlling the Elaboration Order in Ada,Controlling the Elaboration Order in GNAT,Checking the Elaboration Order,Elaboration Order Handling in GNAT
26737 @anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order-in-ada}@anchor{222}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id5}@anchor{223}
26738 @section Controlling the Elaboration Order in Ada
26741 Ada provides several idioms and pragmas to aid the programmer with specifying
26742 the desired elaboration order and avoiding ABE problems altogether.
26745 @itemize *
26747 @item 
26748 `Packages without a body'
26750 A library package which does not require a completing body does not suffer
26751 from ABE problems.
26753 @example
26754 package Pack is
26755    generic
26756       type Element is private;
26757    package Containers is
26758       type Element_Array is array (1 .. 10) of Element;
26759    end Containers;
26760 end Pack;
26761 @end example
26763 In the example above, package @code{Pack} does not require a body because it
26764 does not contain any constructs which require completion in a body. As a
26765 result, generic @code{Pack.Containers} can be instantiated without encountering
26766 any ABE problems.
26767 @end itemize
26769 @geindex pragma Pure
26772 @itemize *
26774 @item 
26775 `pragma Pure'
26777 Pragma @code{Pure} places sufficient restrictions on a unit to guarantee that no
26778 scenario within the unit can result in an ABE problem.
26779 @end itemize
26781 @geindex pragma Preelaborate
26784 @itemize *
26786 @item 
26787 `pragma Preelaborate'
26789 Pragma @code{Preelaborate} is slightly less restrictive than pragma @code{Pure},
26790 but still strong enough to prevent ABE problems within a unit.
26791 @end itemize
26793 @geindex pragma Elaborate_Body
26796 @itemize *
26798 @item 
26799 `pragma Elaborate_Body'
26801 Pragma @code{Elaborate_Body} requires that the body of a unit is elaborated
26802 immediately after its spec. This restriction guarantees that no client
26803 scenario can invoke a server target before the target body has been
26804 elaborated because the spec and body are effectively “glued” together.
26806 @example
26807 package Server is
26808    pragma Elaborate_Body;
26810    function Func return Integer;
26811 end Server;
26812 @end example
26814 @example
26815 package body Server is
26816    function Func return Integer is
26817    begin
26818       ...
26819    end Func;
26820 end Server;
26821 @end example
26823 @example
26824 with Server;
26825 package Client is
26826    Val : constant Integer := Server.Func;
26827 end Client;
26828 @end example
26830 In the example above, pragma @code{Elaborate_Body} guarantees the following
26831 elaboration order:
26833 @example
26834 spec of Server
26835 body of Server
26836 spec of Client
26837 @end example
26839 because the spec of @code{Server} must be elaborated prior to @code{Client} by
26840 virtue of the `with' clause, and in addition the body of @code{Server} must be
26841 elaborated immediately after the spec of @code{Server}.
26843 Removing pragma @code{Elaborate_Body} could result in the following incorrect
26844 elaboration order:
26846 @example
26847 spec of Server
26848 spec of Client
26849 body of Server
26850 @end example
26852 where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func} has
26853 not been elaborated yet.
26854 @end itemize
26856 The pragmas outlined above allow a server unit to guarantee safe elaboration
26857 use by client units. Thus it is a good rule to mark units as @code{Pure} or
26858 @code{Preelaborate}, and if this is not possible, mark them as @code{Elaborate_Body}.
26860 There are however situations where @code{Pure}, @code{Preelaborate}, and
26861 @code{Elaborate_Body} are not applicable. Ada provides another set of pragmas for
26862 use by client units to help ensure the elaboration safety of server units they
26863 depend on.
26865 @geindex pragma Elaborate (Unit)
26868 @itemize *
26870 @item 
26871 `pragma Elaborate (Unit)'
26873 Pragma @code{Elaborate} can be placed in the context clauses of a unit, after a
26874 `with' clause. It guarantees that both the spec and body of its argument will
26875 be elaborated prior to the unit with the pragma. Note that other unrelated
26876 units may be elaborated in between the spec and the body.
26878 @example
26879 package Server is
26880    function Func return Integer;
26881 end Server;
26882 @end example
26884 @example
26885 package body Server is
26886    function Func return Integer is
26887    begin
26888       ...
26889    end Func;
26890 end Server;
26891 @end example
26893 @example
26894 with Server;
26895 pragma Elaborate (Server);
26896 package Client is
26897    Val : constant Integer := Server.Func;
26898 end Client;
26899 @end example
26901 In the example above, pragma @code{Elaborate} guarantees the following
26902 elaboration order:
26904 @example
26905 spec of Server
26906 body of Server
26907 spec of Client
26908 @end example
26910 Removing pragma @code{Elaborate} could result in the following incorrect
26911 elaboration order:
26913 @example
26914 spec of Server
26915 spec of Client
26916 body of Server
26917 @end example
26919 where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func}
26920 has not been elaborated yet.
26921 @end itemize
26923 @geindex pragma Elaborate_All (Unit)
26926 @itemize *
26928 @item 
26929 `pragma Elaborate_All (Unit)'
26931 Pragma @code{Elaborate_All} is placed in the context clauses of a unit, after
26932 a `with' clause. It guarantees that both the spec and body of its argument
26933 will be elaborated prior to the unit with the pragma, as well as all units
26934 `with'ed by the spec and body of the argument, recursively. Note that other
26935 unrelated units may be elaborated in between the spec and the body.
26937 @example
26938 package Math is
26939    function Factorial (Val : Natural) return Natural;
26940 end Math;
26941 @end example
26943 @example
26944 package body Math is
26945    function Factorial (Val : Natural) return Natural is
26946    begin
26947       ...;
26948    end Factorial;
26949 end Math;
26950 @end example
26952 @example
26953 package Computer is
26954    type Operation_Kind is (None, Op_Factorial);
26956    function Compute
26957      (Val : Natural;
26958       Op  : Operation_Kind) return Natural;
26959 end Computer;
26960 @end example
26962 @example
26963 with Math;
26964 package body Computer is
26965    function Compute
26966      (Val : Natural;
26967       Op  : Operation_Kind) return Natural
26968    is
26969       if Op = Op_Factorial then
26970          return Math.Factorial (Val);
26971       end if;
26973       return 0;
26974    end Compute;
26975 end Computer;
26976 @end example
26978 @example
26979 with Computer;
26980 pragma Elaborate_All (Computer);
26981 package Client is
26982    Val : constant Natural :=
26983            Computer.Compute (123, Computer.Op_Factorial);
26984 end Client;
26985 @end example
26987 In the example above, pragma @code{Elaborate_All} can result in the following
26988 elaboration order:
26990 @example
26991 spec of Math
26992 body of Math
26993 spec of Computer
26994 body of Computer
26995 spec of Client
26996 @end example
26998 Note that there are several allowable suborders for the specs and bodies of
26999 @code{Math} and @code{Computer}, but the point is that these specs and bodies will
27000 be elaborated prior to @code{Client}.
27002 Removing pragma @code{Elaborate_All} could result in the following incorrect
27003 elaboration order:
27005 @example
27006 spec of Math
27007 spec of Computer
27008 body of Computer
27009 spec of Client
27010 body of Math
27011 @end example
27013 where @code{Client} invokes @code{Computer.Compute}, which in turn invokes
27014 @code{Math.Factorial}, but the body of @code{Math.Factorial} has not been
27015 elaborated yet.
27016 @end itemize
27018 All pragmas shown above can be summarized by the following rule:
27020 `If a client unit elaborates a server target directly or indirectly, then if
27021 the server unit requires a body and does not have pragma Pure, Preelaborate,
27022 or Elaborate_Body, then the client unit should have pragma Elaborate or
27023 Elaborate_All for the server unit.'
27025 If the rule outlined above is not followed, then a program may fall in one of
27026 the following states:
27029 @itemize *
27031 @item 
27032 `No elaboration order exists'
27034 In this case a compiler must diagnose the situation, and refuse to build an
27035 executable program.
27037 @item 
27038 `One or more incorrect elaboration orders exist'
27040 In this case a compiler can build an executable program, but
27041 @code{Program_Error} will be raised when the program is run.
27043 @item 
27044 `Several elaboration orders exist, some correct, some incorrect'
27046 In this case the programmer has not controlled the elaboration order. As a
27047 result, a compiler may or may not pick one of the correct orders, and the
27048 program may or may not raise @code{Program_Error} when it is run. This is the
27049 worst possible state because the program may fail on another compiler, or
27050 even another version of the same compiler.
27052 @item 
27053 `One or more correct orders exist'
27055 In this case a compiler can build an executable program, and the program is
27056 run successfully. This state may be guaranteed by following the outlined
27057 rules, or may be the result of good program architecture.
27058 @end itemize
27060 Note that one additional advantage of using @code{Elaborate} and @code{Elaborate_All}
27061 is that the program continues to stay in the last state (one or more correct
27062 orders exist) even if maintenance changes the bodies of targets.
27064 @node Controlling the Elaboration Order in GNAT,Mixing Elaboration Models,Controlling the Elaboration Order in Ada,Elaboration Order Handling in GNAT
27065 @anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order-in-gnat}@anchor{224}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id6}@anchor{225}
27066 @section Controlling the Elaboration Order in GNAT
27069 In addition to Ada semantics and rules synthesized from them, GNAT offers
27070 three elaboration models to aid the programmer with specifying the correct
27071 elaboration order and to diagnose elaboration problems.
27073 @geindex Dynamic elaboration model
27076 @itemize *
27078 @item 
27079 `Dynamic elaboration model'
27081 This is the most permissive of the three elaboration models and emulates the
27082 behavior specified by the Ada Reference Manual. When the dynamic model is in
27083 effect, GNAT makes the following assumptions:
27086 @itemize -
27088 @item 
27089 All code within all units in a partition is considered to be elaboration
27090 code.
27092 @item 
27093 Some of the invocations in elaboration code may not take place at run time
27094 due to conditional execution.
27095 @end itemize
27097 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
27098 that invoke internal targets. In addition, GNAT generates run-time checks for
27099 all external targets and for all scenarios that may exhibit ABE problems.
27101 The elaboration order is obtained by honoring all `with' clauses, purity and
27102 preelaborability of units, and elaboration-control pragmas. The dynamic model
27103 attempts to take all invocations in elaboration code into account. If an
27104 invocation leads to a circularity, GNAT ignores the invocation based on the
27105 assumptions stated above. An order obtained using the dynamic model may fail
27106 an ABE check at run time when GNAT ignored an invocation.
27108 The dynamic model is enabled with compiler switch @code{-gnatE}.
27109 @end itemize
27111 @geindex Static elaboration model
27114 @itemize *
27116 @item 
27117 `Static elaboration model'
27119 This is the middle ground of the three models. When the static model is in
27120 effect, GNAT makes the following assumptions:
27123 @itemize -
27125 @item 
27126 Only code at the library level and in package body statements within all
27127 units in a partition is considered to be elaboration code.
27129 @item 
27130 All invocations in elaboration will take place at run time, regardless of
27131 conditional execution.
27132 @end itemize
27134 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
27135 that invoke internal targets. In addition, GNAT generates run-time checks for
27136 all external targets and for all scenarios that may exhibit ABE problems.
27138 The elaboration order is obtained by honoring all `with' clauses, purity and
27139 preelaborability of units, presence of elaboration-control pragmas, and all
27140 invocations in elaboration code. An order obtained using the static model is
27141 guaranteed to be ABE problem-free, excluding dispatching calls and
27142 access-to-subprogram types.
27144 The static model is the default model in GNAT.
27145 @end itemize
27147 @geindex SPARK elaboration model
27150 @itemize *
27152 @item 
27153 `SPARK elaboration model'
27155 This is the most conservative of the three models and enforces the SPARK
27156 rules of elaboration as defined in the SPARK Reference Manual, section 7.7.
27157 The SPARK model is in effect only when a scenario and a target reside in a
27158 region subject to @code{SPARK_Mode On}, otherwise the dynamic or static model
27159 is in effect.
27161 The SPARK model is enabled with compiler switch @code{-gnatd.v}.
27162 @end itemize
27164 @geindex Legacy elaboration models
27167 @itemize *
27169 @item 
27170 `Legacy elaboration models'
27172 In addition to the three elaboration models outlined above, GNAT provides the
27173 following legacy models:
27176 @itemize -
27178 @item 
27179 @cite{Legacy elaboration-checking model} available in pre-18.x versions of GNAT.
27180 This model is enabled with compiler switch @code{-gnatH}.
27182 @item 
27183 @cite{Legacy elaboration-order model} available in pre-20.x versions of GNAT.
27184 This model is enabled with binder switch @code{-H}.
27185 @end itemize
27186 @end itemize
27188 @geindex Relaxed elaboration mode
27190 The dynamic, legacy, and static models can be relaxed using compiler switch
27191 @code{-gnatJ}, making them more permissive. Note that in this mode, GNAT
27192 may not diagnose certain elaboration issues or install run-time checks.
27194 @node Mixing Elaboration Models,ABE Diagnostics,Controlling the Elaboration Order in GNAT,Elaboration Order Handling in GNAT
27195 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{226}@anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{227}
27196 @section Mixing Elaboration Models
27199 It is possible to mix units compiled with a different elaboration model,
27200 however the following rules must be observed:
27203 @itemize *
27205 @item 
27206 A client unit compiled with the dynamic model can only `with' a server unit
27207 that meets at least one of the following criteria:
27210 @itemize -
27212 @item 
27213 The server unit is compiled with the dynamic model.
27215 @item 
27216 The server unit is a GNAT implementation unit from the @code{Ada}, @code{GNAT},
27217 @code{Interfaces}, or @code{System} hierarchies.
27219 @item 
27220 The server unit has pragma @code{Pure} or @code{Preelaborate}.
27222 @item 
27223 The client unit has an explicit @code{Elaborate_All} pragma for the server
27224 unit.
27225 @end itemize
27226 @end itemize
27228 These rules ensure that elaboration checks are not omitted. If the rules are
27229 violated, the binder emits a warning:
27231 @quotation
27233 @example
27234 warning: "x.ads" has dynamic elaboration checks and with's
27235 warning:   "y.ads" which has static elaboration checks
27236 @end example
27237 @end quotation
27239 The warnings can be suppressed by binder switch @code{-ws}.
27241 @node ABE Diagnostics,SPARK Diagnostics,Mixing Elaboration Models,Elaboration Order Handling in GNAT
27242 @anchor{gnat_ugn/elaboration_order_handling_in_gnat abe-diagnostics}@anchor{228}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{229}
27243 @section ABE Diagnostics
27246 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
27247 that invoke internal targets, regardless of whether the dynamic, SPARK, or
27248 static model is in effect.
27250 Note that GNAT emits warnings rather than hard errors whenever it encounters an
27251 elaboration problem. This is because the elaboration model in effect may be too
27252 conservative, or a particular scenario may not be invoked due conditional
27253 execution. The warnings can be suppressed selectively with @code{pragma Warnings
27254 (Off)} or globally with compiler switch @code{-gnatwL}.
27256 A `guaranteed ABE' arises when the body of a target is not elaborated early
27257 enough, and causes `all' scenarios that directly invoke the target to fail.
27259 @quotation
27261 @example
27262 package body Guaranteed_ABE is
27263    function ABE return Integer;
27265    Val : constant Integer := ABE;
27267    function ABE return Integer is
27268    begin
27269      ...
27270    end ABE;
27271 end Guaranteed_ABE;
27272 @end example
27273 @end quotation
27275 In the example above, the elaboration of @code{Guaranteed_ABE}’s body elaborates
27276 the declaration of @code{Val}. This invokes function @code{ABE}, however the body of
27277 @code{ABE} has not been elaborated yet. GNAT emits the following diagnostic:
27279 @quotation
27281 @example
27282 4.    Val : constant Integer := ABE;
27283                                 |
27284    >>> warning: cannot call "ABE" before body seen
27285    >>> warning: Program_Error will be raised at run time
27286 @end example
27287 @end quotation
27289 A `conditional ABE' arises when the body of a target is not elaborated early
27290 enough, and causes `some' scenarios that directly invoke the target to fail.
27292 @quotation
27294 @example
27295  1. package body Conditional_ABE is
27296  2.    procedure Force_Body is null;
27297  3.
27298  4.    generic
27299  5.       with function Func return Integer;
27300  6.    package Gen is
27301  7.       Val : constant Integer := Func;
27302  8.    end Gen;
27303  9.
27304 10.    function ABE return Integer;
27306 12.    function Cause_ABE return Boolean is
27307 13.       package Inst is new Gen (ABE);
27308 14.    begin
27309 15.       ...
27310 16.    end Cause_ABE;
27312 18.    Val : constant Boolean := Cause_ABE;
27314 20.    function ABE return Integer is
27315 21.    begin
27316 22.       ...
27317 23.    end ABE;
27319 25.    Safe : constant Boolean := Cause_ABE;
27320 26. end Conditional_ABE;
27321 @end example
27322 @end quotation
27324 In the example above, the elaboration of package body @code{Conditional_ABE}
27325 elaborates the declaration of @code{Val}. This invokes function @code{Cause_ABE},
27326 which instantiates generic unit @code{Gen} as @code{Inst}. The elaboration of
27327 @code{Inst} invokes function @code{ABE}, however the body of @code{ABE} has not been
27328 elaborated yet. GNAT emits the following diagnostic:
27330 @quotation
27332 @example
27333 13.       package Inst is new Gen (ABE);
27334           |
27335     >>> warning: in instantiation at line 7
27336     >>> warning: cannot call "ABE" before body seen
27337     >>> warning: Program_Error may be raised at run time
27338     >>> warning:   body of unit "Conditional_ABE" elaborated
27339     >>> warning:   function "Cause_ABE" called at line 18
27340     >>> warning:   function "ABE" called at line 7, instance at line 13
27341 @end example
27342 @end quotation
27344 Note that the same ABE problem does not occur with the elaboration of
27345 declaration @code{Safe} because the body of function @code{ABE} has already been
27346 elaborated at that point.
27348 @node SPARK Diagnostics,Elaboration Circularities,ABE Diagnostics,Elaboration Order Handling in GNAT
27349 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{22a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat spark-diagnostics}@anchor{22b}
27350 @section SPARK Diagnostics
27353 GNAT enforces the SPARK rules of elaboration as defined in the SPARK Reference
27354 Manual section 7.7 when compiler switch @code{-gnatd.v} is in effect. Note
27355 that GNAT emits hard errors whenever it encounters a violation of the SPARK
27356 rules.
27358 @quotation
27360 @example
27361 1. with Server;
27362 2. package body SPARK_Diagnostics with SPARK_Mode is
27363 3.    Val : constant Integer := Server.Func;
27364                                       |
27365    >>> call to "Func" during elaboration in SPARK
27366    >>> unit "SPARK_Diagnostics" requires pragma "Elaborate_All" for "Server"
27367    >>>   body of unit "SPARK_Model" elaborated
27368    >>>   function "Func" called at line 3
27370 4. end SPARK_Diagnostics;
27371 @end example
27372 @end quotation
27374 @node Elaboration Circularities,Resolving Elaboration Circularities,SPARK Diagnostics,Elaboration Order Handling in GNAT
27375 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-circularities}@anchor{22c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{22d}
27376 @section Elaboration Circularities
27379 An `elaboration circularity' occurs whenever the elaboration of a set of
27380 units enters a deadlocked state, where each unit is waiting for another unit
27381 to be elaborated. This situation may be the result of improper use of `with'
27382 clauses, elaboration-control pragmas, or invocations in elaboration code.
27384 The following example exhibits an elaboration circularity.
27386 @quotation
27388 @example
27389 with B; pragma Elaborate (B);
27390 package A is
27391 end A;
27392 @end example
27394 @example
27395 package B is
27396    procedure Force_Body;
27397 end B;
27398 @end example
27400 @example
27401 with C;
27402 package body B is
27403    procedure Force_Body is null;
27405    Elab : constant Integer := C.Func;
27406 end B;
27407 @end example
27409 @example
27410 package C is
27411    function Func return Integer;
27412 end C;
27413 @end example
27415 @example
27416 with A;
27417 package body C is
27418    function Func return Integer is
27419    begin
27420       ...
27421    end Func;
27422 end C;
27423 @end example
27424 @end quotation
27426 The binder emits the following diagnostic:
27428 @quotation
27430 @example
27431 error: Elaboration circularity detected
27432 info:
27433 info:    Reason:
27434 info:
27435 info:      unit "a (spec)" depends on its own elaboration
27436 info:
27437 info:    Circularity:
27438 info:
27439 info:      unit "a (spec)" has with clause and pragma Elaborate for unit "b (spec)"
27440 info:      unit "b (body)" is in the closure of pragma Elaborate
27441 info:      unit "b (body)" invokes a construct of unit "c (body)" at elaboration time
27442 info:      unit "c (body)" has with clause for unit "a (spec)"
27443 info:
27444 info:    Suggestions:
27445 info:
27446 info:      remove pragma Elaborate for unit "b (body)" in unit "a (spec)"
27447 info:      use the dynamic elaboration model (compiler switch -gnatE)
27448 @end example
27449 @end quotation
27451 The diagnostic consist of the following sections:
27454 @itemize *
27456 @item 
27457 Reason
27459 This section provides a short explanation describing why the set of units
27460 could not be ordered.
27462 @item 
27463 Circularity
27465 This section enumerates the units comprising the deadlocked set, along with
27466 their interdependencies.
27468 @item 
27469 Suggestions
27471 This section enumerates various tactics for eliminating the circularity.
27472 @end itemize
27474 @node Resolving Elaboration Circularities,Elaboration-related Compiler Switches,Elaboration Circularities,Elaboration Order Handling in GNAT
27475 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{22e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat resolving-elaboration-circularities}@anchor{22f}
27476 @section Resolving Elaboration Circularities
27479 The most desirable option from the point of view of long-term maintenance is to
27480 rearrange the program so that the elaboration problems are avoided. One useful
27481 technique is to place the elaboration code into separate child packages.
27482 Another is to move some of the initialization code to explicitly invoked
27483 subprograms, where the program controls the order of initialization explicitly.
27484 Although this is the most desirable option, it may be impractical and involve
27485 too much modification, especially in the case of complex legacy code.
27487 When faced with an elaboration circularity, the programmer should also consider
27488 the tactics given in the suggestions section of the circularity diagnostic.
27489 Depending on the units involved in the circularity, their `with' clauses,
27490 purity, preelaborability, presence of elaboration-control pragmas and
27491 invocations at elaboration time, the binder may suggest one or more of the
27492 following tactics to eliminate the circularity:
27495 @itemize *
27497 @item 
27498 Pragma Elaborate elimination
27500 @example
27501 remove pragma Elaborate for unit "..." in unit "..."
27502 @end example
27504 This tactic is suggested when the binder has determined that pragma
27505 @code{Elaborate}:
27508 @itemize -
27510 @item 
27511 Prevents a set of units from being elaborated.
27513 @item 
27514 The removal of the pragma will not eliminate the semantic effects of the
27515 pragma. In other words, the argument of the pragma will still be elaborated
27516 prior to the unit containing the pragma.
27518 @item 
27519 The removal of the pragma will enable the successful ordering of the units.
27520 @end itemize
27522 The programmer should remove the pragma as advised, and rebuild the program.
27524 @item 
27525 Pragma Elaborate_All elimination
27527 @example
27528 remove pragma Elaborate_All for unit "..." in unit "..."
27529 @end example
27531 This tactic is suggested when the binder has determined that pragma
27532 @code{Elaborate_All}:
27535 @itemize -
27537 @item 
27538 Prevents a set of units from being elaborated.
27540 @item 
27541 The removal of the pragma will not eliminate the semantic effects of the
27542 pragma. In other words, the argument of the pragma along with its `with'
27543 closure will still be elaborated prior to the unit containing the pragma.
27545 @item 
27546 The removal of the pragma will enable the successful ordering of the units.
27547 @end itemize
27549 The programmer should remove the pragma as advised, and rebuild the program.
27551 @item 
27552 Pragma Elaborate_All downgrade
27554 @example
27555 change pragma Elaborate_All for unit "..." to Elaborate in unit "..."
27556 @end example
27558 This tactic is always suggested with the pragma @code{Elaborate_All} elimination
27559 tactic. It offers a different alternative of guaranteeing that the argument
27560 of the pragma will still be elaborated prior to the unit containing the
27561 pragma.
27563 The programmer should update the pragma as advised, and rebuild the program.
27565 @item 
27566 Pragma Elaborate_Body elimination
27568 @example
27569 remove pragma Elaborate_Body in unit "..."
27570 @end example
27572 This tactic is suggested when the binder has determined that pragma
27573 @code{Elaborate_Body}:
27576 @itemize -
27578 @item 
27579 Prevents a set of units from being elaborated.
27581 @item 
27582 The removal of the pragma will enable the successful ordering of the units.
27583 @end itemize
27585 Note that the binder cannot determine whether the pragma is required for
27586 other purposes, such as guaranteeing the initialization of a variable
27587 declared in the spec by elaboration code in the body.
27589 The programmer should remove the pragma as advised, and rebuild the program.
27591 @item 
27592 Use of pragma Restrictions
27594 @example
27595 use pragma Restrictions (No_Entry_Calls_In_Elaboration_Code)
27596 @end example
27598 This tactic is suggested when the binder has determined that a task
27599 activation at elaboration time:
27602 @itemize -
27604 @item 
27605 Prevents a set of units from being elaborated.
27606 @end itemize
27608 Note that the binder cannot determine with certainty whether the task will
27609 block at elaboration time.
27611 The programmer should create a configuration file, place the pragma within,
27612 update the general compilation arguments, and rebuild the program.
27614 @item 
27615 Use of dynamic elaboration model
27617 @example
27618 use the dynamic elaboration model (compiler switch -gnatE)
27619 @end example
27621 This tactic is suggested when the binder has determined that an invocation at
27622 elaboration time:
27625 @itemize -
27627 @item 
27628 Prevents a set of units from being elaborated.
27630 @item 
27631 The use of the dynamic model will enable the successful ordering of the
27632 units.
27633 @end itemize
27635 The programmer has two options:
27638 @itemize -
27640 @item 
27641 Determine the units involved in the invocation using the detailed
27642 invocation information, and add compiler switch @code{-gnatE} to the
27643 compilation arguments of selected files only. This approach will yield
27644 safer elaboration orders compared to the other option because it will
27645 minimize the opportunities presented to the dynamic model for ignoring
27646 invocations.
27648 @item 
27649 Add compiler switch @code{-gnatE} to the general compilation arguments.
27650 @end itemize
27652 @item 
27653 Use of detailed invocation information
27655 @example
27656 use detailed invocation information (compiler switch -gnatd_F)
27657 @end example
27659 This tactic is always suggested with the use of the dynamic model tactic. It
27660 causes the circularity section of the circularity diagnostic to describe the
27661 flow of elaboration code from a unit to a unit, enumerating all such paths in
27662 the process.
27664 The programmer should analyze this information to determine which units
27665 should be compiled with the dynamic model.
27667 @item 
27668 Forced-dependency elimination
27670 @example
27671 remove the dependency of unit "..." on unit "..." from the argument of switch -f
27672 @end example
27674 This tactic is suggested when the binder has determined that a dependency
27675 present in the forced-elaboration-order file indicated by binder switch
27676 @code{-f}:
27679 @itemize -
27681 @item 
27682 Prevents a set of units from being elaborated.
27684 @item 
27685 The removal of the dependency will enable the successful ordering of the
27686 units.
27687 @end itemize
27689 The programmer should edit the forced-elaboration-order file, remove the
27690 dependency, and rebind the program.
27692 @item 
27693 All forced-dependency elimination
27695 @example
27696 remove switch -f
27697 @end example
27699 This tactic is suggested in case editing the forced-elaboration-order file is
27700 not an option.
27702 The programmer should remove binder switch @code{-f} from the binder
27703 arguments, and rebind.
27705 @item 
27706 Multiple-circularities diagnostic
27708 @example
27709 diagnose all circularities (binder switch -d_C)
27710 @end example
27712 By default, the binder will diagnose only the highest-precedence circularity.
27713 If the program contains multiple circularities, the binder will suggest the
27714 use of binder switch @code{-d_C} in order to obtain the diagnostics of all
27715 circularities.
27717 The programmer should add binder switch @code{-d_C} to the binder
27718 arguments, and rebind.
27719 @end itemize
27721 If none of the tactics suggested by the binder eliminate the elaboration
27722 circularity, the programmer should consider using one of the legacy elaboration
27723 models, in the following order:
27726 @itemize *
27728 @item 
27729 Use the pre-20.x legacy elaboration-order model, with binder switch
27730 @code{-H}.
27732 @item 
27733 Use both pre-18.x and pre-20.x legacy elaboration models, with compiler
27734 switch @code{-gnatH} and binder switch @code{-H}.
27736 @item 
27737 Use the relaxed static-elaboration model, with compiler switches
27738 @code{-gnatH} @code{-gnatJ} and binder switch @code{-H}.
27740 @item 
27741 Use the relaxed dynamic-elaboration model, with compiler switches
27742 @code{-gnatH} @code{-gnatJ} @code{-gnatE} and binder switch
27743 @code{-H}.
27744 @end itemize
27746 @node Elaboration-related Compiler Switches,Summary of Procedures for Elaboration Control,Resolving Elaboration Circularities,Elaboration Order Handling in GNAT
27747 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-related-compiler-switches}@anchor{230}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id12}@anchor{231}
27748 @section Elaboration-related Compiler Switches
27751 GNAT has several switches that affect the elaboration model and consequently
27752 the elaboration order chosen by the binder.
27754 @geindex -gnatE (gnat)
27757 @table @asis
27759 @item @code{-gnatE}
27761 Dynamic elaboration checking mode enabled
27763 When this switch is in effect, GNAT activates the dynamic model.
27764 @end table
27766 @geindex -gnatel (gnat)
27769 @table @asis
27771 @item @code{-gnatel}
27773 Turn on info messages on generated Elaborate[_All] pragmas
27775 This switch is only applicable to the pre-20.x legacy elaboration models.
27776 The post-20.x elaboration model no longer relies on implicitly generated
27777 @code{Elaborate} and @code{Elaborate_All} pragmas to order units.
27779 When this switch is in effect, GNAT will emit the following supplementary
27780 information depending on the elaboration model in effect.
27783 @itemize -
27785 @item 
27786 `Dynamic model'
27788 GNAT will indicate missing @code{Elaborate} and @code{Elaborate_All} pragmas for
27789 all library-level scenarios within the partition.
27791 @item 
27792 `Static model'
27794 GNAT will indicate all scenarios invoked during elaboration. In addition,
27795 it will provide detailed traceback when an implicit @code{Elaborate} or
27796 @code{Elaborate_All} pragma is generated.
27798 @item 
27799 `SPARK model'
27801 GNAT will indicate how an elaboration requirement is met by the context of
27802 a unit. This diagnostic requires compiler switch @code{-gnatd.v}.
27804 @example
27805 1. with Server; pragma Elaborate_All (Server);
27806 2. package Client with SPARK_Mode is
27807 3.    Val : constant Integer := Server.Func;
27808                                       |
27809    >>> info: call to "Func" during elaboration in SPARK
27810    >>> info: "Elaborate_All" requirement for unit "Server" met by pragma at line 1
27812 4. end Client;
27813 @end example
27814 @end itemize
27815 @end table
27817 @geindex -gnatH (gnat)
27820 @table @asis
27822 @item @code{-gnatH}
27824 Legacy elaboration checking mode enabled
27826 When this switch is in effect, GNAT will utilize the pre-18.x elaboration
27827 model.
27828 @end table
27830 @geindex -gnatJ (gnat)
27833 @table @asis
27835 @item @code{-gnatJ}
27837 Relaxed elaboration checking mode enabled
27839 When this switch is in effect, GNAT will not process certain scenarios,
27840 resulting in a more permissive elaboration model. Note that this may
27841 eliminate some diagnostics and run-time checks.
27842 @end table
27844 @geindex -gnatw.f (gnat)
27847 @table @asis
27849 @item @code{-gnatw.f}
27851 Turn on warnings for suspicious Subp’Access
27853 When this switch is in effect, GNAT will treat @code{'Access} of an entry,
27854 operator, or subprogram as a potential call to the target and issue warnings:
27856 @example
27857  1. package body Attribute_Call is
27858  2.    function Func return Integer;
27859  3.    type Func_Ptr is access function return Integer;
27860  4.
27861  5.    Ptr : constant Func_Ptr := Func'Access;
27862                                       |
27863     >>> warning: "Access" attribute of "Func" before body seen
27864     >>> warning: possible Program_Error on later references
27865     >>> warning:   body of unit "Attribute_Call" elaborated
27866     >>> warning:   "Access" of "Func" taken at line 5
27868  6.
27869  7.    function Func return Integer is
27870  8.    begin
27871  9.       ...
27872 10.    end Func;
27873 11. end Attribute_Call;
27874 @end example
27876 In the example above, the elaboration of declaration @code{Ptr} is assigned
27877 @code{Func'Access} before the body of @code{Func} has been elaborated.
27878 @end table
27880 @geindex -gnatwl (gnat)
27883 @table @asis
27885 @item @code{-gnatwl}
27887 Turn on warnings for elaboration problems
27889 When this switch is in effect, GNAT emits diagnostics in the form of warnings
27890 concerning various elaboration problems. The warnings are enabled by default.
27891 The switch is provided in case all warnings are suppressed, but elaboration
27892 warnings are still desired.
27894 @item @code{-gnatwL}
27896 Turn off warnings for elaboration problems
27898 When this switch is in effect, GNAT no longer emits any diagnostics in the
27899 form of warnings. Selective suppression of elaboration problems is possible
27900 using @code{pragma Warnings (Off)}.
27902 @example
27903  1. package body Selective_Suppression is
27904  2.    function ABE return Integer;
27905  3.
27906  4.    Val_1 : constant Integer := ABE;
27907                                    |
27908     >>> warning: cannot call "ABE" before body seen
27909     >>> warning: Program_Error will be raised at run time
27911  5.
27912  6.    pragma Warnings (Off);
27913  7.    Val_2 : constant Integer := ABE;
27914  8.    pragma Warnings (On);
27915  9.
27916 10.    function ABE return Integer is
27917 11.    begin
27918 12.       ...
27919 13.    end ABE;
27920 14. end Selective_Suppression;
27921 @end example
27923 Note that suppressing elaboration warnings does not eliminate run-time
27924 checks. The example above will still fail at run time with an ABE.
27925 @end table
27927 @node Summary of Procedures for Elaboration Control,Inspecting the Chosen Elaboration Order,Elaboration-related Compiler Switches,Elaboration Order Handling in GNAT
27928 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id13}@anchor{232}@anchor{gnat_ugn/elaboration_order_handling_in_gnat summary-of-procedures-for-elaboration-control}@anchor{233}
27929 @section Summary of Procedures for Elaboration Control
27932 A programmer should first compile the program with the default options, using
27933 none of the binder or compiler switches. If the binder succeeds in finding an
27934 elaboration order, then apart from possible cases involving dispatching calls
27935 and access-to-subprogram types, the program is free of elaboration errors.
27937 If it is important for the program to be portable to compilers other than GNAT,
27938 then the programmer should use compiler switch @code{-gnatel} and consider
27939 the messages about missing or implicitly created @code{Elaborate} and
27940 @code{Elaborate_All} pragmas.
27942 If the binder reports an elaboration circularity, the programmer has several
27943 options:
27946 @itemize *
27948 @item 
27949 Ensure that elaboration warnings are enabled. This will allow the static
27950 model to output trace information of elaboration issues. The trace
27951 information could shed light on previously unforeseen dependencies, as well
27952 as their origins. Elaboration warnings are enabled with compiler switch
27953 @code{-gnatwl}.
27955 @item 
27956 Cosider the tactics given in the suggestions section of the circularity
27957 diagnostic.
27959 @item 
27960 If none of the steps outlined above resolve the circularity, use a more
27961 permissive elaboration model, in the following order:
27964 @itemize -
27966 @item 
27967 Use the pre-20.x legacy elaboration-order model, with binder switch
27968 @code{-H}.
27970 @item 
27971 Use both pre-18.x and pre-20.x legacy elaboration models, with compiler
27972 switch @code{-gnatH} and binder switch @code{-H}.
27974 @item 
27975 Use the relaxed static elaboration model, with compiler switches
27976 @code{-gnatH} @code{-gnatJ} and binder switch @code{-H}.
27978 @item 
27979 Use the relaxed dynamic elaboration model, with compiler switches
27980 @code{-gnatH} @code{-gnatJ} @code{-gnatE} and binder switch
27981 @code{-H}.
27982 @end itemize
27983 @end itemize
27985 @node Inspecting the Chosen Elaboration Order,,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
27986 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id14}@anchor{234}@anchor{gnat_ugn/elaboration_order_handling_in_gnat inspecting-the-chosen-elaboration-order}@anchor{235}
27987 @section Inspecting the Chosen Elaboration Order
27990 To see the elaboration order chosen by the binder, inspect the contents of file
27991 @cite{b~xxx.adb}. On certain targets, this file appears as @cite{b_xxx.adb}. The
27992 elaboration order appears as a sequence of calls to @code{Elab_Body} and
27993 @code{Elab_Spec}, interspersed with assignments to @cite{Exxx} which indicates that a
27994 particular unit is elaborated. For example:
27996 @quotation
27998 @example
27999 System.Soft_Links'Elab_Body;
28000 E14 := True;
28001 System.Secondary_Stack'Elab_Body;
28002 E18 := True;
28003 System.Exception_Table'Elab_Body;
28004 E24 := True;
28005 Ada.Io_Exceptions'Elab_Spec;
28006 E67 := True;
28007 Ada.Tags'Elab_Spec;
28008 Ada.Streams'Elab_Spec;
28009 E43 := True;
28010 Interfaces.C'Elab_Spec;
28011 E69 := True;
28012 System.Finalization_Root'Elab_Spec;
28013 E60 := True;
28014 System.Os_Lib'Elab_Body;
28015 E71 := True;
28016 System.Finalization_Implementation'Elab_Spec;
28017 System.Finalization_Implementation'Elab_Body;
28018 E62 := True;
28019 Ada.Finalization'Elab_Spec;
28020 E58 := True;
28021 Ada.Finalization.List_Controller'Elab_Spec;
28022 E76 := True;
28023 System.File_Control_Block'Elab_Spec;
28024 E74 := True;
28025 System.File_Io'Elab_Body;
28026 E56 := True;
28027 Ada.Tags'Elab_Body;
28028 E45 := True;
28029 Ada.Text_Io'Elab_Spec;
28030 Ada.Text_Io'Elab_Body;
28031 E07 := True;
28032 @end example
28033 @end quotation
28035 Note also binder switch @code{-l}, which outputs the chosen elaboration
28036 order and provides a more readable form of the above:
28038 @quotation
28040 @example
28041 ada (spec)
28042 interfaces (spec)
28043 system (spec)
28044 system.case_util (spec)
28045 system.case_util (body)
28046 system.concat_2 (spec)
28047 system.concat_2 (body)
28048 system.concat_3 (spec)
28049 system.concat_3 (body)
28050 system.htable (spec)
28051 system.parameters (spec)
28052 system.parameters (body)
28053 system.crtl (spec)
28054 interfaces.c_streams (spec)
28055 interfaces.c_streams (body)
28056 system.restrictions (spec)
28057 system.restrictions (body)
28058 system.standard_library (spec)
28059 system.exceptions (spec)
28060 system.exceptions (body)
28061 system.storage_elements (spec)
28062 system.storage_elements (body)
28063 system.secondary_stack (spec)
28064 system.stack_checking (spec)
28065 system.stack_checking (body)
28066 system.string_hash (spec)
28067 system.string_hash (body)
28068 system.htable (body)
28069 system.strings (spec)
28070 system.strings (body)
28071 system.traceback (spec)
28072 system.traceback (body)
28073 system.traceback_entries (spec)
28074 system.traceback_entries (body)
28075 ada.exceptions (spec)
28076 ada.exceptions.last_chance_handler (spec)
28077 system.soft_links (spec)
28078 system.soft_links (body)
28079 ada.exceptions.last_chance_handler (body)
28080 system.secondary_stack (body)
28081 system.exception_table (spec)
28082 system.exception_table (body)
28083 ada.io_exceptions (spec)
28084 ada.tags (spec)
28085 ada.streams (spec)
28086 interfaces.c (spec)
28087 interfaces.c (body)
28088 system.finalization_root (spec)
28089 system.finalization_root (body)
28090 system.memory (spec)
28091 system.memory (body)
28092 system.standard_library (body)
28093 system.os_lib (spec)
28094 system.os_lib (body)
28095 system.unsigned_types (spec)
28096 system.stream_attributes (spec)
28097 system.stream_attributes (body)
28098 system.finalization_implementation (spec)
28099 system.finalization_implementation (body)
28100 ada.finalization (spec)
28101 ada.finalization (body)
28102 ada.finalization.list_controller (spec)
28103 ada.finalization.list_controller (body)
28104 system.file_control_block (spec)
28105 system.file_io (spec)
28106 system.file_io (body)
28107 system.val_uns (spec)
28108 system.val_util (spec)
28109 system.val_util (body)
28110 system.val_uns (body)
28111 system.wch_con (spec)
28112 system.wch_con (body)
28113 system.wch_cnv (spec)
28114 system.wch_jis (spec)
28115 system.wch_jis (body)
28116 system.wch_cnv (body)
28117 system.wch_stw (spec)
28118 system.wch_stw (body)
28119 ada.tags (body)
28120 ada.exceptions (body)
28121 ada.text_io (spec)
28122 ada.text_io (body)
28123 text_io (spec)
28124 gdbstr (body)
28125 @end example
28126 @end quotation
28128 @node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
28129 @anchor{gnat_ugn/inline_assembler doc}@anchor{236}@anchor{gnat_ugn/inline_assembler id1}@anchor{237}@anchor{gnat_ugn/inline_assembler inline-assembler}@anchor{10}
28130 @chapter Inline Assembler
28133 @geindex Inline Assembler
28135 If you need to write low-level software that interacts directly
28136 with the hardware, Ada provides two ways to incorporate assembly
28137 language code into your program.  First, you can import and invoke
28138 external routines written in assembly language, an Ada feature fully
28139 supported by GNAT.  However, for small sections of code it may be simpler
28140 or more efficient to include assembly language statements directly
28141 in your Ada source program, using the facilities of the implementation-defined
28142 package @code{System.Machine_Code}, which incorporates the gcc
28143 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
28144 including the following:
28147 @itemize *
28149 @item 
28150 No need to use non-Ada tools
28152 @item 
28153 Consistent interface over different targets
28155 @item 
28156 Automatic usage of the proper calling conventions
28158 @item 
28159 Access to Ada constants and variables
28161 @item 
28162 Definition of intrinsic routines
28164 @item 
28165 Possibility of inlining a subprogram comprising assembler code
28167 @item 
28168 Code optimizer can take Inline Assembler code into account
28169 @end itemize
28171 This appendix presents a series of examples to show you how to use
28172 the Inline Assembler.  Although it focuses on the Intel x86,
28173 the general approach applies also to other processors.
28174 It is assumed that you are familiar with Ada
28175 and with assembly language programming.
28177 @menu
28178 * Basic Assembler Syntax:: 
28179 * A Simple Example of Inline Assembler:: 
28180 * Output Variables in Inline Assembler:: 
28181 * Input Variables in Inline Assembler:: 
28182 * Inlining Inline Assembler Code:: 
28183 * Other Asm Functionality:: 
28185 @end menu
28187 @node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
28188 @anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{238}@anchor{gnat_ugn/inline_assembler id2}@anchor{239}
28189 @section Basic Assembler Syntax
28192 The assembler used by GNAT and gcc is based not on the Intel assembly
28193 language, but rather on a language that descends from the AT&T Unix
28194 assembler @code{as} (and which is often referred to as ‘AT&T syntax’).
28195 The following table summarizes the main features of @code{as} syntax
28196 and points out the differences from the Intel conventions.
28197 See the gcc @code{as} and @code{gas} (an @code{as} macro
28198 pre-processor) documentation for further information.
28201 @display
28202 `Register names'@w{ }
28203 @display
28204 gcc / @code{as}: Prefix with ‘%’; for example @code{%eax}@w{ }
28205 Intel: No extra punctuation; for example @code{eax}@w{ }
28206 @end display
28207 @end display
28212 @display
28213 `Immediate operand'@w{ }
28214 @display
28215 gcc / @code{as}: Prefix with ‘$’; for example @code{$4}@w{ }
28216 Intel: No extra punctuation; for example @code{4}@w{ }
28217 @end display
28218 @end display
28223 @display
28224 `Address'@w{ }
28225 @display
28226 gcc / @code{as}: Prefix with ‘$’; for example @code{$loc}@w{ }
28227 Intel: No extra punctuation; for example @code{loc}@w{ }
28228 @end display
28229 @end display
28234 @display
28235 `Memory contents'@w{ }
28236 @display
28237 gcc / @code{as}: No extra punctuation; for example @code{loc}@w{ }
28238 Intel: Square brackets; for example @code{[loc]}@w{ }
28239 @end display
28240 @end display
28245 @display
28246 `Register contents'@w{ }
28247 @display
28248 gcc / @code{as}: Parentheses; for example @code{(%eax)}@w{ }
28249 Intel: Square brackets; for example @code{[eax]}@w{ }
28250 @end display
28251 @end display
28256 @display
28257 `Hexadecimal numbers'@w{ }
28258 @display
28259 gcc / @code{as}: Leading ‘0x’ (C language syntax); for example @code{0xA0}@w{ }
28260 Intel: Trailing ‘h’; for example @code{A0h}@w{ }
28261 @end display
28262 @end display
28267 @display
28268 `Operand size'@w{ }
28269 @display
28270 gcc / @code{as}: Explicit in op code; for example @code{movw} to move a 16-bit word@w{ }
28271 Intel: Implicit, deduced by assembler; for example @code{mov}@w{ }
28272 @end display
28273 @end display
28278 @display
28279 `Instruction repetition'@w{ }
28280 @display
28281 gcc / @code{as}: Split into two lines; for example@w{ }
28282 @display
28283 @code{rep}@w{ }
28284 @code{stosl}@w{ }
28285 @end display
28286 Intel: Keep on one line; for example @code{rep stosl}@w{ }
28287 @end display
28288 @end display
28293 @display
28294 `Order of operands'@w{ }
28295 @display
28296 gcc / @code{as}: Source first; for example @code{movw $4, %eax}@w{ }
28297 Intel: Destination first; for example @code{mov eax, 4}@w{ }
28298 @end display
28299 @end display
28303 @node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
28304 @anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{23a}@anchor{gnat_ugn/inline_assembler id3}@anchor{23b}
28305 @section A Simple Example of Inline Assembler
28308 The following example will generate a single assembly language statement,
28309 @code{nop}, which does nothing.  Despite its lack of run-time effect,
28310 the example will be useful in illustrating the basics of
28311 the Inline Assembler facility.
28313 @quotation
28315 @example
28316 with System.Machine_Code; use System.Machine_Code;
28317 procedure Nothing is
28318 begin
28319    Asm ("nop");
28320 end Nothing;
28321 @end example
28322 @end quotation
28324 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
28325 here it takes one parameter, a `template string' that must be a static
28326 expression and that will form the generated instruction.
28327 @code{Asm} may be regarded as a compile-time procedure that parses
28328 the template string and additional parameters (none here),
28329 from which it generates a sequence of assembly language instructions.
28331 The examples in this chapter will illustrate several of the forms
28332 for invoking @code{Asm}; a complete specification of the syntax
28333 is found in the @code{Machine_Code_Insertions} section of the
28334 @cite{GNAT Reference Manual}.
28336 Under the standard GNAT conventions, the @code{Nothing} procedure
28337 should be in a file named @code{nothing.adb}.
28338 You can build the executable in the usual way:
28340 @quotation
28342 @example
28343 $ gnatmake nothing
28344 @end example
28345 @end quotation
28347 However, the interesting aspect of this example is not its run-time behavior
28348 but rather the generated assembly code.
28349 To see this output, invoke the compiler as follows:
28351 @quotation
28353 @example
28354 $ gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
28355 @end example
28356 @end quotation
28358 where the options are:
28361 @itemize *
28363 @item 
28365 @table @asis
28367 @item @code{-c}
28369 compile only (no bind or link)
28370 @end table
28372 @item 
28374 @table @asis
28376 @item @code{-S}
28378 generate assembler listing
28379 @end table
28381 @item 
28383 @table @asis
28385 @item @code{-fomit-frame-pointer}
28387 do not set up separate stack frames
28388 @end table
28390 @item 
28392 @table @asis
28394 @item @code{-gnatp}
28396 do not add runtime checks
28397 @end table
28398 @end itemize
28400 This gives a human-readable assembler version of the code. The resulting
28401 file will have the same name as the Ada source file, but with a @code{.s}
28402 extension. In our example, the file @code{nothing.s} has the following
28403 contents:
28405 @quotation
28407 @example
28408 .file "nothing.adb"
28409 gcc2_compiled.:
28410 ___gnu_compiled_ada:
28411 .text
28412    .align 4
28413 .globl __ada_nothing
28414 __ada_nothing:
28415 #APP
28416    nop
28417 #NO_APP
28418    jmp L1
28419    .align 2,0x90
28421    ret
28422 @end example
28423 @end quotation
28425 The assembly code you included is clearly indicated by
28426 the compiler, between the @code{#APP} and @code{#NO_APP}
28427 delimiters. The character before the ‘APP’ and ‘NOAPP’
28428 can differ on different targets. For example, GNU/Linux uses ‘#APP’ while
28429 on NT you will see ‘/APP’.
28431 If you make a mistake in your assembler code (such as using the
28432 wrong size modifier, or using a wrong operand for the instruction) GNAT
28433 will report this error in a temporary file, which will be deleted when
28434 the compilation is finished.  Generating an assembler file will help
28435 in such cases, since you can assemble this file separately using the
28436 @code{as} assembler that comes with gcc.
28438 Assembling the file using the command
28440 @quotation
28442 @example
28443 $ as nothing.s
28444 @end example
28445 @end quotation
28447 will give you error messages whose lines correspond to the assembler
28448 input file, so you can easily find and correct any mistakes you made.
28449 If there are no errors, @code{as} will generate an object file
28450 @code{nothing.out}.
28452 @node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
28453 @anchor{gnat_ugn/inline_assembler id4}@anchor{23c}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{23d}
28454 @section Output Variables in Inline Assembler
28457 The examples in this section, showing how to access the processor flags,
28458 illustrate how to specify the destination operands for assembly language
28459 statements.
28461 @quotation
28463 @example
28464 with Interfaces; use Interfaces;
28465 with Ada.Text_IO; use Ada.Text_IO;
28466 with System.Machine_Code; use System.Machine_Code;
28467 procedure Get_Flags is
28468    Flags : Unsigned_32;
28469    use ASCII;
28470 begin
28471    Asm ("pushfl"          & LF & HT & -- push flags on stack
28472         "popl %%eax"      & LF & HT & -- load eax with flags
28473         "movl %%eax, %0",             -- store flags in variable
28474         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28475    Put_Line ("Flags register:" & Flags'Img);
28476 end Get_Flags;
28477 @end example
28478 @end quotation
28480 In order to have a nicely aligned assembly listing, we have separated
28481 multiple assembler statements in the Asm template string with linefeed
28482 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
28483 The resulting section of the assembly output file is:
28485 @quotation
28487 @example
28488 #APP
28489    pushfl
28490    popl %eax
28491    movl %eax, -40(%ebp)
28492 #NO_APP
28493 @end example
28494 @end quotation
28496 It would have been legal to write the Asm invocation as:
28498 @quotation
28500 @example
28501 Asm ("pushfl popl %%eax movl %%eax, %0")
28502 @end example
28503 @end quotation
28505 but in the generated assembler file, this would come out as:
28507 @quotation
28509 @example
28510 #APP
28511    pushfl popl %eax movl %eax, -40(%ebp)
28512 #NO_APP
28513 @end example
28514 @end quotation
28516 which is not so convenient for the human reader.
28518 We use Ada comments
28519 at the end of each line to explain what the assembler instructions
28520 actually do.  This is a useful convention.
28522 When writing Inline Assembler instructions, you need to precede each register
28523 and variable name with a percent sign.  Since the assembler already requires
28524 a percent sign at the beginning of a register name, you need two consecutive
28525 percent signs for such names in the Asm template string, thus @code{%%eax}.
28526 In the generated assembly code, one of the percent signs will be stripped off.
28528 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28529 variables: operands you later define using @code{Input} or @code{Output}
28530 parameters to @code{Asm}.
28531 An output variable is illustrated in
28532 the third statement in the Asm template string:
28534 @quotation
28536 @example
28537 movl %%eax, %0
28538 @end example
28539 @end quotation
28541 The intent is to store the contents of the eax register in a variable that can
28542 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
28543 necessarily work, since the compiler might optimize by using a register
28544 to hold Flags, and the expansion of the @code{movl} instruction would not be
28545 aware of this optimization.  The solution is not to store the result directly
28546 but rather to advise the compiler to choose the correct operand form;
28547 that is the purpose of the @code{%0} output variable.
28549 Information about the output variable is supplied in the @code{Outputs}
28550 parameter to @code{Asm}:
28552 @quotation
28554 @example
28555 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28556 @end example
28557 @end quotation
28559 The output is defined by the @code{Asm_Output} attribute of the target type;
28560 the general format is
28562 @quotation
28564 @example
28565 Type'Asm_Output (constraint_string, variable_name)
28566 @end example
28567 @end quotation
28569 The constraint string directs the compiler how
28570 to store/access the associated variable.  In the example
28572 @quotation
28574 @example
28575 Unsigned_32'Asm_Output ("=m", Flags);
28576 @end example
28577 @end quotation
28579 the @code{"m"} (memory) constraint tells the compiler that the variable
28580 @code{Flags} should be stored in a memory variable, thus preventing
28581 the optimizer from keeping it in a register.  In contrast,
28583 @quotation
28585 @example
28586 Unsigned_32'Asm_Output ("=r", Flags);
28587 @end example
28588 @end quotation
28590 uses the @code{"r"} (register) constraint, telling the compiler to
28591 store the variable in a register.
28593 If the constraint is preceded by the equal character ‘=’, it tells
28594 the compiler that the variable will be used to store data into it.
28596 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28597 allowing the optimizer to choose whatever it deems best.
28599 There are a fairly large number of constraints, but the ones that are
28600 most useful (for the Intel x86 processor) are the following:
28602 @quotation
28605 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
28606 @item
28610 @tab
28612 output constraint
28614 @item
28618 @tab
28620 global (i.e., can be stored anywhere)
28622 @item
28626 @tab
28628 in memory
28630 @item
28634 @tab
28636 a constant
28638 @item
28642 @tab
28644 use eax
28646 @item
28650 @tab
28652 use ebx
28654 @item
28658 @tab
28660 use ecx
28662 @item
28666 @tab
28668 use edx
28670 @item
28674 @tab
28676 use esi
28678 @item
28682 @tab
28684 use edi
28686 @item
28690 @tab
28692 use one of eax, ebx, ecx or edx
28694 @item
28698 @tab
28700 use one of eax, ebx, ecx, edx, esi or edi
28702 @end multitable
28704 @end quotation
28706 The full set of constraints is described in the gcc and @code{as}
28707 documentation; note that it is possible to combine certain constraints
28708 in one constraint string.
28710 You specify the association of an output variable with an assembler operand
28711 through the @code{%@var{n}} notation, where `n' is a non-negative
28712 integer.  Thus in
28714 @quotation
28716 @example
28717 Asm ("pushfl"          & LF & HT & -- push flags on stack
28718      "popl %%eax"      & LF & HT & -- load eax with flags
28719      "movl %%eax, %0",             -- store flags in variable
28720      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28721 @end example
28722 @end quotation
28724 @code{%0} will be replaced in the expanded code by the appropriate operand,
28725 whatever
28726 the compiler decided for the @code{Flags} variable.
28728 In general, you may have any number of output variables:
28731 @itemize *
28733 @item 
28734 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28736 @item 
28737 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28738 of @code{Asm_Output} attributes
28739 @end itemize
28741 For example:
28743 @quotation
28745 @example
28746 Asm ("movl %%eax, %0" & LF & HT &
28747      "movl %%ebx, %1" & LF & HT &
28748      "movl %%ecx, %2",
28749      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
28750                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
28751                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
28752 @end example
28753 @end quotation
28755 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28756 in the Ada program.
28758 As a variation on the @code{Get_Flags} example, we can use the constraints
28759 string to direct the compiler to store the eax register into the @code{Flags}
28760 variable, instead of including the store instruction explicitly in the
28761 @code{Asm} template string:
28763 @quotation
28765 @example
28766 with Interfaces; use Interfaces;
28767 with Ada.Text_IO; use Ada.Text_IO;
28768 with System.Machine_Code; use System.Machine_Code;
28769 procedure Get_Flags_2 is
28770    Flags : Unsigned_32;
28771    use ASCII;
28772 begin
28773    Asm ("pushfl"      & LF & HT & -- push flags on stack
28774         "popl %%eax",             -- save flags in eax
28775         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28776    Put_Line ("Flags register:" & Flags'Img);
28777 end Get_Flags_2;
28778 @end example
28779 @end quotation
28781 The @code{"a"} constraint tells the compiler that the @code{Flags}
28782 variable will come from the eax register. Here is the resulting code:
28784 @quotation
28786 @example
28787 #APP
28788    pushfl
28789    popl %eax
28790 #NO_APP
28791    movl %eax,-40(%ebp)
28792 @end example
28793 @end quotation
28795 The compiler generated the store of eax into Flags after
28796 expanding the assembler code.
28798 Actually, there was no need to pop the flags into the eax register;
28799 more simply, we could just pop the flags directly into the program variable:
28801 @quotation
28803 @example
28804 with Interfaces; use Interfaces;
28805 with Ada.Text_IO; use Ada.Text_IO;
28806 with System.Machine_Code; use System.Machine_Code;
28807 procedure Get_Flags_3 is
28808    Flags : Unsigned_32;
28809    use ASCII;
28810 begin
28811    Asm ("pushfl"  & LF & HT & -- push flags on stack
28812         "pop %0",             -- save flags in Flags
28813         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28814    Put_Line ("Flags register:" & Flags'Img);
28815 end Get_Flags_3;
28816 @end example
28817 @end quotation
28819 @node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
28820 @anchor{gnat_ugn/inline_assembler id5}@anchor{23e}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{23f}
28821 @section Input Variables in Inline Assembler
28824 The example in this section illustrates how to specify the source operands
28825 for assembly language statements.
28826 The program simply increments its input value by 1:
28828 @quotation
28830 @example
28831 with Interfaces; use Interfaces;
28832 with Ada.Text_IO; use Ada.Text_IO;
28833 with System.Machine_Code; use System.Machine_Code;
28834 procedure Increment is
28836    function Incr (Value : Unsigned_32) return Unsigned_32 is
28837       Result : Unsigned_32;
28838    begin
28839       Asm ("incl %0",
28840            Outputs => Unsigned_32'Asm_Output ("=a", Result),
28841            Inputs  => Unsigned_32'Asm_Input ("a", Value));
28842       return Result;
28843    end Incr;
28845    Value : Unsigned_32;
28847 begin
28848    Value := 5;
28849    Put_Line ("Value before is" & Value'Img);
28850    Value := Incr (Value);
28851   Put_Line ("Value after is" & Value'Img);
28852 end Increment;
28853 @end example
28854 @end quotation
28856 The @code{Outputs} parameter to @code{Asm} specifies
28857 that the result will be in the eax register and that it is to be stored
28858 in the @code{Result} variable.
28860 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28861 but with an @code{Asm_Input} attribute.
28862 The @code{"="} constraint, indicating an output value, is not present.
28864 You can have multiple input variables, in the same way that you can have more
28865 than one output variable.
28867 The parameter count (%0, %1) etc, still starts at the first output statement,
28868 and continues with the input statements.
28870 Just as the @code{Outputs} parameter causes the register to be stored into the
28871 target variable after execution of the assembler statements, so does the
28872 @code{Inputs} parameter cause its variable to be loaded into the register
28873 before execution of the assembler statements.
28875 Thus the effect of the @code{Asm} invocation is:
28878 @itemize *
28880 @item 
28881 load the 32-bit value of @code{Value} into eax
28883 @item 
28884 execute the @code{incl %eax} instruction
28886 @item 
28887 store the contents of eax into the @code{Result} variable
28888 @end itemize
28890 The resulting assembler file (with @code{-O2} optimization) contains:
28892 @quotation
28894 @example
28895 _increment__incr.1:
28896    subl $4,%esp
28897    movl 8(%esp),%eax
28898 #APP
28899    incl %eax
28900 #NO_APP
28901    movl %eax,%edx
28902    movl %ecx,(%esp)
28903    addl $4,%esp
28904    ret
28905 @end example
28906 @end quotation
28908 @node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
28909 @anchor{gnat_ugn/inline_assembler id6}@anchor{240}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{241}
28910 @section Inlining Inline Assembler Code
28913 For a short subprogram such as the @code{Incr} function in the previous
28914 section, the overhead of the call and return (creating / deleting the stack
28915 frame) can be significant, compared to the amount of code in the subprogram
28916 body.  A solution is to apply Ada’s @code{Inline} pragma to the subprogram,
28917 which directs the compiler to expand invocations of the subprogram at the
28918 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28919 Here is the resulting program:
28921 @quotation
28923 @example
28924 with Interfaces; use Interfaces;
28925 with Ada.Text_IO; use Ada.Text_IO;
28926 with System.Machine_Code; use System.Machine_Code;
28927 procedure Increment_2 is
28929    function Incr (Value : Unsigned_32) return Unsigned_32 is
28930       Result : Unsigned_32;
28931    begin
28932       Asm ("incl %0",
28933            Outputs => Unsigned_32'Asm_Output ("=a", Result),
28934            Inputs  => Unsigned_32'Asm_Input ("a", Value));
28935       return Result;
28936    end Incr;
28937    pragma Inline (Increment);
28939    Value : Unsigned_32;
28941 begin
28942    Value := 5;
28943    Put_Line ("Value before is" & Value'Img);
28944    Value := Increment (Value);
28945    Put_Line ("Value after is" & Value'Img);
28946 end Increment_2;
28947 @end example
28948 @end quotation
28950 Compile the program with both optimization (@code{-O2}) and inlining
28951 (@code{-gnatn}) enabled.
28953 The @code{Incr} function is still compiled as usual, but at the
28954 point in @code{Increment} where our function used to be called:
28956 @quotation
28958 @example
28959 pushl %edi
28960 call _increment__incr.1
28961 @end example
28962 @end quotation
28964 the code for the function body directly appears:
28966 @quotation
28968 @example
28969 movl %esi,%eax
28970 #APP
28971    incl %eax
28972 #NO_APP
28973    movl %eax,%edx
28974 @end example
28975 @end quotation
28977 thus saving the overhead of stack frame setup and an out-of-line call.
28979 @node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
28980 @anchor{gnat_ugn/inline_assembler id7}@anchor{242}@anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{243}
28981 @section Other @code{Asm} Functionality
28984 This section describes two important parameters to the @code{Asm}
28985 procedure: @code{Clobber}, which identifies register usage;
28986 and @code{Volatile}, which inhibits unwanted optimizations.
28988 @menu
28989 * The Clobber Parameter:: 
28990 * The Volatile Parameter:: 
28992 @end menu
28994 @node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
28995 @anchor{gnat_ugn/inline_assembler id8}@anchor{244}@anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{245}
28996 @subsection The @code{Clobber} Parameter
28999 One of the dangers of intermixing assembly language and a compiled language
29000 such as Ada is that the compiler needs to be aware of which registers are
29001 being used by the assembly code.  In some cases, such as the earlier examples,
29002 the constraint string is sufficient to indicate register usage (e.g.,
29003 @code{"a"} for
29004 the eax register).  But more generally, the compiler needs an explicit
29005 identification of the registers that are used by the Inline Assembly
29006 statements.
29008 Using a register that the compiler doesn’t know about
29009 could be a side effect of an instruction (like @code{mull}
29010 storing its result in both eax and edx).
29011 It can also arise from explicit register usage in your
29012 assembly code; for example:
29014 @quotation
29016 @example
29017 Asm ("movl %0, %%ebx" & LF & HT &
29018      "movl %%ebx, %1",
29019      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29020      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
29021 @end example
29022 @end quotation
29024 where the compiler (since it does not analyze the @code{Asm} template string)
29025 does not know you are using the ebx register.
29027 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
29028 to identify the registers that will be used by your assembly code:
29030 @quotation
29032 @example
29033 Asm ("movl %0, %%ebx" & LF & HT &
29034      "movl %%ebx, %1",
29035      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29036      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
29037      Clobber => "ebx");
29038 @end example
29039 @end quotation
29041 The Clobber parameter is a static string expression specifying the
29042 register(s) you are using.  Note that register names are `not' prefixed
29043 by a percent sign. Also, if more than one register is used then their names
29044 are separated by commas; e.g., @code{"eax, ebx"}
29046 The @code{Clobber} parameter has several additional uses:
29049 @itemize *
29051 @item 
29052 Use ‘register’ name @code{cc} to indicate that flags might have changed
29054 @item 
29055 Use ‘register’ name @code{memory} if you changed a memory location
29056 @end itemize
29058 @node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
29059 @anchor{gnat_ugn/inline_assembler id9}@anchor{246}@anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{247}
29060 @subsection The @code{Volatile} Parameter
29063 @geindex Volatile parameter
29065 Compiler optimizations in the presence of Inline Assembler may sometimes have
29066 unwanted effects.  For example, when an @code{Asm} invocation with an input
29067 variable is inside a loop, the compiler might move the loading of the input
29068 variable outside the loop, regarding it as a one-time initialization.
29070 If this effect is not desired, you can disable such optimizations by setting
29071 the @code{Volatile} parameter to @code{True}; for example:
29073 @quotation
29075 @example
29076 Asm ("movl %0, %%ebx" & LF & HT &
29077      "movl %%ebx, %1",
29078      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
29079      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
29080      Clobber  => "ebx",
29081      Volatile => True);
29082 @end example
29083 @end quotation
29085 By default, @code{Volatile} is set to @code{False} unless there is no
29086 @code{Outputs} parameter.
29088 Although setting @code{Volatile} to @code{True} prevents unwanted
29089 optimizations, it will also disable other optimizations that might be
29090 important for efficiency. In general, you should set @code{Volatile}
29091 to @code{True} only if the compiler’s optimizations have created
29092 problems.
29094 @node GNU Free Documentation License,Index,Inline Assembler,Top
29095 @anchor{share/gnu_free_documentation_license doc}@anchor{248}@anchor{share/gnu_free_documentation_license gnu-fdl}@anchor{1}@anchor{share/gnu_free_documentation_license gnu-free-documentation-license}@anchor{249}
29096 @chapter GNU Free Documentation License
29099 Version 1.3, 3 November 2008
29101 Copyright  2000, 2001, 2002, 2007, 2008  Free Software Foundation, Inc
29102 @indicateurl{https://fsf.org/}
29104 Everyone is permitted to copy and distribute verbatim copies of this
29105 license document, but changing it is not allowed.
29107 `Preamble'
29109 The purpose of this License is to make a manual, textbook, or other
29110 functional and useful document “free” in the sense of freedom: to
29111 assure everyone the effective freedom to copy and redistribute it,
29112 with or without modifying it, either commercially or noncommercially.
29113 Secondarily, this License preserves for the author and publisher a way
29114 to get credit for their work, while not being considered responsible
29115 for modifications made by others.
29117 This License is a kind of “copyleft”, which means that derivative
29118 works of the document must themselves be free in the same sense.  It
29119 complements the GNU General Public License, which is a copyleft
29120 license designed for free software.
29122 We have designed this License in order to use it for manuals for free
29123 software, because free software needs free documentation: a free
29124 program should come with manuals providing the same freedoms that the
29125 software does.  But this License is not limited to software manuals;
29126 it can be used for any textual work, regardless of subject matter or
29127 whether it is published as a printed book.  We recommend this License
29128 principally for works whose purpose is instruction or reference.
29130 `1. APPLICABILITY AND DEFINITIONS'
29132 This License applies to any manual or other work, in any medium, that
29133 contains a notice placed by the copyright holder saying it can be
29134 distributed under the terms of this License.  Such a notice grants a
29135 world-wide, royalty-free license, unlimited in duration, to use that
29136 work under the conditions stated herein.  The `Document', below,
29137 refers to any such manual or work.  Any member of the public is a
29138 licensee, and is addressed as “`you'”.  You accept the license if you
29139 copy, modify or distribute the work in a way requiring permission
29140 under copyright law.
29142 A “`Modified Version'” of the Document means any work containing the
29143 Document or a portion of it, either copied verbatim, or with
29144 modifications and/or translated into another language.
29146 A “`Secondary Section'” is a named appendix or a front-matter section of
29147 the Document that deals exclusively with the relationship of the
29148 publishers or authors of the Document to the Document’s overall subject
29149 (or to related matters) and contains nothing that could fall directly
29150 within that overall subject.  (Thus, if the Document is in part a
29151 textbook of mathematics, a Secondary Section may not explain any
29152 mathematics.)  The relationship could be a matter of historical
29153 connection with the subject or with related matters, or of legal,
29154 commercial, philosophical, ethical or political position regarding
29155 them.
29157 The “`Invariant Sections'” are certain Secondary Sections whose titles
29158 are designated, as being those of Invariant Sections, in the notice
29159 that says that the Document is released under this License.  If a
29160 section does not fit the above definition of Secondary then it is not
29161 allowed to be designated as Invariant.  The Document may contain zero
29162 Invariant Sections.  If the Document does not identify any Invariant
29163 Sections then there are none.
29165 The “`Cover Texts'” are certain short passages of text that are listed,
29166 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
29167 the Document is released under this License.  A Front-Cover Text may
29168 be at most 5 words, and a Back-Cover Text may be at most 25 words.
29170 A “`Transparent'” copy of the Document means a machine-readable copy,
29171 represented in a format whose specification is available to the
29172 general public, that is suitable for revising the document
29173 straightforwardly with generic text editors or (for images composed of
29174 pixels) generic paint programs or (for drawings) some widely available
29175 drawing editor, and that is suitable for input to text formatters or
29176 for automatic translation to a variety of formats suitable for input
29177 to text formatters.  A copy made in an otherwise Transparent file
29178 format whose markup, or absence of markup, has been arranged to thwart
29179 or discourage subsequent modification by readers is not Transparent.
29180 An image format is not Transparent if used for any substantial amount
29181 of text.  A copy that is not “Transparent” is called `Opaque'.
29183 Examples of suitable formats for Transparent copies include plain
29184 ASCII without markup, Texinfo input format, LaTeX input format, SGML
29185 or XML using a publicly available DTD, and standard-conforming simple
29186 HTML, PostScript or PDF designed for human modification.  Examples of
29187 transparent image formats include PNG, XCF and JPG.  Opaque formats
29188 include proprietary formats that can be read and edited only by
29189 proprietary word processors, SGML or XML for which the DTD and/or
29190 processing tools are not generally available, and the
29191 machine-generated HTML, PostScript or PDF produced by some word
29192 processors for output purposes only.
29194 The “`Title Page'” means, for a printed book, the title page itself,
29195 plus such following pages as are needed to hold, legibly, the material
29196 this License requires to appear in the title page.  For works in
29197 formats which do not have any title page as such, “Title Page” means
29198 the text near the most prominent appearance of the work’s title,
29199 preceding the beginning of the body of the text.
29201 The “`publisher'” means any person or entity that distributes
29202 copies of the Document to the public.
29204 A section “`Entitled XYZ'” means a named subunit of the Document whose
29205 title either is precisely XYZ or contains XYZ in parentheses following
29206 text that translates XYZ in another language.  (Here XYZ stands for a
29207 specific section name mentioned below, such as “`Acknowledgements'”,
29208 “`Dedications'”, “`Endorsements'”, or “`History'”.)
29209 To “`Preserve the Title'”
29210 of such a section when you modify the Document means that it remains a
29211 section “Entitled XYZ” according to this definition.
29213 The Document may include Warranty Disclaimers next to the notice which
29214 states that this License applies to the Document.  These Warranty
29215 Disclaimers are considered to be included by reference in this
29216 License, but only as regards disclaiming warranties: any other
29217 implication that these Warranty Disclaimers may have is void and has
29218 no effect on the meaning of this License.
29220 `2. VERBATIM COPYING'
29222 You may copy and distribute the Document in any medium, either
29223 commercially or noncommercially, provided that this License, the
29224 copyright notices, and the license notice saying this License applies
29225 to the Document are reproduced in all copies, and that you add no other
29226 conditions whatsoever to those of this License.  You may not use
29227 technical measures to obstruct or control the reading or further
29228 copying of the copies you make or distribute.  However, you may accept
29229 compensation in exchange for copies.  If you distribute a large enough
29230 number of copies you must also follow the conditions in section 3.
29232 You may also lend copies, under the same conditions stated above, and
29233 you may publicly display copies.
29235 `3. COPYING IN QUANTITY'
29237 If you publish printed copies (or copies in media that commonly have
29238 printed covers) of the Document, numbering more than 100, and the
29239 Document’s license notice requires Cover Texts, you must enclose the
29240 copies in covers that carry, clearly and legibly, all these Cover
29241 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
29242 the back cover.  Both covers must also clearly and legibly identify
29243 you as the publisher of these copies.  The front cover must present
29244 the full title with all words of the title equally prominent and
29245 visible.  You may add other material on the covers in addition.
29246 Copying with changes limited to the covers, as long as they preserve
29247 the title of the Document and satisfy these conditions, can be treated
29248 as verbatim copying in other respects.
29250 If the required texts for either cover are too voluminous to fit
29251 legibly, you should put the first ones listed (as many as fit
29252 reasonably) on the actual cover, and continue the rest onto adjacent
29253 pages.
29255 If you publish or distribute Opaque copies of the Document numbering
29256 more than 100, you must either include a machine-readable Transparent
29257 copy along with each Opaque copy, or state in or with each Opaque copy
29258 a computer-network location from which the general network-using
29259 public has access to download using public-standard network protocols
29260 a complete Transparent copy of the Document, free of added material.
29261 If you use the latter option, you must take reasonably prudent steps,
29262 when you begin distribution of Opaque copies in quantity, to ensure
29263 that this Transparent copy will remain thus accessible at the stated
29264 location until at least one year after the last time you distribute an
29265 Opaque copy (directly or through your agents or retailers) of that
29266 edition to the public.
29268 It is requested, but not required, that you contact the authors of the
29269 Document well before redistributing any large number of copies, to give
29270 them a chance to provide you with an updated version of the Document.
29272 `4. MODIFICATIONS'
29274 You may copy and distribute a Modified Version of the Document under
29275 the conditions of sections 2 and 3 above, provided that you release
29276 the Modified Version under precisely this License, with the Modified
29277 Version filling the role of the Document, thus licensing distribution
29278 and modification of the Modified Version to whoever possesses a copy
29279 of it.  In addition, you must do these things in the Modified Version:
29282 @enumerate A
29284 @item 
29285 Use in the Title Page (and on the covers, if any) a title distinct
29286 from that of the Document, and from those of previous versions
29287 (which should, if there were any, be listed in the History section
29288 of the Document).  You may use the same title as a previous version
29289 if the original publisher of that version gives permission.
29291 @item 
29292 List on the Title Page, as authors, one or more persons or entities
29293 responsible for authorship of the modifications in the Modified
29294 Version, together with at least five of the principal authors of the
29295 Document (all of its principal authors, if it has fewer than five),
29296 unless they release you from this requirement.
29298 @item 
29299 State on the Title page the name of the publisher of the
29300 Modified Version, as the publisher.
29302 @item 
29303 Preserve all the copyright notices of the Document.
29305 @item 
29306 Add an appropriate copyright notice for your modifications
29307 adjacent to the other copyright notices.
29309 @item 
29310 Include, immediately after the copyright notices, a license notice
29311 giving the public permission to use the Modified Version under the
29312 terms of this License, in the form shown in the Addendum below.
29314 @item 
29315 Preserve in that license notice the full lists of Invariant Sections
29316 and required Cover Texts given in the Document’s license notice.
29318 @item 
29319 Include an unaltered copy of this License.
29321 @item 
29322 Preserve the section Entitled “History”, Preserve its Title, and add
29323 to it an item stating at least the title, year, new authors, and
29324 publisher of the Modified Version as given on the Title Page.  If
29325 there is no section Entitled “History” in the Document, create one
29326 stating the title, year, authors, and publisher of the Document as
29327 given on its Title Page, then add an item describing the Modified
29328 Version as stated in the previous sentence.
29330 @item 
29331 Preserve the network location, if any, given in the Document for
29332 public access to a Transparent copy of the Document, and likewise
29333 the network locations given in the Document for previous versions
29334 it was based on.  These may be placed in the “History” section.
29335 You may omit a network location for a work that was published at
29336 least four years before the Document itself, or if the original
29337 publisher of the version it refers to gives permission.
29339 @item 
29340 For any section Entitled “Acknowledgements” or “Dedications”,
29341 Preserve the Title of the section, and preserve in the section all
29342 the substance and tone of each of the contributor acknowledgements
29343 and/or dedications given therein.
29345 @item 
29346 Preserve all the Invariant Sections of the Document,
29347 unaltered in their text and in their titles.  Section numbers
29348 or the equivalent are not considered part of the section titles.
29350 @item 
29351 Delete any section Entitled “Endorsements”.  Such a section
29352 may not be included in the Modified Version.
29354 @item 
29355 Do not retitle any existing section to be Entitled “Endorsements”
29356 or to conflict in title with any Invariant Section.
29358 @item 
29359 Preserve any Warranty Disclaimers.
29360 @end enumerate
29362 If the Modified Version includes new front-matter sections or
29363 appendices that qualify as Secondary Sections and contain no material
29364 copied from the Document, you may at your option designate some or all
29365 of these sections as invariant.  To do this, add their titles to the
29366 list of Invariant Sections in the Modified Version’s license notice.
29367 These titles must be distinct from any other section titles.
29369 You may add a section Entitled “Endorsements”, provided it contains
29370 nothing but endorsements of your Modified Version by various
29371 parties—for example, statements of peer review or that the text has
29372 been approved by an organization as the authoritative definition of a
29373 standard.
29375 You may add a passage of up to five words as a Front-Cover Text, and a
29376 passage of up to 25 words as a Back-Cover Text, to the end of the list
29377 of Cover Texts in the Modified Version.  Only one passage of
29378 Front-Cover Text and one of Back-Cover Text may be added by (or
29379 through arrangements made by) any one entity.  If the Document already
29380 includes a cover text for the same cover, previously added by you or
29381 by arrangement made by the same entity you are acting on behalf of,
29382 you may not add another; but you may replace the old one, on explicit
29383 permission from the previous publisher that added the old one.
29385 The author(s) and publisher(s) of the Document do not by this License
29386 give permission to use their names for publicity for or to assert or
29387 imply endorsement of any Modified Version.
29389 `5. COMBINING DOCUMENTS'
29391 You may combine the Document with other documents released under this
29392 License, under the terms defined in section 4 above for modified
29393 versions, provided that you include in the combination all of the
29394 Invariant Sections of all of the original documents, unmodified, and
29395 list them all as Invariant Sections of your combined work in its
29396 license notice, and that you preserve all their Warranty Disclaimers.
29398 The combined work need only contain one copy of this License, and
29399 multiple identical Invariant Sections may be replaced with a single
29400 copy.  If there are multiple Invariant Sections with the same name but
29401 different contents, make the title of each such section unique by
29402 adding at the end of it, in parentheses, the name of the original
29403 author or publisher of that section if known, or else a unique number.
29404 Make the same adjustment to the section titles in the list of
29405 Invariant Sections in the license notice of the combined work.
29407 In the combination, you must combine any sections Entitled “History”
29408 in the various original documents, forming one section Entitled
29409 “History”; likewise combine any sections Entitled “Acknowledgements”,
29410 and any sections Entitled “Dedications”.  You must delete all sections
29411 Entitled “Endorsements”.
29413 `6. COLLECTIONS OF DOCUMENTS'
29415 You may make a collection consisting of the Document and other documents
29416 released under this License, and replace the individual copies of this
29417 License in the various documents with a single copy that is included in
29418 the collection, provided that you follow the rules of this License for
29419 verbatim copying of each of the documents in all other respects.
29421 You may extract a single document from such a collection, and distribute
29422 it individually under this License, provided you insert a copy of this
29423 License into the extracted document, and follow this License in all
29424 other respects regarding verbatim copying of that document.
29426 `7. AGGREGATION WITH INDEPENDENT WORKS'
29428 A compilation of the Document or its derivatives with other separate
29429 and independent documents or works, in or on a volume of a storage or
29430 distribution medium, is called an “aggregate” if the copyright
29431 resulting from the compilation is not used to limit the legal rights
29432 of the compilation’s users beyond what the individual works permit.
29433 When the Document is included in an aggregate, this License does not
29434 apply to the other works in the aggregate which are not themselves
29435 derivative works of the Document.
29437 If the Cover Text requirement of section 3 is applicable to these
29438 copies of the Document, then if the Document is less than one half of
29439 the entire aggregate, the Document’s Cover Texts may be placed on
29440 covers that bracket the Document within the aggregate, or the
29441 electronic equivalent of covers if the Document is in electronic form.
29442 Otherwise they must appear on printed covers that bracket the whole
29443 aggregate.
29445 `8. TRANSLATION'
29447 Translation is considered a kind of modification, so you may
29448 distribute translations of the Document under the terms of section 4.
29449 Replacing Invariant Sections with translations requires special
29450 permission from their copyright holders, but you may include
29451 translations of some or all Invariant Sections in addition to the
29452 original versions of these Invariant Sections.  You may include a
29453 translation of this License, and all the license notices in the
29454 Document, and any Warranty Disclaimers, provided that you also include
29455 the original English version of this License and the original versions
29456 of those notices and disclaimers.  In case of a disagreement between
29457 the translation and the original version of this License or a notice
29458 or disclaimer, the original version will prevail.
29460 If a section in the Document is Entitled “Acknowledgements”,
29461 “Dedications”, or “History”, the requirement (section 4) to Preserve
29462 its Title (section 1) will typically require changing the actual
29463 title.
29465 `9. TERMINATION'
29467 You may not copy, modify, sublicense, or distribute the Document
29468 except as expressly provided under this License.  Any attempt
29469 otherwise to copy, modify, sublicense, or distribute it is void, and
29470 will automatically terminate your rights under this License.
29472 However, if you cease all violation of this License, then your license
29473 from a particular copyright holder is reinstated (a) provisionally,
29474 unless and until the copyright holder explicitly and finally
29475 terminates your license, and (b) permanently, if the copyright holder
29476 fails to notify you of the violation by some reasonable means prior to
29477 60 days after the cessation.
29479 Moreover, your license from a particular copyright holder is
29480 reinstated permanently if the copyright holder notifies you of the
29481 violation by some reasonable means, this is the first time you have
29482 received notice of violation of this License (for any work) from that
29483 copyright holder, and you cure the violation prior to 30 days after
29484 your receipt of the notice.
29486 Termination of your rights under this section does not terminate the
29487 licenses of parties who have received copies or rights from you under
29488 this License.  If your rights have been terminated and not permanently
29489 reinstated, receipt of a copy of some or all of the same material does
29490 not give you any rights to use it.
29492 `10. FUTURE REVISIONS OF THIS LICENSE'
29494 The Free Software Foundation may publish new, revised versions
29495 of the GNU Free Documentation License from time to time.  Such new
29496 versions will be similar in spirit to the present version, but may
29497 differ in detail to address new problems or concerns.  See
29498 @indicateurl{https://www.gnu.org/copyleft/}.
29500 Each version of the License is given a distinguishing version number.
29501 If the Document specifies that a particular numbered version of this
29502 License “or any later version” applies to it, you have the option of
29503 following the terms and conditions either of that specified version or
29504 of any later version that has been published (not as a draft) by the
29505 Free Software Foundation.  If the Document does not specify a version
29506 number of this License, you may choose any version ever published (not
29507 as a draft) by the Free Software Foundation.  If the Document
29508 specifies that a proxy can decide which future versions of this
29509 License can be used, that proxy’s public statement of acceptance of a
29510 version permanently authorizes you to choose that version for the
29511 Document.
29513 `11. RELICENSING'
29515 “Massive Multiauthor Collaboration Site” (or “MMC Site”) means any
29516 World Wide Web server that publishes copyrightable works and also
29517 provides prominent facilities for anybody to edit those works.  A
29518 public wiki that anybody can edit is an example of such a server.  A
29519 “Massive Multiauthor Collaboration” (or “MMC”) contained in the
29520 site means any set of copyrightable works thus published on the MMC
29521 site.
29523 “CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0
29524 license published by Creative Commons Corporation, a not-for-profit
29525 corporation with a principal place of business in San Francisco,
29526 California, as well as future copyleft versions of that license
29527 published by that same organization.
29529 “Incorporate” means to publish or republish a Document, in whole or
29530 in part, as part of another Document.
29532 An MMC is “eligible for relicensing” if it is licensed under this
29533 License, and if all works that were first published under this License
29534 somewhere other than this MMC, and subsequently incorporated in whole
29535 or in part into the MMC, (1) had no cover texts or invariant sections,
29536 and (2) were thus incorporated prior to November 1, 2008.
29538 The operator of an MMC Site may republish an MMC contained in the site
29539 under CC-BY-SA on the same site at any time before August 1, 2009,
29540 provided the MMC is eligible for relicensing.
29542 `ADDENDUM: How to use this License for your documents'
29544 To use this License in a document you have written, include a copy of
29545 the License in the document and put the following copyright and
29546 license notices just after the title page:
29548 @quotation
29550 Copyright © YEAR  YOUR NAME.
29551 Permission is granted to copy, distribute and/or modify this document
29552 under the terms of the GNU Free Documentation License, Version 1.3
29553 or any later version published by the Free Software Foundation;
29554 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
29555 A copy of the license is included in the section entitled “GNU
29556 Free Documentation License”.
29557 @end quotation
29559 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
29560 replace the “with … Texts.” line with this:
29562 @quotation
29564 with the Invariant Sections being LIST THEIR TITLES, with the
29565 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
29566 @end quotation
29568 If you have Invariant Sections without Cover Texts, or some other
29569 combination of the three, merge those two alternatives to suit the
29570 situation.
29572 If your document contains nontrivial examples of program code, we
29573 recommend releasing these examples in parallel under your choice of
29574 free software license, such as the GNU General Public License,
29575 to permit their use in free software.
29577 @node Index,,GNU Free Documentation License,Top
29578 @unnumbered Index
29581 @printindex ge
29583 @anchor{d1}@w{                              }
29584 @anchor{gnat_ugn/gnat_utility_programs switches-related-to-project-files}@w{                              }
29586 @c %**end of body
29587 @bye